@kubb/plugin-zod 5.0.0-alpha.3 → 5.0.0-alpha.31

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