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