@kubb/plugin-zod 5.0.0-alpha.24 → 5.0.0-alpha.26

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 (47) hide show
  1. package/dist/index.cjs +1673 -88
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.ts +317 -2
  4. package/dist/index.js +1646 -88
  5. package/dist/index.js.map +1 -1
  6. package/package.json +5 -33
  7. package/src/components/Operations.tsx +22 -15
  8. package/src/components/Zod.tsx +18 -118
  9. package/src/components/ZodMini.tsx +41 -0
  10. package/src/constants.ts +5 -0
  11. package/src/generators/zodGenerator.tsx +165 -158
  12. package/src/generators/zodGeneratorLegacy.tsx +401 -0
  13. package/src/index.ts +11 -1
  14. package/src/plugin.ts +105 -129
  15. package/src/presets.ts +25 -0
  16. package/src/printers/printerZod.ts +271 -0
  17. package/src/printers/printerZodMini.ts +246 -0
  18. package/src/resolvers/resolverZod.ts +71 -0
  19. package/src/resolvers/resolverZodLegacy.ts +60 -0
  20. package/src/types.ts +121 -92
  21. package/src/utils.ts +248 -0
  22. package/dist/components-DW4Q2yVq.js +0 -868
  23. package/dist/components-DW4Q2yVq.js.map +0 -1
  24. package/dist/components-qFUGs0vU.cjs +0 -916
  25. package/dist/components-qFUGs0vU.cjs.map +0 -1
  26. package/dist/components.cjs +0 -4
  27. package/dist/components.d.ts +0 -56
  28. package/dist/components.js +0 -2
  29. package/dist/generators-C9BCTLXg.cjs +0 -301
  30. package/dist/generators-C9BCTLXg.cjs.map +0 -1
  31. package/dist/generators-maqx12yN.js +0 -290
  32. package/dist/generators-maqx12yN.js.map +0 -1
  33. package/dist/generators.cjs +0 -4
  34. package/dist/generators.d.ts +0 -12
  35. package/dist/generators.js +0 -2
  36. package/dist/templates/ToZod.source.cjs +0 -7
  37. package/dist/templates/ToZod.source.cjs.map +0 -1
  38. package/dist/templates/ToZod.source.d.ts +0 -7
  39. package/dist/templates/ToZod.source.js +0 -6
  40. package/dist/templates/ToZod.source.js.map +0 -1
  41. package/dist/types-CClg-ikj.d.ts +0 -172
  42. package/src/components/index.ts +0 -2
  43. package/src/generators/index.ts +0 -2
  44. package/src/generators/operationsGenerator.tsx +0 -50
  45. package/src/parser.ts +0 -952
  46. package/src/templates/ToZod.source.ts +0 -4
  47. package/templates/ToZod.ts +0 -61
@@ -1,916 +0,0 @@
1
- //#region \0rolldown/runtime.js
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __name = (target, value) => __defProp(target, "name", {
5
- value,
6
- configurable: true
7
- });
8
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
- var __getOwnPropNames = Object.getOwnPropertyNames;
10
- var __getProtoOf = Object.getPrototypeOf;
11
- var __hasOwnProp = Object.prototype.hasOwnProperty;
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
- key = keys[i];
15
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
- get: ((k) => from[k]).bind(null, key),
17
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
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
- //#endregion
27
- let _kubb_plugin_oas = require("@kubb/plugin-oas");
28
- let _kubb_react_fabric = require("@kubb/react-fabric");
29
- let _kubb_react_fabric_jsx_runtime = require("@kubb/react-fabric/jsx-runtime");
30
- let remeda = require("remeda");
31
- //#region ../../internals/utils/src/string.ts
32
- /**
33
- * Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
34
- * Returns the string unchanged when no balanced quote pair is found.
35
- *
36
- * @example
37
- * trimQuotes('"hello"') // 'hello'
38
- * trimQuotes('hello') // 'hello'
39
- */
40
- function trimQuotes(text) {
41
- if (text.length >= 2) {
42
- const first = text[0];
43
- const last = text[text.length - 1];
44
- if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
45
- }
46
- return text;
47
- }
48
- /**
49
- * Escapes characters that are not allowed inside JS string literals.
50
- * Handles quotes, backslashes, and Unicode line terminators (U+2028 / U+2029).
51
- *
52
- * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
53
- *
54
- * @example
55
- * ```ts
56
- * jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
57
- * ```
58
- */
59
- function jsStringEscape(input) {
60
- return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
61
- switch (character) {
62
- case "\"":
63
- case "'":
64
- case "\\": return `\\${character}`;
65
- case "\n": return "\\n";
66
- case "\r": return "\\r";
67
- case "\u2028": return "\\u2028";
68
- case "\u2029": return "\\u2029";
69
- default: return "";
70
- }
71
- });
72
- }
73
- //#endregion
74
- //#region ../../internals/utils/src/object.ts
75
- /**
76
- * Serializes a primitive value to a JSON string literal, stripping any surrounding quote characters first.
77
- *
78
- * @example
79
- * stringify('hello') // '"hello"'
80
- * stringify('"hello"') // '"hello"'
81
- */
82
- function stringify(value) {
83
- if (value === void 0 || value === null) return "\"\"";
84
- return JSON.stringify(trimQuotes(value.toString()));
85
- }
86
- /**
87
- * Converts a plain object into a multiline key-value string suitable for embedding in generated code.
88
- * Nested objects are recursively stringified with indentation.
89
- *
90
- * @example
91
- * stringifyObject({ foo: 'bar', nested: { a: 1 } })
92
- * // 'foo: bar,\nnested: {\n a: 1\n }'
93
- */
94
- function stringifyObject(value) {
95
- return Object.entries(value).map(([key, val]) => {
96
- if (val !== null && typeof val === "object") return `${key}: {\n ${stringifyObject(val)}\n }`;
97
- return `${key}: ${val}`;
98
- }).filter(Boolean).join(",\n");
99
- }
100
- //#endregion
101
- //#region ../../internals/utils/src/regexp.ts
102
- /**
103
- * Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
104
- * Inline flags expressed as `^(?im)` prefixes are extracted and applied to the resulting expression.
105
- * Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
106
- *
107
- * @example
108
- * toRegExpString('^(?im)foo') // → 'new RegExp("foo", "im")'
109
- * toRegExpString('^(?im)foo', null) // → '/foo/im'
110
- */
111
- function toRegExpString(text, func = "RegExp") {
112
- const raw = trimQuotes(text);
113
- const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i);
114
- const replacementTarget = match?.[1] ?? "";
115
- const matchedFlags = match?.[2];
116
- const cleaned = raw.replace(/^\\?\//, "").replace(/\\?\/$/, "").replace(replacementTarget, "");
117
- const { source, flags } = new RegExp(cleaned, matchedFlags);
118
- if (func === null) return `/${source}/${flags}`;
119
- return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ""})`;
120
- }
121
- //#endregion
122
- //#region src/components/Operations.tsx
123
- function Operations({ name, operations }) {
124
- const operationsJSON = operations.reduce((prev, acc) => {
125
- prev[`"${acc.operation.getOperationId()}"`] = acc.data;
126
- return prev;
127
- }, {});
128
- const pathsJSON = operations.reduce((prev, acc) => {
129
- prev[`"${acc.operation.path}"`] = {
130
- ...prev[`"${acc.operation.path}"`] || {},
131
- [acc.operation.method]: `operations["${acc.operation.getOperationId()}"]`
132
- };
133
- return prev;
134
- }, {});
135
- return /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsxs)(_kubb_react_fabric_jsx_runtime.Fragment, { children: [
136
- /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
137
- name: "OperationSchema",
138
- isExportable: true,
139
- isIndexable: true,
140
- children: /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Type, {
141
- name: "OperationSchema",
142
- export: true,
143
- children: `{
144
- readonly request: z.ZodTypeAny | undefined;
145
- readonly parameters: {
146
- readonly path: z.ZodTypeAny | undefined;
147
- readonly query: z.ZodTypeAny | undefined;
148
- readonly header: z.ZodTypeAny | undefined;
149
- };
150
- readonly responses: {
151
- readonly [status: number]: z.ZodTypeAny;
152
- readonly default: z.ZodTypeAny;
153
- };
154
- readonly errors: {
155
- readonly [status: number]: z.ZodTypeAny;
156
- };
157
- }`
158
- })
159
- }),
160
- /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
161
- name: "OperationsMap",
162
- isExportable: true,
163
- isIndexable: true,
164
- children: /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Type, {
165
- name: "OperationsMap",
166
- export: true,
167
- children: "Record<string, OperationSchema>"
168
- })
169
- }),
170
- /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
171
- name,
172
- isExportable: true,
173
- isIndexable: true,
174
- children: /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Const, {
175
- export: true,
176
- name,
177
- asConst: true,
178
- children: `{${stringifyObject(operationsJSON)}}`
179
- })
180
- }),
181
- /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
182
- name: "paths",
183
- isExportable: true,
184
- isIndexable: true,
185
- children: /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Const, {
186
- export: true,
187
- name: "paths",
188
- asConst: true,
189
- children: `{${stringifyObject(pathsJSON)}}`
190
- })
191
- })
192
- ] });
193
- }
194
- //#endregion
195
- //#region src/parser.ts
196
- /**
197
- * Helper to build string/array length constraint checks for Zod Mini mode
198
- */
199
- function buildLengthChecks(min, max) {
200
- const checks = [];
201
- if (min !== void 0) checks.push(`z.minLength(${min})`);
202
- if (max !== void 0) checks.push(`z.maxLength(${max})`);
203
- return checks;
204
- }
205
- const zodKeywordMapper = {
206
- any: () => "z.any()",
207
- unknown: () => "z.unknown()",
208
- void: () => "z.void()",
209
- number: (coercion, min, max, exclusiveMinimum, exclusiveMaximum, mini) => {
210
- if (mini) {
211
- const checks = [];
212
- if (min !== void 0) checks.push(`z.minimum(${min})`);
213
- if (max !== void 0) checks.push(`z.maximum(${max})`);
214
- if (exclusiveMinimum !== void 0) checks.push(`z.minimum(${exclusiveMinimum}, { exclusive: true })`);
215
- if (exclusiveMaximum !== void 0) checks.push(`z.maximum(${exclusiveMaximum}, { exclusive: true })`);
216
- if (checks.length > 0) return `z.number().check(${checks.join(", ")})`;
217
- return "z.number()";
218
- }
219
- return [
220
- coercion ? "z.coerce.number()" : "z.number()",
221
- min !== void 0 ? `.min(${min})` : void 0,
222
- max !== void 0 ? `.max(${max})` : void 0,
223
- exclusiveMinimum !== void 0 ? `.gt(${exclusiveMinimum})` : void 0,
224
- exclusiveMaximum !== void 0 ? `.lt(${exclusiveMaximum})` : void 0
225
- ].filter(Boolean).join("");
226
- },
227
- integer: (coercion, min, max, version = "3", exclusiveMinimum, exclusiveMaximum, mini) => {
228
- if (mini) {
229
- const checks = [];
230
- if (min !== void 0) checks.push(`z.minimum(${min})`);
231
- if (max !== void 0) checks.push(`z.maximum(${max})`);
232
- if (exclusiveMinimum !== void 0) checks.push(`z.minimum(${exclusiveMinimum}, { exclusive: true })`);
233
- if (exclusiveMaximum !== void 0) checks.push(`z.maximum(${exclusiveMaximum}, { exclusive: true })`);
234
- if (checks.length > 0) return `z.int().check(${checks.join(", ")})`;
235
- return "z.int()";
236
- }
237
- return [
238
- coercion ? "z.coerce.number().int()" : version === "4" ? "z.int()" : "z.number().int()",
239
- min !== void 0 ? `.min(${min})` : void 0,
240
- max !== void 0 ? `.max(${max})` : void 0,
241
- exclusiveMinimum !== void 0 ? `.gt(${exclusiveMinimum})` : void 0,
242
- exclusiveMaximum !== void 0 ? `.lt(${exclusiveMaximum})` : void 0
243
- ].filter(Boolean).join("");
244
- },
245
- bigint: (coercion) => coercion ? "z.coerce.bigint()" : "z.bigint()",
246
- interface: (value, strict) => {
247
- if (strict) return `z.strictInterface({
248
- ${value}
249
- })`;
250
- return `z.interface({
251
- ${value}
252
- })`;
253
- },
254
- object: (value, strict, version = "3") => {
255
- if (version === "4" && strict) return `z.strictObject({
256
- ${value}
257
- })`;
258
- if (strict) return `z.object({
259
- ${value}
260
- }).strict()`;
261
- return `z.object({
262
- ${value}
263
- })`;
264
- },
265
- string: (coercion, min, max, mini) => {
266
- if (mini) {
267
- const checks = buildLengthChecks(min, max);
268
- if (checks.length > 0) return `z.string().check(${checks.join(", ")})`;
269
- return "z.string()";
270
- }
271
- return [
272
- coercion ? "z.coerce.string()" : "z.string()",
273
- min !== void 0 ? `.min(${min})` : void 0,
274
- max !== void 0 ? `.max(${max})` : void 0
275
- ].filter(Boolean).join("");
276
- },
277
- boolean: () => "z.boolean()",
278
- undefined: () => "z.undefined()",
279
- nullable: (value) => {
280
- if (value) return `z.nullable(${value})`;
281
- return ".nullable()";
282
- },
283
- null: () => "z.null()",
284
- nullish: (value) => {
285
- if (value) return `z.nullish(${value})`;
286
- return ".nullish()";
287
- },
288
- array: (items = [], min, max, unique, mini) => {
289
- if (mini) {
290
- const checks = buildLengthChecks(min, max);
291
- if (unique) checks.push(`z.refine(items => new Set(items).size === items.length, { message: "Array entries must be unique" })`);
292
- if (checks.length > 0) return `z.array(${items?.join("")}).check(${checks.join(", ")})`;
293
- return `z.array(${items?.join("")})`;
294
- }
295
- return [
296
- `z.array(${items?.join("")})`,
297
- min !== void 0 ? `.min(${min})` : void 0,
298
- max !== void 0 ? `.max(${max})` : void 0,
299
- unique ? `.refine(items => new Set(items).size === items.length, { message: "Array entries must be unique" })` : void 0
300
- ].filter(Boolean).join("");
301
- },
302
- tuple: (items = []) => `z.tuple([${items?.join(", ")}])`,
303
- enum: (items = []) => `z.enum([${items?.join(", ")}])`,
304
- union: (items = []) => `z.union([${items?.join(", ")}])`,
305
- const: (value) => `z.literal(${value ?? ""})`,
306
- datetime: (offset = false, local = false, version = "3", mini) => {
307
- if (mini) return "z.string()";
308
- if (offset) return version === "4" ? `z.iso.datetime({ offset: ${offset} })` : `z.string().datetime({ offset: ${offset} })`;
309
- if (local) return version === "4" ? `z.iso.datetime({ local: ${local} })` : `z.string().datetime({ local: ${local} })`;
310
- return version === "4" ? "z.iso.datetime()" : "z.string().datetime()";
311
- },
312
- date: (type = "string", coercion, version = "3") => {
313
- if (type === "string") return version === "4" ? "z.iso.date()" : "z.string().date()";
314
- if (coercion) return "z.coerce.date()";
315
- return "z.date()";
316
- },
317
- time: (type = "string", coercion, version = "3") => {
318
- if (type === "string") return version === "4" ? "z.iso.time()" : "z.string().time()";
319
- if (coercion) return "z.coerce.date()";
320
- return "z.date()";
321
- },
322
- uuid: ({ coercion, version = "3", guidType = "uuid", min, max, mini } = {}) => {
323
- const zodGuidType = version === "4" && guidType === "guid" ? "guid" : "uuid";
324
- if (mini) {
325
- const checks = buildLengthChecks(min, max);
326
- if (checks.length > 0) return `z.${zodGuidType}().check(${checks.join(", ")})`;
327
- return `z.${zodGuidType}()`;
328
- }
329
- const zodV4UuidSchema = `z.${zodGuidType}()`;
330
- return [
331
- coercion ? version === "4" ? zodV4UuidSchema : "z.coerce.string().uuid()" : version === "4" ? zodV4UuidSchema : "z.string().uuid()",
332
- min !== void 0 ? `.min(${min})` : void 0,
333
- max !== void 0 ? `.max(${max})` : void 0
334
- ].filter(Boolean).join("");
335
- },
336
- url: (coercion, version = "3", min, max, mini) => {
337
- if (mini) {
338
- const checks = buildLengthChecks(min, max);
339
- if (checks.length > 0) return `z.url().check(${checks.join(", ")})`;
340
- return "z.url()";
341
- }
342
- return [
343
- coercion ? version === "4" ? "z.url()" : "z.coerce.string().url()" : version === "4" ? "z.url()" : "z.string().url()",
344
- min !== void 0 ? `.min(${min})` : void 0,
345
- max !== void 0 ? `.max(${max})` : void 0
346
- ].filter(Boolean).join("");
347
- },
348
- default: (value, innerSchema, mini, isBigInt) => {
349
- if (mini && innerSchema) return `z._default(${innerSchema}, ${isBigInt && typeof value === "number" ? `BigInt(${value})` : typeof value === "object" ? "{}" : value ?? ""})`;
350
- if (typeof value === "object") return ".default({})";
351
- if (value === void 0) return ".default()";
352
- if (typeof value === "string" && !value) return `.default('')`;
353
- if (isBigInt && typeof value === "number") return `.default(BigInt(${value}))`;
354
- return `.default(${value ?? ""})`;
355
- },
356
- and: (items = [], mini) => {
357
- if (mini && items.length > 0) {
358
- const checks = [];
359
- for (const item of items) {
360
- const checkStart = item.indexOf(".check(");
361
- if (checkStart !== -1) {
362
- let depth = 0;
363
- let i = checkStart + 7;
364
- let checkContent = "";
365
- while (i < item.length) {
366
- const char = item[i];
367
- if (char === "(") depth++;
368
- else if (char === ")") {
369
- if (depth === 0) break;
370
- depth--;
371
- }
372
- checkContent += char;
373
- i++;
374
- }
375
- if (checkContent) checks.push(checkContent);
376
- }
377
- }
378
- if (checks.length > 0) return `.check(${checks.join(", ")})`;
379
- return "";
380
- }
381
- return items?.map((item) => `.and(${item})`).join("");
382
- },
383
- describe: (value = "", innerSchema, mini) => {
384
- if (mini) return;
385
- if (innerSchema) return `z.describe(${innerSchema}, ${value})`;
386
- return `.describe(${value})`;
387
- },
388
- max: void 0,
389
- min: void 0,
390
- optional: (value) => {
391
- if (value) return `z.optional(${value})`;
392
- return ".optional()";
393
- },
394
- matches: (value = "", coercion, mini, min, max) => {
395
- if (mini) {
396
- const checks = buildLengthChecks(min, max);
397
- checks.push(`z.regex(${value})`);
398
- return `z.string().check(${checks.join(", ")})`;
399
- }
400
- return [
401
- coercion ? "z.coerce.string()" : "z.string()",
402
- min !== void 0 ? `.min(${min})` : void 0,
403
- max !== void 0 ? `.max(${max})` : void 0,
404
- `.regex(${value})`
405
- ].filter(Boolean).join("");
406
- },
407
- email: (coercion, version = "3", min, max, mini) => {
408
- if (mini) {
409
- const checks = buildLengthChecks(min, max);
410
- if (checks.length > 0) return `z.email().check(${checks.join(", ")})`;
411
- return "z.email()";
412
- }
413
- return [
414
- coercion ? version === "4" ? "z.email()" : "z.coerce.string().email()" : version === "4" ? "z.email()" : "z.string().email()",
415
- min !== void 0 ? `.min(${min})` : void 0,
416
- max !== void 0 ? `.max(${max})` : void 0
417
- ].filter(Boolean).join("");
418
- },
419
- firstName: void 0,
420
- lastName: void 0,
421
- password: void 0,
422
- phone: void 0,
423
- readOnly: void 0,
424
- writeOnly: void 0,
425
- ref: (value) => {
426
- if (!value) return;
427
- return `z.lazy(() => ${value})`;
428
- },
429
- blob: () => "z.instanceof(File)",
430
- deprecated: void 0,
431
- example: void 0,
432
- schema: void 0,
433
- catchall: (value, mini) => {
434
- if (mini) return;
435
- return value ? `.catchall(${value})` : void 0;
436
- },
437
- name: void 0,
438
- exclusiveMinimum: void 0,
439
- exclusiveMaximum: void 0
440
- };
441
- /**
442
- * @link based on https://github.com/cellular/oazapfts/blob/7ba226ebb15374e8483cc53e7532f1663179a22c/src/codegen/generate.ts#L398
443
- */
444
- function sort(items) {
445
- const order = [
446
- _kubb_plugin_oas.schemaKeywords.string,
447
- _kubb_plugin_oas.schemaKeywords.datetime,
448
- _kubb_plugin_oas.schemaKeywords.date,
449
- _kubb_plugin_oas.schemaKeywords.time,
450
- _kubb_plugin_oas.schemaKeywords.tuple,
451
- _kubb_plugin_oas.schemaKeywords.number,
452
- _kubb_plugin_oas.schemaKeywords.object,
453
- _kubb_plugin_oas.schemaKeywords.enum,
454
- _kubb_plugin_oas.schemaKeywords.url,
455
- _kubb_plugin_oas.schemaKeywords.email,
456
- _kubb_plugin_oas.schemaKeywords.firstName,
457
- _kubb_plugin_oas.schemaKeywords.lastName,
458
- _kubb_plugin_oas.schemaKeywords.password,
459
- _kubb_plugin_oas.schemaKeywords.matches,
460
- _kubb_plugin_oas.schemaKeywords.uuid,
461
- _kubb_plugin_oas.schemaKeywords.null,
462
- _kubb_plugin_oas.schemaKeywords.min,
463
- _kubb_plugin_oas.schemaKeywords.max,
464
- _kubb_plugin_oas.schemaKeywords.default,
465
- _kubb_plugin_oas.schemaKeywords.describe,
466
- _kubb_plugin_oas.schemaKeywords.optional,
467
- _kubb_plugin_oas.schemaKeywords.nullable,
468
- _kubb_plugin_oas.schemaKeywords.nullish
469
- ];
470
- if (!items) return [];
471
- return (0, remeda.sortBy)(items, [(v) => order.indexOf(v.keyword), "asc"]);
472
- }
473
- /**
474
- * Keywords that represent modifiers for mini mode
475
- * These are separated from the base schema and wrapped around it
476
- * Note: describe is included to filter it out, but won't be wrapped (Zod Mini doesn't support describe)
477
- */
478
- const miniModifierKeywords = [
479
- _kubb_plugin_oas.schemaKeywords.optional,
480
- _kubb_plugin_oas.schemaKeywords.nullable,
481
- _kubb_plugin_oas.schemaKeywords.nullish,
482
- _kubb_plugin_oas.schemaKeywords.default,
483
- _kubb_plugin_oas.schemaKeywords.describe
484
- ];
485
- /**
486
- * Extracts mini mode modifiers from a schemas array
487
- * This can be reused by other parsers (e.g., valibot) that need similar functionality
488
- * Note: describe is not included as Zod Mini doesn't support it
489
- */
490
- function extractMiniModifiers(schemas) {
491
- const defaultSchema = schemas.find((item) => (0, _kubb_plugin_oas.isKeyword)(item, _kubb_plugin_oas.schemaKeywords.default));
492
- const isBigInt = schemas.some((item) => (0, _kubb_plugin_oas.isKeyword)(item, _kubb_plugin_oas.schemaKeywords.bigint));
493
- let defaultValue = defaultSchema?.args;
494
- if (defaultValue !== void 0) {
495
- const enumSchema = schemas.find((it) => (0, _kubb_plugin_oas.isKeyword)(it, _kubb_plugin_oas.schemaKeywords.enum));
496
- if (enumSchema) {
497
- let rawDefault = defaultValue;
498
- if (typeof rawDefault === "string") try {
499
- rawDefault = JSON.parse(rawDefault);
500
- } catch {}
501
- if (!enumSchema.args.items.map((item) => item.value ?? item.name).includes(rawDefault)) defaultValue = void 0;
502
- }
503
- }
504
- return {
505
- hasOptional: schemas.some((item) => (0, _kubb_plugin_oas.isKeyword)(item, _kubb_plugin_oas.schemaKeywords.optional)),
506
- hasNullable: schemas.some((item) => (0, _kubb_plugin_oas.isKeyword)(item, _kubb_plugin_oas.schemaKeywords.nullable)),
507
- hasNullish: schemas.some((item) => (0, _kubb_plugin_oas.isKeyword)(item, _kubb_plugin_oas.schemaKeywords.nullish)),
508
- defaultValue,
509
- isBigInt
510
- };
511
- }
512
- /**
513
- * Filters out modifier keywords from schemas for mini mode base schema parsing
514
- * This can be reused by other parsers (e.g., valibot) that need similar functionality
515
- */
516
- function filterMiniModifiers(schemas) {
517
- return schemas.filter((item) => !miniModifierKeywords.some((keyword) => (0, _kubb_plugin_oas.isKeyword)(item, keyword)));
518
- }
519
- /**
520
- * Wraps an output string with Zod Mini functional modifiers
521
- * Order: default (innermost) -> nullable -> optional (outermost)
522
- * OR: default -> nullish
523
- * Note: describe is not supported in Zod Mini and is skipped
524
- */
525
- function wrapWithMiniModifiers(output, modifiers) {
526
- let result = output;
527
- if (modifiers.defaultValue !== void 0) result = zodKeywordMapper.default(modifiers.defaultValue, result, true, modifiers.isBigInt);
528
- if (modifiers.hasNullish) result = zodKeywordMapper.nullish(result);
529
- else {
530
- if (modifiers.hasNullable) result = zodKeywordMapper.nullable(result);
531
- if (modifiers.hasOptional) result = zodKeywordMapper.optional(result);
532
- }
533
- return result;
534
- }
535
- const shouldCoerce = (coercion, type) => {
536
- if (coercion === void 0) return false;
537
- if (typeof coercion === "boolean") return coercion;
538
- return !!coercion[type];
539
- };
540
- const parse = (0, _kubb_plugin_oas.createParser)({
541
- mapper: zodKeywordMapper,
542
- handlers: {
543
- union(tree, options) {
544
- const { current, schema, parent, name, siblings } = tree;
545
- if (Array.isArray(current.args) && current.args.length === 1) return this.parse({
546
- schema,
547
- parent,
548
- name,
549
- current: current.args[0],
550
- siblings
551
- }, options);
552
- if (Array.isArray(current.args) && !current.args.length) return "";
553
- return zodKeywordMapper.union(sort(current.args).map((it, _index, siblings) => this.parse({
554
- schema,
555
- parent: current,
556
- name,
557
- current: it,
558
- siblings
559
- }, options)).filter(Boolean));
560
- },
561
- and(tree, options) {
562
- const { current, schema, name } = tree;
563
- const items = sort(current.args).filter((schema) => {
564
- return ![_kubb_plugin_oas.schemaKeywords.optional, _kubb_plugin_oas.schemaKeywords.describe].includes(schema.keyword);
565
- }).map((it, _index, siblings) => this.parse({
566
- schema,
567
- parent: current,
568
- name,
569
- current: it,
570
- siblings
571
- }, options)).filter(Boolean);
572
- return `${items.slice(0, 1)}${zodKeywordMapper.and(items.slice(1), options.mini)}`;
573
- },
574
- array(tree, options) {
575
- const { current, schema, name } = tree;
576
- return zodKeywordMapper.array(sort(current.args.items).map((it, _index, siblings) => {
577
- return this.parse({
578
- schema,
579
- parent: current,
580
- name,
581
- current: it,
582
- siblings
583
- }, options);
584
- }).filter(Boolean), current.args.min, current.args.max, current.args.unique, options.mini);
585
- },
586
- enum(tree, options) {
587
- const { current, schema, name } = tree;
588
- if (current.args.asConst) {
589
- if (current.args.items.length === 1) {
590
- const child = {
591
- keyword: _kubb_plugin_oas.schemaKeywords.const,
592
- args: current.args.items[0]
593
- };
594
- return this.parse({
595
- schema,
596
- parent: current,
597
- name,
598
- current: child,
599
- siblings: [child]
600
- }, options);
601
- }
602
- return zodKeywordMapper.union(current.args.items.map((schema) => ({
603
- keyword: _kubb_plugin_oas.schemaKeywords.const,
604
- args: schema
605
- })).map((it, _index, siblings) => {
606
- return this.parse({
607
- schema,
608
- parent: current,
609
- name,
610
- current: it,
611
- siblings
612
- }, options);
613
- }).filter(Boolean));
614
- }
615
- return zodKeywordMapper.enum(current.args.items.map((schema) => {
616
- if (schema.format === "boolean") return stringify(schema.value);
617
- if (schema.format === "number") return stringify(schema.value);
618
- return stringify(schema.value);
619
- }));
620
- },
621
- ref(tree, options) {
622
- const { current } = tree;
623
- if (options.skipLazyForRefs) return current.args?.name;
624
- return zodKeywordMapper.ref(current.args?.name);
625
- },
626
- object(tree, options) {
627
- const { current, schema, name } = tree;
628
- const properties = Object.entries(current.args?.properties || {}).filter((item) => {
629
- const schema = item[1];
630
- return schema && typeof schema.map === "function";
631
- }).map(([propertyName, schemas]) => {
632
- const nameSchema = schemas.find((it) => it.keyword === _kubb_plugin_oas.schemaKeywords.name);
633
- const isNullable = schemas.some((it) => (0, _kubb_plugin_oas.isKeyword)(it, _kubb_plugin_oas.schemaKeywords.nullable));
634
- const isNullish = schemas.some((it) => (0, _kubb_plugin_oas.isKeyword)(it, _kubb_plugin_oas.schemaKeywords.nullish));
635
- const isOptional = schemas.some((it) => (0, _kubb_plugin_oas.isKeyword)(it, _kubb_plugin_oas.schemaKeywords.optional));
636
- const hasRef = !!_kubb_plugin_oas.SchemaGenerator.find(schemas, _kubb_plugin_oas.schemaKeywords.ref);
637
- const mappedName = nameSchema?.args || propertyName;
638
- if (options.mapper && Object.hasOwn(options.mapper, mappedName)) return `"${propertyName}": ${options.mapper?.[mappedName]}`;
639
- const baseSchemaOutput = sort(schemas).filter((schema) => {
640
- return !(0, _kubb_plugin_oas.isKeyword)(schema, _kubb_plugin_oas.schemaKeywords.optional) && !(0, _kubb_plugin_oas.isKeyword)(schema, _kubb_plugin_oas.schemaKeywords.nullable) && !(0, _kubb_plugin_oas.isKeyword)(schema, _kubb_plugin_oas.schemaKeywords.nullish);
641
- }).map((it) => {
642
- const skipLazyForRefs = options.version === "4" && hasRef;
643
- return this.parse({
644
- schema,
645
- parent: current,
646
- name,
647
- current: it,
648
- siblings: schemas
649
- }, {
650
- ...options,
651
- skipLazyForRefs
652
- });
653
- }).filter(Boolean).join("");
654
- const objectValue = options.wrapOutput ? options.wrapOutput({
655
- output: baseSchemaOutput,
656
- schema: schema?.properties?.[propertyName]
657
- }) || baseSchemaOutput : baseSchemaOutput;
658
- if (options.version === "4" && hasRef) {
659
- if (options.mini) {
660
- if (isNullish) return `get "${propertyName}"(){
661
- return ${zodKeywordMapper.nullish(objectValue)}
662
- }`;
663
- if (isOptional) return `get "${propertyName}"(){
664
- return ${zodKeywordMapper.optional(objectValue)}
665
- }`;
666
- if (isNullable) return `get "${propertyName}"(){
667
- return ${zodKeywordMapper.nullable(objectValue)}
668
- }`;
669
- return `get "${propertyName}"(){
670
- return ${objectValue}
671
- }`;
672
- }
673
- if (isNullish) return `get "${propertyName}"(){
674
- return ${objectValue}${zodKeywordMapper.nullish()}
675
- }`;
676
- if (isOptional) return `get "${propertyName}"(){
677
- return ${objectValue}${zodKeywordMapper.optional()}
678
- }`;
679
- if (isNullable) return `get "${propertyName}"(){
680
- return ${objectValue}${zodKeywordMapper.nullable()}
681
- }`;
682
- return `get "${propertyName}"(){
683
- return ${objectValue}
684
- }`;
685
- }
686
- if (isNullish && options.mini) return `"${propertyName}": ${zodKeywordMapper.nullish(objectValue)}`;
687
- if (isNullish && !options.mini) return `"${propertyName}": ${objectValue}${zodKeywordMapper.nullish()}`;
688
- if (isOptional) return `"${propertyName}": ${zodKeywordMapper.optional(objectValue)}`;
689
- if (isNullable) return `"${propertyName}": ${zodKeywordMapper.nullable(objectValue)}`;
690
- return `"${propertyName}": ${objectValue}`;
691
- }).join(",\n");
692
- const additionalProperties = current.args?.additionalProperties?.length ? current.args.additionalProperties.map((it, _index, siblings) => this.parse({
693
- schema,
694
- parent: current,
695
- name,
696
- current: it,
697
- siblings
698
- }, options)).filter(Boolean).join("") : void 0;
699
- return [zodKeywordMapper.object(properties, current.args?.strict, options.version), additionalProperties ? zodKeywordMapper.catchall(additionalProperties, options.mini) : void 0].filter(Boolean).join("");
700
- },
701
- tuple(tree, options) {
702
- const { current, schema, name } = tree;
703
- return zodKeywordMapper.tuple(current.args.items.map((it, _index, siblings) => this.parse({
704
- schema,
705
- parent: current,
706
- name,
707
- current: it,
708
- siblings
709
- }, options)).filter(Boolean));
710
- },
711
- const(tree, _options) {
712
- const { current } = tree;
713
- if (current.args.format === "number" && current.args.value !== void 0) return zodKeywordMapper.const(Number(current.args.value));
714
- if (current.args.format === "boolean" && current.args.value !== void 0) return zodKeywordMapper.const(typeof current.args.value === "boolean" ? current.args.value : void 0);
715
- return zodKeywordMapper.const(stringify(current.args.value));
716
- },
717
- matches(tree, options) {
718
- const { current, siblings } = tree;
719
- if (siblings.some((it) => (0, _kubb_plugin_oas.isKeyword)(it, _kubb_plugin_oas.schemaKeywords.ref))) return;
720
- const minSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "min");
721
- const maxSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "max");
722
- if (current.args) return zodKeywordMapper.matches(toRegExpString(current.args, null), shouldCoerce(options.coercion, "strings"), options.mini, minSchema?.args, maxSchema?.args);
723
- },
724
- default(tree, options) {
725
- const { current, siblings } = tree;
726
- if (options.mini) return;
727
- const isBigInt = siblings.some((it) => (0, _kubb_plugin_oas.isKeyword)(it, _kubb_plugin_oas.schemaKeywords.bigint));
728
- if (current.args !== void 0) {
729
- const enumSchema = siblings.find((it) => (0, _kubb_plugin_oas.isKeyword)(it, _kubb_plugin_oas.schemaKeywords.enum));
730
- if (enumSchema) {
731
- let rawDefault = current.args;
732
- if (typeof rawDefault === "string") try {
733
- rawDefault = JSON.parse(rawDefault);
734
- } catch {}
735
- if (!enumSchema.args.items.map((item) => item.value ?? item.name).includes(rawDefault)) return;
736
- }
737
- return zodKeywordMapper.default(current.args, void 0, void 0, isBigInt);
738
- }
739
- return zodKeywordMapper.default();
740
- },
741
- describe(tree, options) {
742
- const { current } = tree;
743
- if (current.args) return zodKeywordMapper.describe(stringify(current.args.toString()), void 0, options.mini);
744
- },
745
- string(tree, options) {
746
- const { siblings } = tree;
747
- const minSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "min");
748
- const maxSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "max");
749
- return zodKeywordMapper.string(shouldCoerce(options.coercion, "strings"), minSchema?.args, maxSchema?.args, options.mini);
750
- },
751
- uuid(tree, options) {
752
- const { siblings } = tree;
753
- const minSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "min");
754
- const maxSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "max");
755
- return zodKeywordMapper.uuid({
756
- coercion: shouldCoerce(options.coercion, "strings"),
757
- version: options.version,
758
- guidType: options.guidType,
759
- min: minSchema?.args,
760
- max: maxSchema?.args,
761
- mini: options.mini
762
- });
763
- },
764
- email(tree, options) {
765
- const { siblings } = tree;
766
- const minSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "min");
767
- const maxSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "max");
768
- return zodKeywordMapper.email(shouldCoerce(options.coercion, "strings"), options.version, minSchema?.args, maxSchema?.args, options.mini);
769
- },
770
- url(tree, options) {
771
- const { siblings } = tree;
772
- const minSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "min");
773
- const maxSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "max");
774
- return zodKeywordMapper.url(shouldCoerce(options.coercion, "strings"), options.version, minSchema?.args, maxSchema?.args, options.mini);
775
- },
776
- number(tree, options) {
777
- const { siblings } = tree;
778
- const minSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "min");
779
- const maxSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "max");
780
- const exclusiveMinimumSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "exclusiveMinimum");
781
- const exclusiveMaximumSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "exclusiveMaximum");
782
- return zodKeywordMapper.number(shouldCoerce(options.coercion, "numbers"), minSchema?.args, maxSchema?.args, exclusiveMinimumSchema?.args, exclusiveMaximumSchema?.args, options.mini);
783
- },
784
- integer(tree, options) {
785
- const { siblings } = tree;
786
- const minSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "min");
787
- const maxSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "max");
788
- const exclusiveMinimumSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "exclusiveMinimum");
789
- const exclusiveMaximumSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "exclusiveMaximum");
790
- return zodKeywordMapper.integer(shouldCoerce(options.coercion, "numbers"), minSchema?.args, maxSchema?.args, options.version, exclusiveMinimumSchema?.args, exclusiveMaximumSchema?.args, options.mini);
791
- },
792
- bigint(_tree, options) {
793
- return zodKeywordMapper.bigint(shouldCoerce(options.coercion, "numbers"));
794
- },
795
- datetime(tree, options) {
796
- const { current } = tree;
797
- return zodKeywordMapper.datetime(current.args.offset, current.args.local, options.version, options.mini);
798
- },
799
- date(tree, options) {
800
- const { current } = tree;
801
- return zodKeywordMapper.date(current.args.type, shouldCoerce(options.coercion, "dates"), options.version);
802
- },
803
- time(tree, options) {
804
- const { current } = tree;
805
- return zodKeywordMapper.time(current.args.type, shouldCoerce(options.coercion, "dates"), options.version);
806
- }
807
- }
808
- });
809
- //#endregion
810
- //#region src/components/Zod.tsx
811
- function Zod({ name, typeName, tree, schema, inferTypeName, mapper, coercion, keysToOmit, description, wrapOutput, version, guidType, emptySchemaType, mini = false }) {
812
- const hasTuple = !!_kubb_plugin_oas.SchemaGenerator.find(tree, _kubb_plugin_oas.schemaKeywords.tuple);
813
- const schemas = sort(tree).filter((item) => {
814
- if (hasTuple && ((0, _kubb_plugin_oas.isKeyword)(item, _kubb_plugin_oas.schemaKeywords.min) || (0, _kubb_plugin_oas.isKeyword)(item, _kubb_plugin_oas.schemaKeywords.max))) return false;
815
- return true;
816
- });
817
- const baseSchemas = mini ? filterMiniModifiers(schemas) : schemas;
818
- const output = baseSchemas.map((schemaKeyword, index) => {
819
- return parse({
820
- schema,
821
- parent: void 0,
822
- current: schemaKeyword,
823
- siblings: baseSchemas.filter((_, i) => i !== index),
824
- name
825
- }, {
826
- mapper,
827
- coercion,
828
- wrapOutput,
829
- version,
830
- guidType,
831
- mini
832
- });
833
- }).filter(Boolean).join("");
834
- let suffix = "";
835
- const firstSchema = schemas.at(0);
836
- const lastSchema = schemas.at(-1);
837
- if (!mini && lastSchema && (0, _kubb_plugin_oas.isKeyword)(lastSchema, _kubb_plugin_oas.schemaKeywords.nullable)) if (firstSchema && (0, _kubb_plugin_oas.isKeyword)(firstSchema, _kubb_plugin_oas.schemaKeywords.ref)) if (version === "3") suffix = ".unwrap().schema.unwrap()";
838
- else suffix = ".unwrap().unwrap()";
839
- else suffix = ".unwrap()";
840
- else if (!mini) {
841
- if (firstSchema && (0, _kubb_plugin_oas.isKeyword)(firstSchema, _kubb_plugin_oas.schemaKeywords.ref)) if (version === "3") suffix = ".schema";
842
- else suffix = ".unwrap()";
843
- }
844
- const emptyValue = parse({
845
- schema,
846
- parent: void 0,
847
- current: { keyword: _kubb_plugin_oas.schemaKeywords[emptySchemaType] },
848
- siblings: []
849
- }, {
850
- mapper,
851
- coercion,
852
- wrapOutput,
853
- version,
854
- guidType,
855
- mini
856
- });
857
- let baseSchemaOutput = [output, keysToOmit?.length ? `${suffix}.omit({ ${keysToOmit.map((key) => `'${key}': true`).join(",")} })` : void 0].filter(Boolean).join("") || emptyValue || "";
858
- if (mini) baseSchemaOutput = wrapWithMiniModifiers(baseSchemaOutput, extractMiniModifiers(schemas));
859
- const wrappedSchemaOutput = wrapOutput ? wrapOutput({
860
- output: baseSchemaOutput,
861
- schema
862
- }) || baseSchemaOutput : baseSchemaOutput;
863
- const finalOutput = typeName ? `${wrappedSchemaOutput} as unknown as ${version === "4" ? "z.ZodType" : "ToZod"}<${typeName}>` : wrappedSchemaOutput;
864
- return /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsxs)(_kubb_react_fabric_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
865
- name,
866
- isExportable: true,
867
- isIndexable: true,
868
- children: /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Const, {
869
- export: true,
870
- name,
871
- JSDoc: { comments: [description ? `@description ${jsStringEscape(description)}` : void 0].filter(Boolean) },
872
- children: finalOutput
873
- })
874
- }), inferTypeName && /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsxs)(_kubb_react_fabric.File.Source, {
875
- name: inferTypeName,
876
- isExportable: true,
877
- isIndexable: true,
878
- isTypeOnly: true,
879
- children: [typeName && /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Type, {
880
- export: true,
881
- name: inferTypeName,
882
- children: typeName
883
- }), !typeName && /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Type, {
884
- export: true,
885
- name: inferTypeName,
886
- children: `z.infer<typeof ${name}>`
887
- })]
888
- })] });
889
- }
890
- //#endregion
891
- Object.defineProperty(exports, "Operations", {
892
- enumerable: true,
893
- get: function() {
894
- return Operations;
895
- }
896
- });
897
- Object.defineProperty(exports, "Zod", {
898
- enumerable: true,
899
- get: function() {
900
- return Zod;
901
- }
902
- });
903
- Object.defineProperty(exports, "__name", {
904
- enumerable: true,
905
- get: function() {
906
- return __name;
907
- }
908
- });
909
- Object.defineProperty(exports, "__toESM", {
910
- enumerable: true,
911
- get: function() {
912
- return __toESM;
913
- }
914
- });
915
-
916
- //# sourceMappingURL=components-qFUGs0vU.cjs.map