@ng-openapi/zod 0.1.3 → 0.2.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.
Files changed (4) hide show
  1. package/index.cjs +421 -59
  2. package/index.d.ts +6 -2
  3. package/index.js +421 -59
  4. package/package.json +1 -1
package/index.cjs CHANGED
@@ -38,6 +38,238 @@ module.exports = __toCommonJS(index_exports);
38
38
  // src/lib/zod.generator.ts
39
39
  var path2 = __toESM(require("path"), 1);
40
40
 
41
+ // ../../shared/src/errors.ts
42
+ var NG_OPENAPI_ERROR_BRAND = "__ngOpenApiError";
43
+ var ERROR_LINEAGE = /* @__PURE__ */ new WeakMap();
44
+ var FALLBACK_LINEAGE = Object.freeze([
45
+ "NgOpenApiError"
46
+ ]);
47
+ function registerError(cls, lineage) {
48
+ ERROR_LINEAGE.set(cls, Object.freeze([
49
+ ...lineage
50
+ ]));
51
+ return cls;
52
+ }
53
+ __name(registerError, "registerError");
54
+ function inheritedLineage(cls) {
55
+ for (let current = cls; typeof current === "function"; current = Object.getPrototypeOf(current)) {
56
+ const lineage = ERROR_LINEAGE.get(current);
57
+ if (lineage) {
58
+ return lineage;
59
+ }
60
+ }
61
+ return FALLBACK_LINEAGE;
62
+ }
63
+ __name(inheritedLineage, "inheritedLineage");
64
+ var NgOpenApiError = class extends Error {
65
+ static {
66
+ __name(this, "NgOpenApiError");
67
+ }
68
+ /** The underlying error that caused this one, when there is one. */
69
+ cause;
70
+ constructor(message, cause) {
71
+ super(message);
72
+ const lineage = inheritedLineage(new.target);
73
+ this.name = lineage[0];
74
+ this.cause = cause;
75
+ Object.defineProperty(this, NG_OPENAPI_ERROR_BRAND, {
76
+ value: lineage,
77
+ enumerable: false,
78
+ writable: false,
79
+ configurable: false
80
+ });
81
+ }
82
+ /**
83
+ * `message` and `name` are non-enumerable on Error, so the default
84
+ * JSON.stringify dropped both — the least useful possible serialization for
85
+ * something that exists to be logged.
86
+ *
87
+ * The payload is spread rather than enumerated: `source`, `issues`,
88
+ * `operation`, `names` and `placeholders` are why these classes are typed
89
+ * in the first place, and listing fields by hand silently drops whichever
90
+ * ones a later subclass adds.
91
+ */
92
+ toJSON() {
93
+ const cause = this.cause instanceof Error ? this.cause.message : this.cause;
94
+ return {
95
+ name: this.name,
96
+ message: this.message,
97
+ ...cause === void 0 ? {} : {
98
+ cause
99
+ },
100
+ // Own enumerable properties: the brand is deliberately not one.
101
+ ...Object.fromEntries(Object.entries(this).filter(([key]) => key !== "cause"))
102
+ };
103
+ }
104
+ /**
105
+ * Recognizes branded errors from another bundled copy of this module, so
106
+ * `error instanceof SpecLoadError` works for a plugin-thrown error too.
107
+ * The prototype chain is checked first, so a caller's own subclass of these
108
+ * classes still matches even though it carries no lineage entry.
109
+ *
110
+ * Never throws and never runs foreign code: both reflective reads sit
111
+ * inside the try, because a Proxy traps `getPrototypeOf` just as readily as
112
+ * `getOwnPropertyDescriptor`.
113
+ */
114
+ static [Symbol.hasInstance](value) {
115
+ if (typeof value !== "object" || value === null) {
116
+ return false;
117
+ }
118
+ try {
119
+ if (Object.prototype.isPrototypeOf.call(this.prototype, value)) {
120
+ return true;
121
+ }
122
+ const expected = ERROR_LINEAGE.get(this)?.[0];
123
+ if (expected === void 0) {
124
+ return false;
125
+ }
126
+ const descriptor = Object.getOwnPropertyDescriptor(value, NG_OPENAPI_ERROR_BRAND);
127
+ if (!descriptor || descriptor.enumerable || !("value" in descriptor)) {
128
+ return false;
129
+ }
130
+ return Array.isArray(descriptor.value) && descriptor.value.includes(expected);
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
135
+ };
136
+ registerError(NgOpenApiError, [
137
+ "NgOpenApiError"
138
+ ]);
139
+ var SpecLoadError = class extends NgOpenApiError {
140
+ static {
141
+ __name(this, "SpecLoadError");
142
+ }
143
+ /** The file path or URL that failed to load. */
144
+ source;
145
+ constructor(message, source, cause) {
146
+ super(message, cause);
147
+ this.source = source;
148
+ }
149
+ };
150
+ registerError(SpecLoadError, [
151
+ "SpecLoadError",
152
+ "NgOpenApiError"
153
+ ]);
154
+ var SpecParseError = class extends NgOpenApiError {
155
+ static {
156
+ __name(this, "SpecParseError");
157
+ }
158
+ /** The file path or URL the content came from, when known. */
159
+ source;
160
+ constructor(message, source, cause) {
161
+ super(message, cause);
162
+ this.source = source;
163
+ }
164
+ };
165
+ registerError(SpecParseError, [
166
+ "SpecParseError",
167
+ "NgOpenApiError"
168
+ ]);
169
+ function describeOperation(operation) {
170
+ const location = `(${operation.method}) ${operation.path}`;
171
+ return operation.operationId ? `${operation.operationId} (${location})` : location;
172
+ }
173
+ __name(describeOperation, "describeOperation");
174
+ function captureOperation(operation) {
175
+ return Object.freeze({
176
+ operationId: operation.operationId,
177
+ method: operation.method,
178
+ path: operation.path
179
+ });
180
+ }
181
+ __name(captureOperation, "captureOperation");
182
+ var InvalidIdentifierError = class extends NgOpenApiError {
183
+ static {
184
+ __name(this, "InvalidIdentifierError");
185
+ }
186
+ /** The rejected name, verbatim; absent when no name could be derived. */
187
+ identifier;
188
+ /** The operation whose name was being derived. */
189
+ operation;
190
+ constructor(message, operation, identifier) {
191
+ super(message);
192
+ this.operation = captureOperation(operation);
193
+ this.identifier = identifier;
194
+ }
195
+ };
196
+ registerError(InvalidIdentifierError, [
197
+ "InvalidIdentifierError",
198
+ "NgOpenApiError"
199
+ ]);
200
+ var DuplicateGeneratedNameError = class extends NgOpenApiError {
201
+ static {
202
+ __name(this, "DuplicateGeneratedNameError");
203
+ }
204
+ /** The colliding generated names. */
205
+ names;
206
+ /** The operations that produced them, when known. */
207
+ operations;
208
+ constructor(message, names, operations = []) {
209
+ super(message);
210
+ this.names = Object.freeze([
211
+ ...names
212
+ ]);
213
+ this.operations = Object.freeze(operations.map(captureOperation));
214
+ }
215
+ };
216
+ registerError(DuplicateGeneratedNameError, [
217
+ "DuplicateGeneratedNameError",
218
+ "NgOpenApiError"
219
+ ]);
220
+ var UnresolvedPathTemplateError = class extends NgOpenApiError {
221
+ static {
222
+ __name(this, "UnresolvedPathTemplateError");
223
+ }
224
+ /** The path as written in the spec. */
225
+ path;
226
+ /** Placeholder names with no declared parameter. */
227
+ placeholders;
228
+ constructor(message, path3, placeholders) {
229
+ super(message);
230
+ this.path = path3;
231
+ this.placeholders = Object.freeze([
232
+ ...placeholders
233
+ ]);
234
+ }
235
+ };
236
+ registerError(UnresolvedPathTemplateError, [
237
+ "UnresolvedPathTemplateError",
238
+ "NgOpenApiError"
239
+ ]);
240
+ var ConfigValidationError = class extends NgOpenApiError {
241
+ static {
242
+ __name(this, "ConfigValidationError");
243
+ }
244
+ issues;
245
+ constructor(issues) {
246
+ super(`Invalid ng-openapi configuration:
247
+ ${issues.map((issue) => ` - ${issue}`).join("\n")}`);
248
+ this.issues = Object.freeze([
249
+ ...issues
250
+ ]);
251
+ }
252
+ };
253
+ registerError(ConfigValidationError, [
254
+ "ConfigValidationError",
255
+ "NgOpenApiError"
256
+ ]);
257
+ var ConfigLoadError = class extends NgOpenApiError {
258
+ static {
259
+ __name(this, "ConfigLoadError");
260
+ }
261
+ /** Path of the config file that failed to load. */
262
+ source;
263
+ constructor(message, source, cause) {
264
+ super(message, cause);
265
+ this.source = source;
266
+ }
267
+ };
268
+ registerError(ConfigLoadError, [
269
+ "ConfigLoadError",
270
+ "NgOpenApiError"
271
+ ]);
272
+
41
273
  // ../../../node_modules/js-yaml/dist/js-yaml.mjs
42
274
  function isNothing(subject) {
43
275
  return typeof subject === "undefined" || subject === null;
@@ -2740,6 +2972,27 @@ var safeLoad = renamed("safeLoad", "load");
2740
2972
  var safeLoadAll = renamed("safeLoadAll", "loadAll");
2741
2973
  var safeDump = renamed("safeDump", "dump");
2742
2974
 
2975
+ // ../../shared/src/utils/string.utils.ts
2976
+ var IDENTIFIER_SEPARATORS = /(?:_|[^\p{ID_Continue}$])+(.)?/gu;
2977
+ var INVALID_IDENTIFIER_START = /^[^\p{ID_Start}$_]/u;
2978
+ function toIdentifier(converted) {
2979
+ if (converted === "") {
2980
+ return "_";
2981
+ }
2982
+ return converted.replace(INVALID_IDENTIFIER_START, (char) => `_${char}`);
2983
+ }
2984
+ __name(toIdentifier, "toIdentifier");
2985
+ function camelCase(str2) {
2986
+ const converted = str2.replace(IDENTIFIER_SEPARATORS, (_, char) => char ? char.toUpperCase() : "").replace(/^./u, (char) => char.toLowerCase());
2987
+ return toIdentifier(converted);
2988
+ }
2989
+ __name(camelCase, "camelCase");
2990
+ function pascalCase(str2) {
2991
+ const converted = str2.replace(IDENTIFIER_SEPARATORS, (_, char) => char ? char.toUpperCase() : "").replace(/^./u, (char) => char.toUpperCase());
2992
+ return toIdentifier(converted);
2993
+ }
2994
+ __name(pascalCase, "pascalCase");
2995
+
2743
2996
  // ../../shared/src/utils/content-types.constants.ts
2744
2997
  var CONTENT_TYPES = {
2745
2998
  MULTIPART: "multipart/form-data",
@@ -2747,15 +3000,47 @@ var CONTENT_TYPES = {
2747
3000
  JSON: "application/json"
2748
3001
  };
2749
3002
 
2750
- // ../../shared/src/utils/string.utils.ts
2751
- function camelCase(str2) {
2752
- return str2.replace(/[-_.\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "").replace(/^./, (char) => char.toLowerCase());
3003
+ // ../../shared/src/emit/literal.emit.ts
3004
+ function quoteLiteral(value) {
3005
+ return `'${escapeSingleQuoted(value)}'`;
2753
3006
  }
2754
- __name(camelCase, "camelCase");
2755
- function pascalCase(str2) {
2756
- return str2.replace(/[-_.\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "").replace(/^./, (char) => char.toUpperCase());
3007
+ __name(quoteLiteral, "quoteLiteral");
3008
+ function escapeSingleQuoted(value) {
3009
+ return value.replace(/[\\']/g, (char) => `\\${char}`).replace(/\r/g, "\\r").replace(/\n/g, "\\n");
2757
3010
  }
2758
- __name(pascalCase, "pascalCase");
3011
+ __name(escapeSingleQuoted, "escapeSingleQuoted");
3012
+ function emitObjectKey(name, quoteStyle = "double") {
3013
+ const quoted = quoteStyle === "single" ? quoteLiteral(name) : `"${escapeDoubleQuoted(name)}"`;
3014
+ return name === "__proto__" ? `[${quoted}]` : quoted;
3015
+ }
3016
+ __name(emitObjectKey, "emitObjectKey");
3017
+ function escapeDoubleQuoted(value) {
3018
+ return value.replace(/[\\"]/g, (char) => `\\${char}`).replace(/\r/g, "\\r").replace(/\n/g, "\\n");
3019
+ }
3020
+ __name(escapeDoubleQuoted, "escapeDoubleQuoted");
3021
+
3022
+ // ../../shared/src/utils/functions/argument-names.ts
3023
+ var SERVICE_ARGUMENT_PROFILE = Object.freeze({
3024
+ reserved: Object.freeze([
3025
+ "observe",
3026
+ "options",
3027
+ "url",
3028
+ "params",
3029
+ "headers",
3030
+ "formData",
3031
+ "formBody"
3032
+ ]),
3033
+ bindsRequestBody: true
3034
+ });
3035
+ var RESOURCE_ARGUMENT_PROFILE = Object.freeze({
3036
+ reserved: Object.freeze([
3037
+ "resourceOptions",
3038
+ "requestOptions",
3039
+ "params",
3040
+ "headers"
3041
+ ]),
3042
+ bindsRequestBody: false
3043
+ });
2759
3044
 
2760
3045
  // ../../shared/src/utils/project.utils.ts
2761
3046
  function listGeneratedFileNames(project, directoryPath, suffix) {
@@ -2767,6 +3052,65 @@ function listGeneratedFileNames(project, directoryPath, suffix) {
2767
3052
  }
2768
3053
  __name(listGeneratedFileNames, "listGeneratedFileNames");
2769
3054
 
3055
+ // ../../shared/src/utils/functions/controller-groups.ts
3056
+ function groupOperationsByController(operations, onWarning) {
3057
+ const groups = {};
3058
+ const controllerByFold = /* @__PURE__ */ new Map();
3059
+ const tagSpellings = /* @__PURE__ */ new Map();
3060
+ const namelessTags = /* @__PURE__ */ new Set();
3061
+ operations.forEach((operation) => {
3062
+ const tag = operation.tags?.[0];
3063
+ let rawName = "Default";
3064
+ if (tag !== void 0) {
3065
+ rawName = tag;
3066
+ } else {
3067
+ const pathParts = operation.path.split("/").filter((part) => part && !part.startsWith("{"));
3068
+ if (pathParts.length > 1) {
3069
+ rawName = pathParts[1];
3070
+ }
3071
+ }
3072
+ const sanitized = pascalCase(rawName);
3073
+ const isNameless = !/\p{L}/u.test(sanitized);
3074
+ const candidate = isNameless ? "Default" : sanitized;
3075
+ const fold = candidate.toLowerCase();
3076
+ const controllerName = controllerByFold.get(fold) ?? candidate;
3077
+ controllerByFold.set(fold, controllerName);
3078
+ if (tag !== void 0 && isNameless) {
3079
+ namelessTags.add(tag);
3080
+ } else if (tag !== void 0) {
3081
+ const spellings = tagSpellings.get(controllerName) ?? /* @__PURE__ */ new Set();
3082
+ spellings.add(tag);
3083
+ tagSpellings.set(controllerName, spellings);
3084
+ }
3085
+ if (!groups[controllerName]) {
3086
+ groups[controllerName] = [];
3087
+ }
3088
+ groups[controllerName].push(operation);
3089
+ });
3090
+ for (const tag of namelessTags) {
3091
+ onWarning?.(`Tag "${tag}" contains no characters usable in a name \u2014 its operations are generated into the "Default" controller. Rename the tag to give them a file of their own.`);
3092
+ }
3093
+ for (const [controllerName, spellings] of tagSpellings) {
3094
+ if (spellings.size > 1) {
3095
+ onWarning?.(`Tags ${[
3096
+ ...spellings
3097
+ ].map((name) => `"${name}"`).join(" and ")} all map to the controller "${controllerName}" \u2014 their operations are generated into one file. Rename one tag to keep them apart.`);
3098
+ }
3099
+ }
3100
+ return groups;
3101
+ }
3102
+ __name(groupOperationsByController, "groupOperationsByController");
3103
+
3104
+ // ../../shared/src/utils/functions/method-names.ts
3105
+ var RESERVED_MEMBER_NAMES = Object.freeze([
3106
+ "constructor",
3107
+ "httpClient",
3108
+ "basePath",
3109
+ "clientContextToken",
3110
+ "createContextWithClientId"
3111
+ ]);
3112
+ var RESERVED_MEMBER_SET = new Set(RESERVED_MEMBER_NAMES);
3113
+
2770
3114
  // ../../shared/src/config/constants.ts
2771
3115
  var disableLinting = `// @ts-nocheck
2772
3116
  /* eslint-disable */
@@ -2866,14 +3210,14 @@ var ZodSchemaBuilder = class {
2866
3210
  } else if (!buildOptions.required) {
2867
3211
  zodSchema = `${zodSchema}.optional()`;
2868
3212
  }
2869
- if (schema2.description) {
2870
- zodSchema = `${zodSchema}.describe('${this.escapeString(schema2.description)}')`;
3213
+ if (typeof schema2.description === "string" && schema2.description) {
3214
+ zodSchema = `${zodSchema}.describe('${escapeSingleQuoted(schema2.description)}')`;
2871
3215
  }
2872
3216
  return zodSchema;
2873
3217
  }
2874
3218
  async buildStringSchema(schema2, buildOptions) {
2875
3219
  if (schema2.enum && schema2.enum.every((v) => typeof v === "string")) {
2876
- const enumValues = schema2.enum.map((v) => `'${this.escapeString(String(v))}'`).join(", ");
3220
+ const enumValues = schema2.enum.map((v) => emitEnumMember(v)).join(", ");
2877
3221
  return `z.enum([${enumValues}])`;
2878
3222
  }
2879
3223
  if (schema2.format) {
@@ -2907,15 +3251,14 @@ var ZodSchemaBuilder = class {
2907
3251
  }
2908
3252
  }
2909
3253
  let zodString = buildOptions.coerce ? "z.coerce.string()" : "z.string()";
2910
- if (schema2.minLength !== void 0) {
3254
+ if (typeof schema2.minLength === "number" && Number.isFinite(schema2.minLength)) {
2911
3255
  zodString += `.min(${schema2.minLength})`;
2912
3256
  }
2913
- if (schema2.maxLength !== void 0) {
3257
+ if (typeof schema2.maxLength === "number" && Number.isFinite(schema2.maxLength)) {
2914
3258
  zodString += `.max(${schema2.maxLength})`;
2915
3259
  }
2916
- if (schema2.pattern) {
2917
- const escapedPattern = this.escapeRegex(schema2.pattern);
2918
- zodString += `.regex(new RegExp('${escapedPattern}'))`;
3260
+ if (typeof schema2.pattern === "string") {
3261
+ zodString += `.regex(new RegExp(${quoteLiteral(stripRegexDelimiters(schema2.pattern))}))`;
2919
3262
  }
2920
3263
  return zodString;
2921
3264
  }
@@ -2928,13 +3271,13 @@ var ZodSchemaBuilder = class {
2928
3271
  return `z.union([${literals}])`;
2929
3272
  }
2930
3273
  let zodNumber = buildOptions.coerce ? "z.coerce.number()" : "z.number()";
2931
- if (schema2.minimum !== void 0) {
3274
+ if (typeof schema2.minimum === "number" && Number.isFinite(schema2.minimum)) {
2932
3275
  zodNumber += `.min(${schema2.minimum})`;
2933
3276
  }
2934
- if (schema2.maximum !== void 0) {
3277
+ if (typeof schema2.maximum === "number" && Number.isFinite(schema2.maximum)) {
2935
3278
  zodNumber += `.max(${schema2.maximum})`;
2936
3279
  }
2937
- if (schema2.multipleOf !== void 0) {
3280
+ if (typeof schema2.multipleOf === "number" && Number.isFinite(schema2.multipleOf)) {
2938
3281
  zodNumber += `.multipleOf(${schema2.multipleOf})`;
2939
3282
  }
2940
3283
  if (schema2.type === "integer") {
@@ -2961,10 +3304,10 @@ var ZodSchemaBuilder = class {
2961
3304
  required: true
2962
3305
  });
2963
3306
  let zodArray = `z.array(${itemSchema})`;
2964
- if (schema2.minItems !== void 0) {
3307
+ if (typeof schema2.minItems === "number" && Number.isFinite(schema2.minItems)) {
2965
3308
  zodArray += `.min(${schema2.minItems})`;
2966
3309
  }
2967
- if (schema2.maxItems !== void 0) {
3310
+ if (typeof schema2.maxItems === "number" && Number.isFinite(schema2.maxItems)) {
2968
3311
  zodArray += `.max(${schema2.maxItems})`;
2969
3312
  }
2970
3313
  return zodArray;
@@ -3008,7 +3351,7 @@ var ZodSchemaBuilder = class {
3008
3351
  ...buildOptions,
3009
3352
  required: isRequired
3010
3353
  });
3011
- properties.push(` "${propName}": ${propZodSchema}`);
3354
+ properties.push(` ${emitObjectKey(propName)}: ${propZodSchema}`);
3012
3355
  }
3013
3356
  let objectSchema = `z.object({
3014
3357
  ${properties.join(",\n")}
@@ -3042,37 +3385,51 @@ ${properties.join(",\n")}
3042
3385
  }
3043
3386
  return schema2.type || "any";
3044
3387
  }
3388
+ /**
3389
+ * A default value as a zod `.default(...)` literal.
3390
+ *
3391
+ * Recursive, because a default is arbitrary JSON: object keys are spec text
3392
+ * and went into the literal raw (`{ my-key: 1 }` is a syntax error, a
3393
+ * `__proto__` key is the setter), and nested values went through
3394
+ * `String()`, which emits `[object Object]` into source. Not
3395
+ * `emitEnumMember`: that helper serializes an unknown value as a *string*
3396
+ * because a z.enum member must be one, which turned `default: ["x", null]`
3397
+ * into `['x', 'null']`.
3398
+ */
3045
3399
  generateDefaultValue(defaultValue) {
3046
3400
  if (typeof defaultValue === "string") {
3047
- return `'${this.escapeString(defaultValue)}'`;
3401
+ return quoteLiteral(defaultValue);
3048
3402
  }
3049
- if (typeof defaultValue === "number" || typeof defaultValue === "boolean") {
3403
+ if (typeof defaultValue === "boolean" || typeof defaultValue === "number" && Number.isFinite(defaultValue)) {
3050
3404
  return String(defaultValue);
3051
3405
  }
3052
3406
  if (defaultValue === null) {
3053
3407
  return "null";
3054
3408
  }
3055
3409
  if (Array.isArray(defaultValue)) {
3056
- const items = defaultValue.map((item) => typeof item === "string" ? `'${this.escapeString(item)}'` : String(item));
3057
- return `[${items.join(", ")}]`;
3410
+ return `[${defaultValue.map((item) => this.generateDefaultValue(item)).join(", ")}]`;
3058
3411
  }
3059
3412
  if (typeof defaultValue === "object") {
3060
- const entries = Object.entries(defaultValue).map(([key, value]) => {
3061
- const val = typeof value === "string" ? `'${this.escapeString(value)}'` : String(value);
3062
- return `${key}: ${val}`;
3063
- }).join(", ");
3413
+ const entries = Object.entries(defaultValue).map(([key, value]) => `${emitObjectKey(key)}: ${this.generateDefaultValue(value)}`).join(", ");
3064
3414
  return `{ ${entries} }`;
3065
3415
  }
3066
3416
  return "undefined";
3067
3417
  }
3068
- escapeString(str2) {
3069
- return str2.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n");
3418
+ };
3419
+ function stripRegexDelimiters(pattern) {
3420
+ return pattern.replace(/^\/|\/$/g, "");
3421
+ }
3422
+ __name(stripRegexDelimiters, "stripRegexDelimiters");
3423
+ function emitEnumMember(value) {
3424
+ if (typeof value === "string") {
3425
+ return quoteLiteral(value);
3070
3426
  }
3071
- escapeRegex(pattern) {
3072
- const cleaned = pattern.replace(/^\/|\/$/g, "");
3073
- return cleaned.replace(/\\/g, "\\\\");
3427
+ if (typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) {
3428
+ return String(value);
3074
3429
  }
3075
- };
3430
+ return quoteLiteral(JSON.stringify(value) ?? String(value));
3431
+ }
3432
+ __name(emitEnumMember, "emitEnumMember");
3076
3433
 
3077
3434
  // src/lib/zod-schema.generator.ts
3078
3435
  var ZodSchemaGenerator = class {
@@ -3090,7 +3447,7 @@ var ZodSchemaGenerator = class {
3090
3447
  this.schemaBuilder = new ZodSchemaBuilder(spec, config, options);
3091
3448
  }
3092
3449
  async generateParametersValidator(parameters, operationName, suffix) {
3093
- const properties = {};
3450
+ const properties = /* @__PURE__ */ new Map();
3094
3451
  const requiredFields = [];
3095
3452
  for (const param of parameters) {
3096
3453
  const schema2 = this.resolveParameterSchema(param);
@@ -3099,7 +3456,7 @@ var ZodSchemaGenerator = class {
3099
3456
  coerce: this.shouldCoerce(param.in),
3100
3457
  strict: this.isStrict(param.in)
3101
3458
  });
3102
- properties[param.name] = zodSchema;
3459
+ properties.set(param.name, zodSchema);
3103
3460
  if (param.required) {
3104
3461
  requiredFields.push(param.name);
3105
3462
  }
@@ -3190,10 +3547,12 @@ var ZodSchemaGenerator = class {
3190
3547
  return statements;
3191
3548
  }
3192
3549
  generateObjectValidator(name, properties) {
3193
- if (Object.keys(properties).length === 0) {
3550
+ if (properties.size === 0) {
3194
3551
  return `export const ${name} = z.object({});`;
3195
3552
  }
3196
- const props = Object.entries(properties).map(([key, schema2]) => ` "${key}": ${schema2}`).join(",\n");
3553
+ const props = [
3554
+ ...properties
3555
+ ].map(([key, schema2]) => ` ${emitObjectKey(key)}: ${schema2}`).join(",\n");
3197
3556
  const statements = [
3198
3557
  `export const ${name} = z.object({`,
3199
3558
  props,
@@ -3289,7 +3648,6 @@ var ZodIndexGenerator = class {
3289
3648
  });
3290
3649
  });
3291
3650
  sourceFile.formatText();
3292
- sourceFile.saveSync();
3293
3651
  }
3294
3652
  };
3295
3653
 
@@ -3337,31 +3695,36 @@ var ZodGenerator = class {
3337
3695
  this.onWarning?.("No API paths found in the specification");
3338
3696
  return;
3339
3697
  }
3340
- const controllerGroups = this.groupPathsByController(paths);
3698
+ const controllerGroups = groupOperationsByController(paths, this.onWarning);
3699
+ this.assertDistinctOperationNames(controllerGroups);
3341
3700
  await Promise.all(Object.entries(controllerGroups).map(([validatorName, operations]) => {
3342
3701
  return this.generateValidatorFile(validatorName, operations, outputDir);
3343
3702
  }));
3344
3703
  this.indexGenerator.generateIndex(outputRoot);
3345
3704
  }
3346
- groupPathsByController(paths) {
3347
- const groups = {};
3348
- paths.forEach((path3) => {
3349
- let controllerName = "Default";
3350
- if (path3.tags && path3.tags.length > 0) {
3351
- controllerName = path3.tags[0];
3352
- } else {
3353
- const pathParts = path3.path.split("/").filter((p) => p && !p.startsWith("{"));
3354
- if (pathParts.length > 1) {
3355
- controllerName = pascalCase(pathParts[1]);
3705
+ assertDistinctOperationNames(controllerGroups) {
3706
+ const byName = /* @__PURE__ */ new Map();
3707
+ for (const operations of Object.values(controllerGroups)) {
3708
+ for (const operation of operations) {
3709
+ const name = this.getOperationName(operation);
3710
+ const existing = byName.get(name);
3711
+ if (existing) {
3712
+ existing.push(operation);
3713
+ } else {
3714
+ byName.set(name, [
3715
+ operation
3716
+ ]);
3356
3717
  }
3357
3718
  }
3358
- controllerName = pascalCase(controllerName);
3359
- if (!groups[controllerName]) {
3360
- groups[controllerName] = [];
3361
- }
3362
- groups[controllerName].push(path3);
3363
- });
3364
- return groups;
3719
+ }
3720
+ const collisions = [
3721
+ ...byName.entries()
3722
+ ].filter(([, operations]) => operations.length > 1);
3723
+ if (collisions.length === 0) {
3724
+ return;
3725
+ }
3726
+ const detail = collisions.map(([name, operations]) => `"${name}" from ${operations.map(describeOperation).join(" and ")}`).join("; ");
3727
+ throw new DuplicateGeneratedNameError(`Operations map to the same zod validator name: ${detail}. Ensure each operationId maps to a unique name.`, collisions.map(([name]) => name), collisions.flatMap(([, operations]) => operations));
3365
3728
  }
3366
3729
  async generateValidatorFile(validatorName, operations, outputDir) {
3367
3730
  const fileName = `${camelCase(validatorName)}.validator.ts`;
@@ -3378,7 +3741,6 @@ var ZodGenerator = class {
3378
3741
  if (_statements.length > 0) {
3379
3742
  sourceFile.formatText();
3380
3743
  sourceFile.insertText(0, ZOD_PLUGIN_GENERATOR_HEADER_COMMENT(validatorName));
3381
- sourceFile.saveSync();
3382
3744
  } else {
3383
3745
  this.project.removeSourceFile(sourceFile);
3384
3746
  }
package/index.d.ts CHANGED
@@ -267,7 +267,11 @@ interface GeneratorConfig {
267
267
  output: string;
268
268
  /** Distinguishes tokens/providers when several clients coexist in one app. */
269
269
  clientName?: string;
270
- /** Custom acceptance check run on the parsed spec; returning false aborts generation. */
270
+ /**
271
+ * Custom acceptance check run on the parsed spec; returning false aborts
272
+ * generation. Receives the spec as authored — before deep-pointer `$ref`s
273
+ * are inlined (`core/inline-nested-refs.ts`).
274
+ */
271
275
  validateInput?: (spec: SwaggerSpec) => boolean;
272
276
  options: {
273
277
  /** How date/date-time formats are typed in generated models. */
@@ -367,7 +371,7 @@ declare class ZodGenerator implements IPluginGenerator {
367
371
  private readonly onWarning?;
368
372
  constructor(context: PluginGeneratorContext, options?: ZodPluginOptions);
369
373
  generate(outputRoot: string): Promise<void>;
370
- private groupPathsByController;
374
+ private assertDistinctOperationNames;
371
375
  private generateValidatorFile;
372
376
  private addImports;
373
377
  private generateOperationValidators;
package/index.js CHANGED
@@ -4,6 +4,238 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable:
4
4
  // src/lib/zod.generator.ts
5
5
  import * as path2 from "path";
6
6
 
7
+ // ../../shared/src/errors.ts
8
+ var NG_OPENAPI_ERROR_BRAND = "__ngOpenApiError";
9
+ var ERROR_LINEAGE = /* @__PURE__ */ new WeakMap();
10
+ var FALLBACK_LINEAGE = Object.freeze([
11
+ "NgOpenApiError"
12
+ ]);
13
+ function registerError(cls, lineage) {
14
+ ERROR_LINEAGE.set(cls, Object.freeze([
15
+ ...lineage
16
+ ]));
17
+ return cls;
18
+ }
19
+ __name(registerError, "registerError");
20
+ function inheritedLineage(cls) {
21
+ for (let current = cls; typeof current === "function"; current = Object.getPrototypeOf(current)) {
22
+ const lineage = ERROR_LINEAGE.get(current);
23
+ if (lineage) {
24
+ return lineage;
25
+ }
26
+ }
27
+ return FALLBACK_LINEAGE;
28
+ }
29
+ __name(inheritedLineage, "inheritedLineage");
30
+ var NgOpenApiError = class extends Error {
31
+ static {
32
+ __name(this, "NgOpenApiError");
33
+ }
34
+ /** The underlying error that caused this one, when there is one. */
35
+ cause;
36
+ constructor(message, cause) {
37
+ super(message);
38
+ const lineage = inheritedLineage(new.target);
39
+ this.name = lineage[0];
40
+ this.cause = cause;
41
+ Object.defineProperty(this, NG_OPENAPI_ERROR_BRAND, {
42
+ value: lineage,
43
+ enumerable: false,
44
+ writable: false,
45
+ configurable: false
46
+ });
47
+ }
48
+ /**
49
+ * `message` and `name` are non-enumerable on Error, so the default
50
+ * JSON.stringify dropped both — the least useful possible serialization for
51
+ * something that exists to be logged.
52
+ *
53
+ * The payload is spread rather than enumerated: `source`, `issues`,
54
+ * `operation`, `names` and `placeholders` are why these classes are typed
55
+ * in the first place, and listing fields by hand silently drops whichever
56
+ * ones a later subclass adds.
57
+ */
58
+ toJSON() {
59
+ const cause = this.cause instanceof Error ? this.cause.message : this.cause;
60
+ return {
61
+ name: this.name,
62
+ message: this.message,
63
+ ...cause === void 0 ? {} : {
64
+ cause
65
+ },
66
+ // Own enumerable properties: the brand is deliberately not one.
67
+ ...Object.fromEntries(Object.entries(this).filter(([key]) => key !== "cause"))
68
+ };
69
+ }
70
+ /**
71
+ * Recognizes branded errors from another bundled copy of this module, so
72
+ * `error instanceof SpecLoadError` works for a plugin-thrown error too.
73
+ * The prototype chain is checked first, so a caller's own subclass of these
74
+ * classes still matches even though it carries no lineage entry.
75
+ *
76
+ * Never throws and never runs foreign code: both reflective reads sit
77
+ * inside the try, because a Proxy traps `getPrototypeOf` just as readily as
78
+ * `getOwnPropertyDescriptor`.
79
+ */
80
+ static [Symbol.hasInstance](value) {
81
+ if (typeof value !== "object" || value === null) {
82
+ return false;
83
+ }
84
+ try {
85
+ if (Object.prototype.isPrototypeOf.call(this.prototype, value)) {
86
+ return true;
87
+ }
88
+ const expected = ERROR_LINEAGE.get(this)?.[0];
89
+ if (expected === void 0) {
90
+ return false;
91
+ }
92
+ const descriptor = Object.getOwnPropertyDescriptor(value, NG_OPENAPI_ERROR_BRAND);
93
+ if (!descriptor || descriptor.enumerable || !("value" in descriptor)) {
94
+ return false;
95
+ }
96
+ return Array.isArray(descriptor.value) && descriptor.value.includes(expected);
97
+ } catch {
98
+ return false;
99
+ }
100
+ }
101
+ };
102
+ registerError(NgOpenApiError, [
103
+ "NgOpenApiError"
104
+ ]);
105
+ var SpecLoadError = class extends NgOpenApiError {
106
+ static {
107
+ __name(this, "SpecLoadError");
108
+ }
109
+ /** The file path or URL that failed to load. */
110
+ source;
111
+ constructor(message, source, cause) {
112
+ super(message, cause);
113
+ this.source = source;
114
+ }
115
+ };
116
+ registerError(SpecLoadError, [
117
+ "SpecLoadError",
118
+ "NgOpenApiError"
119
+ ]);
120
+ var SpecParseError = class extends NgOpenApiError {
121
+ static {
122
+ __name(this, "SpecParseError");
123
+ }
124
+ /** The file path or URL the content came from, when known. */
125
+ source;
126
+ constructor(message, source, cause) {
127
+ super(message, cause);
128
+ this.source = source;
129
+ }
130
+ };
131
+ registerError(SpecParseError, [
132
+ "SpecParseError",
133
+ "NgOpenApiError"
134
+ ]);
135
+ function describeOperation(operation) {
136
+ const location = `(${operation.method}) ${operation.path}`;
137
+ return operation.operationId ? `${operation.operationId} (${location})` : location;
138
+ }
139
+ __name(describeOperation, "describeOperation");
140
+ function captureOperation(operation) {
141
+ return Object.freeze({
142
+ operationId: operation.operationId,
143
+ method: operation.method,
144
+ path: operation.path
145
+ });
146
+ }
147
+ __name(captureOperation, "captureOperation");
148
+ var InvalidIdentifierError = class extends NgOpenApiError {
149
+ static {
150
+ __name(this, "InvalidIdentifierError");
151
+ }
152
+ /** The rejected name, verbatim; absent when no name could be derived. */
153
+ identifier;
154
+ /** The operation whose name was being derived. */
155
+ operation;
156
+ constructor(message, operation, identifier) {
157
+ super(message);
158
+ this.operation = captureOperation(operation);
159
+ this.identifier = identifier;
160
+ }
161
+ };
162
+ registerError(InvalidIdentifierError, [
163
+ "InvalidIdentifierError",
164
+ "NgOpenApiError"
165
+ ]);
166
+ var DuplicateGeneratedNameError = class extends NgOpenApiError {
167
+ static {
168
+ __name(this, "DuplicateGeneratedNameError");
169
+ }
170
+ /** The colliding generated names. */
171
+ names;
172
+ /** The operations that produced them, when known. */
173
+ operations;
174
+ constructor(message, names, operations = []) {
175
+ super(message);
176
+ this.names = Object.freeze([
177
+ ...names
178
+ ]);
179
+ this.operations = Object.freeze(operations.map(captureOperation));
180
+ }
181
+ };
182
+ registerError(DuplicateGeneratedNameError, [
183
+ "DuplicateGeneratedNameError",
184
+ "NgOpenApiError"
185
+ ]);
186
+ var UnresolvedPathTemplateError = class extends NgOpenApiError {
187
+ static {
188
+ __name(this, "UnresolvedPathTemplateError");
189
+ }
190
+ /** The path as written in the spec. */
191
+ path;
192
+ /** Placeholder names with no declared parameter. */
193
+ placeholders;
194
+ constructor(message, path3, placeholders) {
195
+ super(message);
196
+ this.path = path3;
197
+ this.placeholders = Object.freeze([
198
+ ...placeholders
199
+ ]);
200
+ }
201
+ };
202
+ registerError(UnresolvedPathTemplateError, [
203
+ "UnresolvedPathTemplateError",
204
+ "NgOpenApiError"
205
+ ]);
206
+ var ConfigValidationError = class extends NgOpenApiError {
207
+ static {
208
+ __name(this, "ConfigValidationError");
209
+ }
210
+ issues;
211
+ constructor(issues) {
212
+ super(`Invalid ng-openapi configuration:
213
+ ${issues.map((issue) => ` - ${issue}`).join("\n")}`);
214
+ this.issues = Object.freeze([
215
+ ...issues
216
+ ]);
217
+ }
218
+ };
219
+ registerError(ConfigValidationError, [
220
+ "ConfigValidationError",
221
+ "NgOpenApiError"
222
+ ]);
223
+ var ConfigLoadError = class extends NgOpenApiError {
224
+ static {
225
+ __name(this, "ConfigLoadError");
226
+ }
227
+ /** Path of the config file that failed to load. */
228
+ source;
229
+ constructor(message, source, cause) {
230
+ super(message, cause);
231
+ this.source = source;
232
+ }
233
+ };
234
+ registerError(ConfigLoadError, [
235
+ "ConfigLoadError",
236
+ "NgOpenApiError"
237
+ ]);
238
+
7
239
  // ../../../node_modules/js-yaml/dist/js-yaml.mjs
8
240
  function isNothing(subject) {
9
241
  return typeof subject === "undefined" || subject === null;
@@ -2706,6 +2938,27 @@ var safeLoad = renamed("safeLoad", "load");
2706
2938
  var safeLoadAll = renamed("safeLoadAll", "loadAll");
2707
2939
  var safeDump = renamed("safeDump", "dump");
2708
2940
 
2941
+ // ../../shared/src/utils/string.utils.ts
2942
+ var IDENTIFIER_SEPARATORS = /(?:_|[^\p{ID_Continue}$])+(.)?/gu;
2943
+ var INVALID_IDENTIFIER_START = /^[^\p{ID_Start}$_]/u;
2944
+ function toIdentifier(converted) {
2945
+ if (converted === "") {
2946
+ return "_";
2947
+ }
2948
+ return converted.replace(INVALID_IDENTIFIER_START, (char) => `_${char}`);
2949
+ }
2950
+ __name(toIdentifier, "toIdentifier");
2951
+ function camelCase(str2) {
2952
+ const converted = str2.replace(IDENTIFIER_SEPARATORS, (_, char) => char ? char.toUpperCase() : "").replace(/^./u, (char) => char.toLowerCase());
2953
+ return toIdentifier(converted);
2954
+ }
2955
+ __name(camelCase, "camelCase");
2956
+ function pascalCase(str2) {
2957
+ const converted = str2.replace(IDENTIFIER_SEPARATORS, (_, char) => char ? char.toUpperCase() : "").replace(/^./u, (char) => char.toUpperCase());
2958
+ return toIdentifier(converted);
2959
+ }
2960
+ __name(pascalCase, "pascalCase");
2961
+
2709
2962
  // ../../shared/src/utils/content-types.constants.ts
2710
2963
  var CONTENT_TYPES = {
2711
2964
  MULTIPART: "multipart/form-data",
@@ -2713,15 +2966,47 @@ var CONTENT_TYPES = {
2713
2966
  JSON: "application/json"
2714
2967
  };
2715
2968
 
2716
- // ../../shared/src/utils/string.utils.ts
2717
- function camelCase(str2) {
2718
- return str2.replace(/[-_.\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "").replace(/^./, (char) => char.toLowerCase());
2969
+ // ../../shared/src/emit/literal.emit.ts
2970
+ function quoteLiteral(value) {
2971
+ return `'${escapeSingleQuoted(value)}'`;
2719
2972
  }
2720
- __name(camelCase, "camelCase");
2721
- function pascalCase(str2) {
2722
- return str2.replace(/[-_.\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "").replace(/^./, (char) => char.toUpperCase());
2973
+ __name(quoteLiteral, "quoteLiteral");
2974
+ function escapeSingleQuoted(value) {
2975
+ return value.replace(/[\\']/g, (char) => `\\${char}`).replace(/\r/g, "\\r").replace(/\n/g, "\\n");
2723
2976
  }
2724
- __name(pascalCase, "pascalCase");
2977
+ __name(escapeSingleQuoted, "escapeSingleQuoted");
2978
+ function emitObjectKey(name, quoteStyle = "double") {
2979
+ const quoted = quoteStyle === "single" ? quoteLiteral(name) : `"${escapeDoubleQuoted(name)}"`;
2980
+ return name === "__proto__" ? `[${quoted}]` : quoted;
2981
+ }
2982
+ __name(emitObjectKey, "emitObjectKey");
2983
+ function escapeDoubleQuoted(value) {
2984
+ return value.replace(/[\\"]/g, (char) => `\\${char}`).replace(/\r/g, "\\r").replace(/\n/g, "\\n");
2985
+ }
2986
+ __name(escapeDoubleQuoted, "escapeDoubleQuoted");
2987
+
2988
+ // ../../shared/src/utils/functions/argument-names.ts
2989
+ var SERVICE_ARGUMENT_PROFILE = Object.freeze({
2990
+ reserved: Object.freeze([
2991
+ "observe",
2992
+ "options",
2993
+ "url",
2994
+ "params",
2995
+ "headers",
2996
+ "formData",
2997
+ "formBody"
2998
+ ]),
2999
+ bindsRequestBody: true
3000
+ });
3001
+ var RESOURCE_ARGUMENT_PROFILE = Object.freeze({
3002
+ reserved: Object.freeze([
3003
+ "resourceOptions",
3004
+ "requestOptions",
3005
+ "params",
3006
+ "headers"
3007
+ ]),
3008
+ bindsRequestBody: false
3009
+ });
2725
3010
 
2726
3011
  // ../../shared/src/utils/project.utils.ts
2727
3012
  function listGeneratedFileNames(project, directoryPath, suffix) {
@@ -2733,6 +3018,65 @@ function listGeneratedFileNames(project, directoryPath, suffix) {
2733
3018
  }
2734
3019
  __name(listGeneratedFileNames, "listGeneratedFileNames");
2735
3020
 
3021
+ // ../../shared/src/utils/functions/controller-groups.ts
3022
+ function groupOperationsByController(operations, onWarning) {
3023
+ const groups = {};
3024
+ const controllerByFold = /* @__PURE__ */ new Map();
3025
+ const tagSpellings = /* @__PURE__ */ new Map();
3026
+ const namelessTags = /* @__PURE__ */ new Set();
3027
+ operations.forEach((operation) => {
3028
+ const tag = operation.tags?.[0];
3029
+ let rawName = "Default";
3030
+ if (tag !== void 0) {
3031
+ rawName = tag;
3032
+ } else {
3033
+ const pathParts = operation.path.split("/").filter((part) => part && !part.startsWith("{"));
3034
+ if (pathParts.length > 1) {
3035
+ rawName = pathParts[1];
3036
+ }
3037
+ }
3038
+ const sanitized = pascalCase(rawName);
3039
+ const isNameless = !/\p{L}/u.test(sanitized);
3040
+ const candidate = isNameless ? "Default" : sanitized;
3041
+ const fold = candidate.toLowerCase();
3042
+ const controllerName = controllerByFold.get(fold) ?? candidate;
3043
+ controllerByFold.set(fold, controllerName);
3044
+ if (tag !== void 0 && isNameless) {
3045
+ namelessTags.add(tag);
3046
+ } else if (tag !== void 0) {
3047
+ const spellings = tagSpellings.get(controllerName) ?? /* @__PURE__ */ new Set();
3048
+ spellings.add(tag);
3049
+ tagSpellings.set(controllerName, spellings);
3050
+ }
3051
+ if (!groups[controllerName]) {
3052
+ groups[controllerName] = [];
3053
+ }
3054
+ groups[controllerName].push(operation);
3055
+ });
3056
+ for (const tag of namelessTags) {
3057
+ onWarning?.(`Tag "${tag}" contains no characters usable in a name \u2014 its operations are generated into the "Default" controller. Rename the tag to give them a file of their own.`);
3058
+ }
3059
+ for (const [controllerName, spellings] of tagSpellings) {
3060
+ if (spellings.size > 1) {
3061
+ onWarning?.(`Tags ${[
3062
+ ...spellings
3063
+ ].map((name) => `"${name}"`).join(" and ")} all map to the controller "${controllerName}" \u2014 their operations are generated into one file. Rename one tag to keep them apart.`);
3064
+ }
3065
+ }
3066
+ return groups;
3067
+ }
3068
+ __name(groupOperationsByController, "groupOperationsByController");
3069
+
3070
+ // ../../shared/src/utils/functions/method-names.ts
3071
+ var RESERVED_MEMBER_NAMES = Object.freeze([
3072
+ "constructor",
3073
+ "httpClient",
3074
+ "basePath",
3075
+ "clientContextToken",
3076
+ "createContextWithClientId"
3077
+ ]);
3078
+ var RESERVED_MEMBER_SET = new Set(RESERVED_MEMBER_NAMES);
3079
+
2736
3080
  // ../../shared/src/config/constants.ts
2737
3081
  var disableLinting = `// @ts-nocheck
2738
3082
  /* eslint-disable */
@@ -2832,14 +3176,14 @@ var ZodSchemaBuilder = class {
2832
3176
  } else if (!buildOptions.required) {
2833
3177
  zodSchema = `${zodSchema}.optional()`;
2834
3178
  }
2835
- if (schema2.description) {
2836
- zodSchema = `${zodSchema}.describe('${this.escapeString(schema2.description)}')`;
3179
+ if (typeof schema2.description === "string" && schema2.description) {
3180
+ zodSchema = `${zodSchema}.describe('${escapeSingleQuoted(schema2.description)}')`;
2837
3181
  }
2838
3182
  return zodSchema;
2839
3183
  }
2840
3184
  async buildStringSchema(schema2, buildOptions) {
2841
3185
  if (schema2.enum && schema2.enum.every((v) => typeof v === "string")) {
2842
- const enumValues = schema2.enum.map((v) => `'${this.escapeString(String(v))}'`).join(", ");
3186
+ const enumValues = schema2.enum.map((v) => emitEnumMember(v)).join(", ");
2843
3187
  return `z.enum([${enumValues}])`;
2844
3188
  }
2845
3189
  if (schema2.format) {
@@ -2873,15 +3217,14 @@ var ZodSchemaBuilder = class {
2873
3217
  }
2874
3218
  }
2875
3219
  let zodString = buildOptions.coerce ? "z.coerce.string()" : "z.string()";
2876
- if (schema2.minLength !== void 0) {
3220
+ if (typeof schema2.minLength === "number" && Number.isFinite(schema2.minLength)) {
2877
3221
  zodString += `.min(${schema2.minLength})`;
2878
3222
  }
2879
- if (schema2.maxLength !== void 0) {
3223
+ if (typeof schema2.maxLength === "number" && Number.isFinite(schema2.maxLength)) {
2880
3224
  zodString += `.max(${schema2.maxLength})`;
2881
3225
  }
2882
- if (schema2.pattern) {
2883
- const escapedPattern = this.escapeRegex(schema2.pattern);
2884
- zodString += `.regex(new RegExp('${escapedPattern}'))`;
3226
+ if (typeof schema2.pattern === "string") {
3227
+ zodString += `.regex(new RegExp(${quoteLiteral(stripRegexDelimiters(schema2.pattern))}))`;
2885
3228
  }
2886
3229
  return zodString;
2887
3230
  }
@@ -2894,13 +3237,13 @@ var ZodSchemaBuilder = class {
2894
3237
  return `z.union([${literals}])`;
2895
3238
  }
2896
3239
  let zodNumber = buildOptions.coerce ? "z.coerce.number()" : "z.number()";
2897
- if (schema2.minimum !== void 0) {
3240
+ if (typeof schema2.minimum === "number" && Number.isFinite(schema2.minimum)) {
2898
3241
  zodNumber += `.min(${schema2.minimum})`;
2899
3242
  }
2900
- if (schema2.maximum !== void 0) {
3243
+ if (typeof schema2.maximum === "number" && Number.isFinite(schema2.maximum)) {
2901
3244
  zodNumber += `.max(${schema2.maximum})`;
2902
3245
  }
2903
- if (schema2.multipleOf !== void 0) {
3246
+ if (typeof schema2.multipleOf === "number" && Number.isFinite(schema2.multipleOf)) {
2904
3247
  zodNumber += `.multipleOf(${schema2.multipleOf})`;
2905
3248
  }
2906
3249
  if (schema2.type === "integer") {
@@ -2927,10 +3270,10 @@ var ZodSchemaBuilder = class {
2927
3270
  required: true
2928
3271
  });
2929
3272
  let zodArray = `z.array(${itemSchema})`;
2930
- if (schema2.minItems !== void 0) {
3273
+ if (typeof schema2.minItems === "number" && Number.isFinite(schema2.minItems)) {
2931
3274
  zodArray += `.min(${schema2.minItems})`;
2932
3275
  }
2933
- if (schema2.maxItems !== void 0) {
3276
+ if (typeof schema2.maxItems === "number" && Number.isFinite(schema2.maxItems)) {
2934
3277
  zodArray += `.max(${schema2.maxItems})`;
2935
3278
  }
2936
3279
  return zodArray;
@@ -2974,7 +3317,7 @@ var ZodSchemaBuilder = class {
2974
3317
  ...buildOptions,
2975
3318
  required: isRequired
2976
3319
  });
2977
- properties.push(` "${propName}": ${propZodSchema}`);
3320
+ properties.push(` ${emitObjectKey(propName)}: ${propZodSchema}`);
2978
3321
  }
2979
3322
  let objectSchema = `z.object({
2980
3323
  ${properties.join(",\n")}
@@ -3008,37 +3351,51 @@ ${properties.join(",\n")}
3008
3351
  }
3009
3352
  return schema2.type || "any";
3010
3353
  }
3354
+ /**
3355
+ * A default value as a zod `.default(...)` literal.
3356
+ *
3357
+ * Recursive, because a default is arbitrary JSON: object keys are spec text
3358
+ * and went into the literal raw (`{ my-key: 1 }` is a syntax error, a
3359
+ * `__proto__` key is the setter), and nested values went through
3360
+ * `String()`, which emits `[object Object]` into source. Not
3361
+ * `emitEnumMember`: that helper serializes an unknown value as a *string*
3362
+ * because a z.enum member must be one, which turned `default: ["x", null]`
3363
+ * into `['x', 'null']`.
3364
+ */
3011
3365
  generateDefaultValue(defaultValue) {
3012
3366
  if (typeof defaultValue === "string") {
3013
- return `'${this.escapeString(defaultValue)}'`;
3367
+ return quoteLiteral(defaultValue);
3014
3368
  }
3015
- if (typeof defaultValue === "number" || typeof defaultValue === "boolean") {
3369
+ if (typeof defaultValue === "boolean" || typeof defaultValue === "number" && Number.isFinite(defaultValue)) {
3016
3370
  return String(defaultValue);
3017
3371
  }
3018
3372
  if (defaultValue === null) {
3019
3373
  return "null";
3020
3374
  }
3021
3375
  if (Array.isArray(defaultValue)) {
3022
- const items = defaultValue.map((item) => typeof item === "string" ? `'${this.escapeString(item)}'` : String(item));
3023
- return `[${items.join(", ")}]`;
3376
+ return `[${defaultValue.map((item) => this.generateDefaultValue(item)).join(", ")}]`;
3024
3377
  }
3025
3378
  if (typeof defaultValue === "object") {
3026
- const entries = Object.entries(defaultValue).map(([key, value]) => {
3027
- const val = typeof value === "string" ? `'${this.escapeString(value)}'` : String(value);
3028
- return `${key}: ${val}`;
3029
- }).join(", ");
3379
+ const entries = Object.entries(defaultValue).map(([key, value]) => `${emitObjectKey(key)}: ${this.generateDefaultValue(value)}`).join(", ");
3030
3380
  return `{ ${entries} }`;
3031
3381
  }
3032
3382
  return "undefined";
3033
3383
  }
3034
- escapeString(str2) {
3035
- return str2.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n");
3384
+ };
3385
+ function stripRegexDelimiters(pattern) {
3386
+ return pattern.replace(/^\/|\/$/g, "");
3387
+ }
3388
+ __name(stripRegexDelimiters, "stripRegexDelimiters");
3389
+ function emitEnumMember(value) {
3390
+ if (typeof value === "string") {
3391
+ return quoteLiteral(value);
3036
3392
  }
3037
- escapeRegex(pattern) {
3038
- const cleaned = pattern.replace(/^\/|\/$/g, "");
3039
- return cleaned.replace(/\\/g, "\\\\");
3393
+ if (typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) {
3394
+ return String(value);
3040
3395
  }
3041
- };
3396
+ return quoteLiteral(JSON.stringify(value) ?? String(value));
3397
+ }
3398
+ __name(emitEnumMember, "emitEnumMember");
3042
3399
 
3043
3400
  // src/lib/zod-schema.generator.ts
3044
3401
  var ZodSchemaGenerator = class {
@@ -3056,7 +3413,7 @@ var ZodSchemaGenerator = class {
3056
3413
  this.schemaBuilder = new ZodSchemaBuilder(spec, config, options);
3057
3414
  }
3058
3415
  async generateParametersValidator(parameters, operationName, suffix) {
3059
- const properties = {};
3416
+ const properties = /* @__PURE__ */ new Map();
3060
3417
  const requiredFields = [];
3061
3418
  for (const param of parameters) {
3062
3419
  const schema2 = this.resolveParameterSchema(param);
@@ -3065,7 +3422,7 @@ var ZodSchemaGenerator = class {
3065
3422
  coerce: this.shouldCoerce(param.in),
3066
3423
  strict: this.isStrict(param.in)
3067
3424
  });
3068
- properties[param.name] = zodSchema;
3425
+ properties.set(param.name, zodSchema);
3069
3426
  if (param.required) {
3070
3427
  requiredFields.push(param.name);
3071
3428
  }
@@ -3156,10 +3513,12 @@ var ZodSchemaGenerator = class {
3156
3513
  return statements;
3157
3514
  }
3158
3515
  generateObjectValidator(name, properties) {
3159
- if (Object.keys(properties).length === 0) {
3516
+ if (properties.size === 0) {
3160
3517
  return `export const ${name} = z.object({});`;
3161
3518
  }
3162
- const props = Object.entries(properties).map(([key, schema2]) => ` "${key}": ${schema2}`).join(",\n");
3519
+ const props = [
3520
+ ...properties
3521
+ ].map(([key, schema2]) => ` ${emitObjectKey(key)}: ${schema2}`).join(",\n");
3163
3522
  const statements = [
3164
3523
  `export const ${name} = z.object({`,
3165
3524
  props,
@@ -3255,7 +3614,6 @@ var ZodIndexGenerator = class {
3255
3614
  });
3256
3615
  });
3257
3616
  sourceFile.formatText();
3258
- sourceFile.saveSync();
3259
3617
  }
3260
3618
  };
3261
3619
 
@@ -3303,31 +3661,36 @@ var ZodGenerator = class {
3303
3661
  this.onWarning?.("No API paths found in the specification");
3304
3662
  return;
3305
3663
  }
3306
- const controllerGroups = this.groupPathsByController(paths);
3664
+ const controllerGroups = groupOperationsByController(paths, this.onWarning);
3665
+ this.assertDistinctOperationNames(controllerGroups);
3307
3666
  await Promise.all(Object.entries(controllerGroups).map(([validatorName, operations]) => {
3308
3667
  return this.generateValidatorFile(validatorName, operations, outputDir);
3309
3668
  }));
3310
3669
  this.indexGenerator.generateIndex(outputRoot);
3311
3670
  }
3312
- groupPathsByController(paths) {
3313
- const groups = {};
3314
- paths.forEach((path3) => {
3315
- let controllerName = "Default";
3316
- if (path3.tags && path3.tags.length > 0) {
3317
- controllerName = path3.tags[0];
3318
- } else {
3319
- const pathParts = path3.path.split("/").filter((p) => p && !p.startsWith("{"));
3320
- if (pathParts.length > 1) {
3321
- controllerName = pascalCase(pathParts[1]);
3671
+ assertDistinctOperationNames(controllerGroups) {
3672
+ const byName = /* @__PURE__ */ new Map();
3673
+ for (const operations of Object.values(controllerGroups)) {
3674
+ for (const operation of operations) {
3675
+ const name = this.getOperationName(operation);
3676
+ const existing = byName.get(name);
3677
+ if (existing) {
3678
+ existing.push(operation);
3679
+ } else {
3680
+ byName.set(name, [
3681
+ operation
3682
+ ]);
3322
3683
  }
3323
3684
  }
3324
- controllerName = pascalCase(controllerName);
3325
- if (!groups[controllerName]) {
3326
- groups[controllerName] = [];
3327
- }
3328
- groups[controllerName].push(path3);
3329
- });
3330
- return groups;
3685
+ }
3686
+ const collisions = [
3687
+ ...byName.entries()
3688
+ ].filter(([, operations]) => operations.length > 1);
3689
+ if (collisions.length === 0) {
3690
+ return;
3691
+ }
3692
+ const detail = collisions.map(([name, operations]) => `"${name}" from ${operations.map(describeOperation).join(" and ")}`).join("; ");
3693
+ throw new DuplicateGeneratedNameError(`Operations map to the same zod validator name: ${detail}. Ensure each operationId maps to a unique name.`, collisions.map(([name]) => name), collisions.flatMap(([, operations]) => operations));
3331
3694
  }
3332
3695
  async generateValidatorFile(validatorName, operations, outputDir) {
3333
3696
  const fileName = `${camelCase(validatorName)}.validator.ts`;
@@ -3344,7 +3707,6 @@ var ZodGenerator = class {
3344
3707
  if (_statements.length > 0) {
3345
3708
  sourceFile.formatText();
3346
3709
  sourceFile.insertText(0, ZOD_PLUGIN_GENERATOR_HEADER_COMMENT(validatorName));
3347
- sourceFile.saveSync();
3348
3710
  } else {
3349
3711
  this.project.removeSourceFile(sourceFile);
3350
3712
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ng-openapi/zod",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "Zod validation plugin for ng-openapi - Generate Zod schemas from OpenAPI specifications",
5
5
  "keywords": [
6
6
  "angular",