@cerios/openapi-to-zod 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -66,7 +66,7 @@ var ConfigurationError = class extends GeneratorError {
66
66
 
67
67
  // src/generator.ts
68
68
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
69
- import { dirname } from "path";
69
+ import { dirname, normalize } from "path";
70
70
  import { parse } from "yaml";
71
71
 
72
72
  // src/utils/name-utils.ts
@@ -120,7 +120,7 @@ function generateEnum(name, values, options) {
120
120
  const enumCode = `export enum ${enumName} {
121
121
  ${enumEntries}
122
122
  }`;
123
- const schemaCode2 = `export const ${schemaName} = z.enum(${enumName});`;
123
+ const schemaCode2 = `export const ${schemaName} = z.nativeEnum(${enumName});`;
124
124
  const typeCode2 = `export type ${name} = z.infer<typeof ${schemaName}>;`;
125
125
  return { enumCode, schemaCode: schemaCode2, typeCode: typeCode2 };
126
126
  }
@@ -303,20 +303,20 @@ function generateArrayValidation(schema, context) {
303
303
  }
304
304
 
305
305
  // src/validators/composition-validator.ts
306
- function generateUnion(schemas, discriminator, isNullable2, context, options) {
306
+ function generateUnion(schemas, discriminator, isNullable2, context, options, currentSchema) {
307
307
  if (discriminator) {
308
308
  let resolvedSchemas = schemas;
309
309
  if ((options == null ? void 0 : options.discriminatorMapping) && context.resolveDiscriminatorMapping) {
310
310
  resolvedSchemas = context.resolveDiscriminatorMapping(options.discriminatorMapping, schemas);
311
311
  }
312
- let schemaStrings2 = resolvedSchemas.map((s) => context.generatePropertySchema(s));
312
+ let schemaStrings2 = resolvedSchemas.map((s) => context.generatePropertySchema(s, currentSchema));
313
313
  if (options == null ? void 0 : options.passthrough) {
314
314
  schemaStrings2 = schemaStrings2.map((s) => s.includes(".catchall(") ? s : `${s}.catchall(z.unknown())`);
315
315
  }
316
316
  const union2 = `z.discriminatedUnion("${discriminator}", [${schemaStrings2.join(", ")}])`;
317
317
  return wrapNullable(union2, isNullable2);
318
318
  }
319
- let schemaStrings = schemas.map((s) => context.generatePropertySchema(s));
319
+ let schemaStrings = schemas.map((s) => context.generatePropertySchema(s, currentSchema));
320
320
  if (options == null ? void 0 : options.passthrough) {
321
321
  schemaStrings = schemaStrings.map((s) => s.includes(".catchall(") ? s : `${s}.catchall(z.unknown())`);
322
322
  }
@@ -1149,7 +1149,8 @@ var _PropertyGenerator = class _PropertyGenerator {
1149
1149
  {
1150
1150
  passthrough: needsPassthrough,
1151
1151
  discriminatorMapping: (_c = schema.discriminator) == null ? void 0 : _c.mapping
1152
- }
1152
+ },
1153
+ currentSchema
1153
1154
  );
1154
1155
  if (schema.unevaluatedProperties !== void 0) {
1155
1156
  composition = this.applyUnevaluatedProperties(composition, schema);
@@ -1169,7 +1170,8 @@ var _PropertyGenerator = class _PropertyGenerator {
1169
1170
  {
1170
1171
  passthrough: needsPassthrough,
1171
1172
  discriminatorMapping: (_e = schema.discriminator) == null ? void 0 : _e.mapping
1172
- }
1173
+ },
1174
+ currentSchema
1173
1175
  );
1174
1176
  if (schema.unevaluatedProperties !== void 0) {
1175
1177
  composition = this.applyUnevaluatedProperties(composition, schema);
@@ -1340,10 +1342,13 @@ var ZodSchemaGenerator = class {
1340
1342
  }
1341
1343
  for (const [name, schema] of Object.entries(this.spec.components.schemas)) {
1342
1344
  if (schema.enum) {
1343
- const typeMode = this.schemaTypeModeMap.get(name) || "inferred";
1344
- if (typeMode === "inferred") {
1345
+ const context = this.schemaUsageMap.get(name);
1346
+ const resolvedOptions = context === "response" ? this.responseOptions : this.requestOptions;
1347
+ if (resolvedOptions.enumType === "typescript") {
1348
+ this.generateNativeEnum(name, schema);
1349
+ } else {
1345
1350
  const { enumCode } = generateEnum(name, schema.enum, {
1346
- enumType: this.options.enumType || "zod",
1351
+ enumType: "zod",
1347
1352
  prefix: this.options.prefix,
1348
1353
  suffix: this.options.suffix
1349
1354
  });
@@ -1351,14 +1356,13 @@ var ZodSchemaGenerator = class {
1351
1356
  this.enums.set(name, enumCode);
1352
1357
  this.needsZodImport = true;
1353
1358
  }
1354
- } else {
1355
- this.generateNativeEnum(name, schema);
1356
1359
  }
1357
1360
  }
1358
1361
  }
1359
1362
  for (const [name, schema] of Object.entries(this.spec.components.schemas)) {
1360
1363
  this.generateComponentSchema(name, schema);
1361
1364
  }
1365
+ this.generateQueryParameterSchemas();
1362
1366
  const orderedSchemaNames = this.topologicalSort();
1363
1367
  const output = ["// Auto-generated by @cerios/openapi-to-zod", "// Do not edit this file manually", ""];
1364
1368
  if (this.options.showStats === true) {
@@ -1369,12 +1373,8 @@ var ZodSchemaGenerator = class {
1369
1373
  output.push('import { z } from "zod";');
1370
1374
  output.push("");
1371
1375
  }
1372
- if (this.enums.size > 0 || this.nativeEnums.size > 0) {
1373
- output.push("// Enums");
1374
- for (const enumCode of this.enums.values()) {
1375
- output.push(enumCode);
1376
- output.push("");
1377
- }
1376
+ if (this.nativeEnums.size > 0) {
1377
+ output.push("// Native Enums");
1378
1378
  for (const enumCode of this.nativeEnums.values()) {
1379
1379
  output.push(enumCode);
1380
1380
  output.push("");
@@ -1382,9 +1382,13 @@ var ZodSchemaGenerator = class {
1382
1382
  }
1383
1383
  output.push("// Schemas and Types");
1384
1384
  for (const name of orderedSchemaNames) {
1385
+ const enumCode = this.enums.get(name);
1385
1386
  const schemaCode = this.schemas.get(name);
1386
1387
  const typeCode = this.types.get(name);
1387
- if (schemaCode) {
1388
+ if (enumCode) {
1389
+ output.push(enumCode);
1390
+ output.push("");
1391
+ } else if (schemaCode) {
1388
1392
  output.push(schemaCode);
1389
1393
  if (!schemaCode.includes(`export type ${name}`)) {
1390
1394
  const schemaName = `${toCamelCase(name, { prefix: this.options.prefix, suffix: this.options.suffix })}Schema`;
@@ -1402,7 +1406,8 @@ var ZodSchemaGenerator = class {
1402
1406
  * Ensure directory exists for a file path
1403
1407
  */
1404
1408
  ensureDirectoryExists(filePath) {
1405
- const dir = dirname(filePath);
1409
+ const normalizedPath = normalize(filePath);
1410
+ const dir = dirname(normalizedPath);
1406
1411
  if (!existsSync(dir)) {
1407
1412
  mkdirSync(dir, { recursive: true });
1408
1413
  }
@@ -1418,8 +1423,9 @@ var ZodSchemaGenerator = class {
1418
1423
  );
1419
1424
  }
1420
1425
  const output = this.generateString();
1421
- this.ensureDirectoryExists(this.options.output);
1422
- writeFileSync(this.options.output, output);
1426
+ const normalizedOutput = normalize(this.options.output);
1427
+ this.ensureDirectoryExists(normalizedOutput);
1428
+ writeFileSync(normalizedOutput, output);
1423
1429
  }
1424
1430
  /**
1425
1431
  * Resolve options for a specific context (request or response)
@@ -1427,17 +1433,18 @@ var ZodSchemaGenerator = class {
1427
1433
  * Response schemas always use 'inferred' mode (Zod schemas)
1428
1434
  */
1429
1435
  resolveOptionsForContext(context) {
1430
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
1436
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
1431
1437
  const contextOptions = context === "request" ? this.options.request : this.options.response;
1438
+ const nativeEnumType = context === "request" ? (_c = (_b = (_a = this.options.request) == null ? void 0 : _a.nativeEnumType) != null ? _b : this.options.nativeEnumType) != null ? _c : "union" : (_d = this.options.nativeEnumType) != null ? _d : "union";
1432
1439
  return {
1433
- mode: (_b = (_a = contextOptions == null ? void 0 : contextOptions.mode) != null ? _a : this.options.mode) != null ? _b : "normal",
1434
- enumType: (_d = (_c = contextOptions == null ? void 0 : contextOptions.enumType) != null ? _c : this.options.enumType) != null ? _d : "zod",
1435
- useDescribe: (_f = (_e = contextOptions == null ? void 0 : contextOptions.useDescribe) != null ? _e : this.options.useDescribe) != null ? _f : false,
1436
- includeDescriptions: (_h = (_g = contextOptions == null ? void 0 : contextOptions.includeDescriptions) != null ? _g : this.options.includeDescriptions) != null ? _h : true,
1440
+ mode: (_f = (_e = contextOptions == null ? void 0 : contextOptions.mode) != null ? _e : this.options.mode) != null ? _f : "normal",
1441
+ enumType: (_h = (_g = contextOptions == null ? void 0 : contextOptions.enumType) != null ? _g : this.options.enumType) != null ? _h : "zod",
1442
+ useDescribe: (_j = (_i = contextOptions == null ? void 0 : contextOptions.useDescribe) != null ? _i : this.options.useDescribe) != null ? _j : false,
1443
+ includeDescriptions: (_l = (_k = contextOptions == null ? void 0 : contextOptions.includeDescriptions) != null ? _k : this.options.includeDescriptions) != null ? _l : true,
1437
1444
  // Response schemas always use 'inferred' mode (Zod schemas are required)
1438
1445
  // Request schemas can optionally use 'native' mode
1439
- typeMode: context === "response" ? "inferred" : (_i = contextOptions == null ? void 0 : contextOptions.typeMode) != null ? _i : "inferred",
1440
- nativeEnumType: (_k = (_j = contextOptions == null ? void 0 : contextOptions.nativeEnumType) != null ? _j : this.options.nativeEnumType) != null ? _k : "union"
1446
+ typeMode: context === "response" ? "inferred" : (_n = (_m = this.options.request) == null ? void 0 : _m.typeMode) != null ? _n : "inferred",
1447
+ nativeEnumType
1441
1448
  };
1442
1449
  }
1443
1450
  /**
@@ -1722,10 +1729,19 @@ var ZodSchemaGenerator = class {
1722
1729
  const context = this.schemaUsageMap.get(name);
1723
1730
  const resolvedOptions = context === "response" ? this.responseOptions : this.requestOptions;
1724
1731
  if (schema.enum) {
1725
- if (typeMode === "inferred") {
1726
- const jsdoc = generateJSDoc(schema, name, { includeDescriptions: resolvedOptions.includeDescriptions });
1732
+ const jsdoc = generateJSDoc(schema, name, { includeDescriptions: resolvedOptions.includeDescriptions });
1733
+ if (resolvedOptions.enumType === "typescript") {
1734
+ const { schemaCode, typeCode } = generateEnum(name, schema.enum, {
1735
+ enumType: "typescript",
1736
+ prefix: this.options.prefix,
1737
+ suffix: this.options.suffix
1738
+ });
1739
+ const enumSchemaCode = `${jsdoc}${schemaCode}
1740
+ ${typeCode}`;
1741
+ this.schemas.set(name, enumSchemaCode);
1742
+ } else {
1727
1743
  const { enumCode, schemaCode, typeCode } = generateEnum(name, schema.enum, {
1728
- enumType: resolvedOptions.enumType,
1744
+ enumType: "zod",
1729
1745
  prefix: this.options.prefix,
1730
1746
  suffix: this.options.suffix
1731
1747
  });
@@ -1784,6 +1800,133 @@ ${typeCode}`;
1784
1800
  this.schemas.set(name, zodSchemaCode);
1785
1801
  }
1786
1802
  }
1803
+ /**
1804
+ * Generate query parameter schemas for each operation
1805
+ */
1806
+ generateQueryParameterSchemas() {
1807
+ var _a;
1808
+ if (!this.spec.paths) {
1809
+ return;
1810
+ }
1811
+ for (const [_path, pathItem] of Object.entries(this.spec.paths)) {
1812
+ if (!pathItem || typeof pathItem !== "object") continue;
1813
+ const methods = ["get", "post", "put", "patch", "delete", "head", "options"];
1814
+ for (const method of methods) {
1815
+ const operation = pathItem[method];
1816
+ if (!operation) continue;
1817
+ if (!operation.operationId || !operation.parameters || !Array.isArray(operation.parameters)) {
1818
+ continue;
1819
+ }
1820
+ const queryParams = operation.parameters.filter(
1821
+ (param) => param && typeof param === "object" && param.in === "query"
1822
+ );
1823
+ if (queryParams.length === 0) {
1824
+ continue;
1825
+ }
1826
+ const pascalOperationId = operation.operationId.includes("-") ? toPascalCase(operation.operationId) : operation.operationId.charAt(0).toUpperCase() + operation.operationId.slice(1);
1827
+ const schemaName = `${pascalOperationId}QueryParams`;
1828
+ if (!this.schemaDependencies.has(schemaName)) {
1829
+ this.schemaDependencies.set(schemaName, /* @__PURE__ */ new Set());
1830
+ }
1831
+ const properties = {};
1832
+ const required = [];
1833
+ for (const param of queryParams) {
1834
+ const paramName = param.name;
1835
+ const isRequired = param.required === true;
1836
+ const paramSchema = param.schema;
1837
+ if (!paramSchema) continue;
1838
+ let zodType = this.generateQueryParamType(paramSchema, param);
1839
+ if (paramSchema.type === "array" && paramSchema.items) {
1840
+ const itemType = this.generateQueryParamType(paramSchema.items, param);
1841
+ zodType = `z.array(${itemType})`;
1842
+ }
1843
+ if (param.description && this.requestOptions.includeDescriptions) {
1844
+ if (this.requestOptions.useDescribe) {
1845
+ zodType = `${zodType}.describe(${JSON.stringify(param.description)})`;
1846
+ }
1847
+ }
1848
+ if (!isRequired) {
1849
+ zodType = `${zodType}.optional()`;
1850
+ }
1851
+ properties[paramName] = zodType;
1852
+ if (isRequired) {
1853
+ required.push(paramName);
1854
+ }
1855
+ if (paramSchema.$ref) {
1856
+ const refName = resolveRef(paramSchema.$ref);
1857
+ (_a = this.schemaDependencies.get(schemaName)) == null ? void 0 : _a.add(refName);
1858
+ }
1859
+ }
1860
+ const objectMode = this.requestOptions.mode;
1861
+ const zodMethod = objectMode === "strict" ? "strictObject" : objectMode === "loose" ? "looseObject" : "object";
1862
+ const propsCode = Object.entries(properties).map(([key, value]) => {
1863
+ const needsQuotes = !/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key);
1864
+ const quotedKey = needsQuotes ? `"${key}"` : key;
1865
+ return ` ${quotedKey}: ${value}`;
1866
+ }).join(",\n");
1867
+ const schemaCode = `z.${zodMethod}({
1868
+ ${propsCode}
1869
+ })`;
1870
+ const operationName = pascalOperationId;
1871
+ const prefixedName = this.options.prefix ? `${toPascalCase(this.options.prefix)}${operationName}` : operationName;
1872
+ const suffixedName = this.options.suffix ? `${prefixedName}${toPascalCase(this.options.suffix)}` : prefixedName;
1873
+ const camelCaseSchemaName = `${suffixedName.charAt(0).toLowerCase() + suffixedName.slice(1)}QueryParamsSchema`;
1874
+ const jsdoc = `/**
1875
+ * Query parameters for ${operation.operationId}
1876
+ */
1877
+ `;
1878
+ const fullSchemaCode = `${jsdoc}export const ${camelCaseSchemaName} = ${schemaCode};`;
1879
+ this.schemas.set(schemaName, fullSchemaCode);
1880
+ this.needsZodImport = true;
1881
+ }
1882
+ }
1883
+ }
1884
+ /**
1885
+ * Generate Zod type for a query parameter schema
1886
+ */
1887
+ generateQueryParamType(schema, param) {
1888
+ if (schema.$ref) {
1889
+ const refName = resolveRef(schema.$ref);
1890
+ const schemaName = toCamelCase(refName, { prefix: this.options.prefix, suffix: this.options.suffix });
1891
+ return `${schemaName}Schema`;
1892
+ }
1893
+ if (schema.enum) {
1894
+ const enumValues = schema.enum.map((v) => typeof v === "string" ? `"${v}"` : v).join(", ");
1895
+ return `z.enum([${enumValues}])`;
1896
+ }
1897
+ const type = schema.type;
1898
+ if (type === "string") {
1899
+ let zodType = "z.string()";
1900
+ if (schema.minLength !== void 0) zodType = `${zodType}.min(${schema.minLength})`;
1901
+ if (schema.maxLength !== void 0) zodType = `${zodType}.max(${schema.maxLength})`;
1902
+ if (schema.pattern) zodType = `${zodType}.regex(/${schema.pattern}/)`;
1903
+ if (schema.format === "email") zodType = `${zodType}.email()`;
1904
+ if (schema.format === "uri" || schema.format === "url") zodType = `${zodType}.url()`;
1905
+ if (schema.format === "uuid") zodType = `${zodType}.uuid()`;
1906
+ return zodType;
1907
+ }
1908
+ if (type === "number" || type === "integer") {
1909
+ let zodType = type === "integer" ? "z.number().int()" : "z.number()";
1910
+ if (schema.minimum !== void 0) {
1911
+ zodType = schema.exclusiveMinimum ? `${zodType}.gt(${schema.minimum})` : `${zodType}.gte(${schema.minimum})`;
1912
+ }
1913
+ if (schema.maximum !== void 0) {
1914
+ zodType = schema.exclusiveMaximum ? `${zodType}.lt(${schema.maximum})` : `${zodType}.lte(${schema.maximum})`;
1915
+ }
1916
+ return zodType;
1917
+ }
1918
+ if (type === "boolean") {
1919
+ return "z.boolean()";
1920
+ }
1921
+ if (type === "array" && schema.items) {
1922
+ const itemType = this.generateQueryParamType(schema.items, param);
1923
+ let arrayType = `z.array(${itemType})`;
1924
+ if (schema.minItems !== void 0) arrayType = `${arrayType}.min(${schema.minItems})`;
1925
+ if (schema.maxItems !== void 0) arrayType = `${arrayType}.max(${schema.maxItems})`;
1926
+ return arrayType;
1927
+ }
1928
+ return "z.unknown()";
1929
+ }
1787
1930
  /**
1788
1931
  * Generate native TypeScript enum
1789
1932
  */
@@ -1794,8 +1937,8 @@ ${typeCode}`;
1794
1937
  const jsdoc = generateJSDoc(schema, name, { includeDescriptions: resolvedOptions.includeDescriptions });
1795
1938
  if (resolvedOptions.nativeEnumType === "enum") {
1796
1939
  const enumName = `${name}Enum`;
1797
- const members = schema.enum.map((value, index) => {
1798
- const key = typeof value === "string" ? this.toEnumKey(value) : `Value${index}`;
1940
+ const members = schema.enum.map((value) => {
1941
+ const key = typeof value === "string" ? this.toEnumKey(value) : `N${value}`;
1799
1942
  const val = typeof value === "string" ? `"${value}"` : value;
1800
1943
  return ` ${key} = ${val}`;
1801
1944
  }).join(",\n");
@@ -1938,7 +2081,11 @@ ${props.join("\n")}
1938
2081
  const visited = /* @__PURE__ */ new Set();
1939
2082
  const visiting = /* @__PURE__ */ new Set();
1940
2083
  const aliases = [];
2084
+ const circularDeps = /* @__PURE__ */ new Set();
1941
2085
  const codeCache = /* @__PURE__ */ new Map();
2086
+ for (const [name, code] of this.enums) {
2087
+ codeCache.set(name, code);
2088
+ }
1942
2089
  for (const [name, code] of this.schemas) {
1943
2090
  codeCache.set(name, code);
1944
2091
  }
@@ -1948,6 +2095,7 @@ ${props.join("\n")}
1948
2095
  const visit = (name) => {
1949
2096
  if (visited.has(name)) return;
1950
2097
  if (visiting.has(name)) {
2098
+ circularDeps.add(name);
1951
2099
  return;
1952
2100
  }
1953
2101
  visiting.add(name);
@@ -1962,19 +2110,27 @@ ${props.join("\n")}
1962
2110
  const deps = this.schemaDependencies.get(name);
1963
2111
  if (deps && deps.size > 0) {
1964
2112
  for (const dep of deps) {
1965
- if (this.schemas.has(dep) || this.types.has(dep)) {
2113
+ if (this.enums.has(dep) || this.schemas.has(dep) || this.types.has(dep)) {
1966
2114
  visit(dep);
1967
2115
  }
1968
2116
  }
1969
2117
  }
1970
2118
  visiting.delete(name);
1971
2119
  visited.add(name);
1972
- sorted.push(name);
2120
+ if (!circularDeps.has(name)) {
2121
+ sorted.push(name);
2122
+ }
1973
2123
  };
1974
- const allNames = /* @__PURE__ */ new Set([...this.schemas.keys(), ...this.types.keys()]);
2124
+ const allNames = /* @__PURE__ */ new Set([...this.enums.keys(), ...this.schemas.keys(), ...this.types.keys()]);
1975
2125
  for (const name of allNames) {
1976
2126
  visit(name);
1977
2127
  }
2128
+ for (const name of circularDeps) {
2129
+ if (!visited.has(name)) {
2130
+ sorted.push(name);
2131
+ visited.add(name);
2132
+ }
2133
+ }
1978
2134
  return [...sorted, ...aliases];
1979
2135
  }
1980
2136
  /**