ng-openapi 0.5.0 → 0.5.1-pr-137-feat-enum-name-extensions-941f4c5.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 (5) hide show
  1. package/README.md +2 -1
  2. package/cli.cjs +146 -83
  3. package/index.d.ts +26 -4
  4. package/index.js +146 -86
  5. package/package.json +1 -1
package/README.md CHANGED
@@ -114,7 +114,8 @@ ng-openapi -i ./swagger.json -o ./src/api --date-type string
114
114
  - `compilerOptions` - TypeScript compiler options for code generation
115
115
  - `package` - `{ name, version?, repository?, publishRegistry?, angularVersion?, packageJson? }`; emits `package.json`, `ng-package.json`, `tsconfig.json`, `README.md` and `.gitignore` so the output builds with ng-packagr and publishes as a standalone Angular library (see the [publishing guide](https://ng-openapi.dev/guide/npm-package))
116
116
  - `options.generateServices` - Generate Angular services (default: `true`)
117
- - `options.generateEnumBasedOnDescription` - Parse enum values from description field (default: `false`)
117
+ - `options.generateEnumBasedOnDescription` - Read enum member names from a JSON-encoded description field (default: `false`)
118
+ - `options.enumNameExtensions` - Vendor extensions to read enum member names from, e.g. `['x-enum-varnames', 'x-enumNames']` (default: none)
118
119
  - `options.validation` - `{ response?: boolean }`; adds a `parse` hook to generated methods for response validation
119
120
  - `options.customHeaders` - Headers to add to all HTTP requests
120
121
  - `options.responseTypeMapping` - Map content types to Angular HttpClient response types
package/cli.cjs CHANGED
@@ -1295,12 +1295,101 @@ function getResponseType(response, config) {
1295
1295
  }
1296
1296
  __name(getResponseType, "getResponseType");
1297
1297
 
1298
+ // ../shared/src/core/enum-member-names.ts
1299
+ function resolveEnumMemberNames(schemaName, definition, config, onWarning) {
1300
+ const values = definition.enum;
1301
+ if (!Array.isArray(values) || values.length === 0) {
1302
+ return void 0;
1303
+ }
1304
+ const { enumNameExtensions = [], generateEnumBasedOnDescription } = config.options;
1305
+ const warn = /* @__PURE__ */ __name((message) => onWarning?.(`Enum "${schemaName}": ${message}`), "warn");
1306
+ for (const extension of enumNameExtensions) {
1307
+ const names = namesFromExtension(definition, extension, values.length, warn);
1308
+ if (names) {
1309
+ return names;
1310
+ }
1311
+ }
1312
+ return generateEnumBasedOnDescription ? namesFromDescription(definition.description, values, warn) : void 0;
1313
+ }
1314
+ __name(resolveEnumMemberNames, "resolveEnumMemberNames");
1315
+ function namesFromExtension(definition, extension, valueCount, warn) {
1316
+ if (!Object.prototype.hasOwnProperty.call(definition, extension)) {
1317
+ return void 0;
1318
+ }
1319
+ const candidates = definition[extension];
1320
+ if (!Array.isArray(candidates) || candidates.length !== valueCount || !candidates.every((candidate) => typeof candidate === "string")) {
1321
+ warn(`\`${extension}\` must be an array of ${valueCount} strings, one per enum value \u2014 ignoring it`);
1322
+ return void 0;
1323
+ }
1324
+ return toMemberNames(`\`${extension}\``, candidates, warn);
1325
+ }
1326
+ __name(namesFromExtension, "namesFromExtension");
1327
+ function namesFromDescription(description, values, warn) {
1328
+ if (typeof description !== "string") {
1329
+ return void 0;
1330
+ }
1331
+ const reject = /* @__PURE__ */ __name((reason) => {
1332
+ if (/^\s*[[{]/.test(description)) {
1333
+ warn(`description looks like JSON (generateEnumBasedOnDescription) but could not be used: ${reason} \u2014 falling back to raw enum values`);
1334
+ }
1335
+ return void 0;
1336
+ }, "reject");
1337
+ let parsed;
1338
+ try {
1339
+ parsed = JSON.parse(description);
1340
+ } catch {
1341
+ return reject("it does not parse");
1342
+ }
1343
+ if (!Array.isArray(parsed) || !parsed.every(isEnumValueObject)) {
1344
+ return reject('expected an array of { "Name": string, "Value": string | number } objects');
1345
+ }
1346
+ const nameByValue = /* @__PURE__ */ new Map();
1347
+ for (const { Name, Value } of parsed) {
1348
+ if (!nameByValue.has(Value)) {
1349
+ nameByValue.set(Value, Name);
1350
+ }
1351
+ }
1352
+ const candidates = [];
1353
+ for (const value of values) {
1354
+ const name = nameByValue.get(value);
1355
+ if (name === void 0) {
1356
+ return reject(`no Name for enum value ${JSON.stringify(value)}`);
1357
+ }
1358
+ candidates.push(name);
1359
+ }
1360
+ return toMemberNames("the description", candidates, warn);
1361
+ }
1362
+ __name(namesFromDescription, "namesFromDescription");
1363
+ function isEnumValueObject(candidate) {
1364
+ return isPlainObject(candidate) && typeof candidate["Name"] === "string" && (typeof candidate["Value"] === "string" || typeof candidate["Value"] === "number");
1365
+ }
1366
+ __name(isEnumValueObject, "isEnumValueObject");
1367
+ function toMemberNames(source, candidates, warn) {
1368
+ const names = candidates.map(toMemberName);
1369
+ const seen = /* @__PURE__ */ new Set();
1370
+ for (const name of names) {
1371
+ if (seen.has(name)) {
1372
+ warn(`names from ${source} are not unique ("${name}" occurs more than once) \u2014 falling back to raw enum values`);
1373
+ return void 0;
1374
+ }
1375
+ seen.add(name);
1376
+ }
1377
+ return names;
1378
+ }
1379
+ __name(toMemberNames, "toMemberNames");
1380
+ function toMemberName(name) {
1381
+ return isValidIdentifier(name) && name !== "__proto__" ? name : pascalCaseForEnums(name);
1382
+ }
1383
+ __name(toMemberName, "toMemberName");
1384
+
1298
1385
  // ../shared/src/core/normalize.ts
1299
- function normalizeSpec(spec, onWarning) {
1386
+ function normalizeSpec(spec, onWarning, enumNaming = {
1387
+ options: {}
1388
+ }) {
1300
1389
  const rawDefinitions = spec.definitions || spec.components?.schemas || {};
1301
1390
  const definitions = Object.fromEntries(Object.entries(rawDefinitions).map(([name, definition]) => [
1302
1391
  name,
1303
- normalizeSchema(definition)
1392
+ nameEnumMembers(name, normalizeSchema(definition), enumNaming, onWarning)
1304
1393
  ]));
1305
1394
  const resolveReference = /* @__PURE__ */ __name((ref) => {
1306
1395
  const parts = ref.split("/");
@@ -1326,6 +1415,15 @@ function normalizeSpec(spec, onWarning) {
1326
1415
  };
1327
1416
  }
1328
1417
  __name(normalizeSpec, "normalizeSpec");
1418
+ function nameEnumMembers(name, definition, enumNaming, onWarning) {
1419
+ delete definition.enumMemberNames;
1420
+ const names = resolveEnumMemberNames(name, definition, enumNaming, onWarning);
1421
+ if (names) {
1422
+ definition.enumMemberNames = names;
1423
+ }
1424
+ return definition;
1425
+ }
1426
+ __name(nameEnumMembers, "nameEnumMembers");
1329
1427
  function infoText(value) {
1330
1428
  if (typeof value === "string") {
1331
1429
  return value;
@@ -1498,9 +1596,11 @@ var SwaggerParser = class _SwaggerParser {
1498
1596
  normalized;
1499
1597
  /** Non-fatal problems found while normalizing — a parameter with no usable name, for one. */
1500
1598
  onWarning;
1501
- constructor(spec, onWarning) {
1599
+ enumNaming;
1600
+ constructor(spec, onWarning, enumNaming) {
1502
1601
  this.spec = spec;
1503
1602
  this.onWarning = onWarning;
1603
+ this.enumNaming = enumNaming;
1504
1604
  }
1505
1605
  /**
1506
1606
  * Loads, parses and wraps a spec.
@@ -1526,7 +1626,7 @@ var SwaggerParser = class _SwaggerParser {
1526
1626
  } catch (error) {
1527
1627
  throw new SpecParseError(`Failed to inline nested $refs in the spec: ${error instanceof Error ? error.message : String(error)}`, swaggerPathOrUrl, error);
1528
1628
  }
1529
- return new _SwaggerParser(inlinedSpec, onWarning);
1629
+ return new _SwaggerParser(inlinedSpec, onWarning, config);
1530
1630
  }
1531
1631
  /**
1532
1632
  * The version-free model generators consume. Computed once and cached —
@@ -1534,7 +1634,7 @@ var SwaggerParser = class _SwaggerParser {
1534
1634
  * can be used as Map keys across generators.
1535
1635
  */
1536
1636
  getNormalizedSpec() {
1537
- this.normalized ??= normalizeSpec(this.spec, this.onWarning);
1637
+ this.normalized ??= normalizeSpec(this.spec, this.onWarning, this.enumNaming);
1538
1638
  return this.normalized;
1539
1639
  }
1540
1640
  /** Definition map regardless of version: 2.0 `definitions` or 3.x `components.schemas`. */
@@ -2385,96 +2485,55 @@ var EnumBuilder = class {
2385
2485
  __name(this, "EnumBuilder");
2386
2486
  }
2387
2487
  config;
2388
- onWarning;
2389
- constructor(config, onWarning) {
2488
+ constructor(config) {
2390
2489
  this.config = config;
2391
- this.onWarning = onWarning;
2392
2490
  }
2393
2491
  build(name, definition) {
2394
- if (!definition.enum?.length) return [];
2492
+ const values = definition.enum;
2493
+ if (!values?.length) return [];
2494
+ const names = definition.enumMemberNames ?? values.map((value) => toEnumKey(value));
2395
2495
  const docs = this.config.options.generateEnumBasedOnDescription ? void 0 : emitDocs(definition.description);
2396
- if (this.config.options.enumStyle === "enum") {
2397
- return this.buildEnumAsEnum(name, definition, docs);
2398
- } else {
2399
- return this.buildEnumAsUnion(name, definition, docs);
2400
- }
2496
+ return this.config.options.enumStyle === "enum" ? this.buildEnumAsEnum(name, values, names, docs) : this.buildEnumAsUnion(name, values, names, docs);
2401
2497
  }
2402
- buildEnumAsEnum(name, definition, docs) {
2403
- if (!definition.enum?.length) throw Error("Enum definition has no values");
2404
- const statements = [];
2405
- const isStringEnum = definition.enum.some((value) => typeof value === "string");
2406
- if (isStringEnum) {
2407
- const members = definition.enum.map((value) => ({
2408
- name: toEnumKey(value),
2409
- value: `${String(value)}`
2410
- }));
2411
- statements.push({
2498
+ buildEnumAsEnum(name, values, names, docs) {
2499
+ const isStringEnum = values.some((value) => typeof value === "string");
2500
+ const members = values.map((value, index) => ({
2501
+ name: names[index],
2502
+ value: isStringEnum ? String(value) : value
2503
+ }));
2504
+ return [
2505
+ {
2412
2506
  kind: import_ts_morph3.StructureKind.Enum,
2413
2507
  name,
2414
2508
  isExported: true,
2415
2509
  docs,
2416
2510
  members
2417
- });
2418
- } else {
2419
- const members = this.buildEnumMembers(name, definition);
2420
- statements.push({
2421
- kind: import_ts_morph3.StructureKind.Enum,
2511
+ }
2512
+ ];
2513
+ }
2514
+ buildEnumAsUnion(name, values, names, docs) {
2515
+ const literals = values.map((value) => typeof value === "string" ? `'${escapeString(value)}'` : isNaN(value) ? `'${value}'` : `${value}`);
2516
+ const objectProperties = literals.map((literal, index) => `${names[index]}: ${literal} as ${name}`);
2517
+ return [
2518
+ {
2519
+ kind: import_ts_morph3.StructureKind.TypeAlias,
2422
2520
  name,
2521
+ type: literals.join(" | "),
2423
2522
  isExported: true,
2424
- docs,
2425
- members
2426
- });
2427
- }
2428
- return statements;
2429
- }
2430
- buildEnumAsUnion(name, definition, docs) {
2431
- if (!definition.enum?.length) throw Error("Enum definition has no values");
2432
- const statements = [];
2433
- const objectProperties = [];
2434
- const unionType = definition.enum.map((value) => {
2435
- const key = toEnumKey(value);
2436
- const val = typeof value === "string" ? `'${escapeString(value)}'` : isNaN(value) ? `'${value}'` : `${value}`;
2437
- objectProperties.push(`${key}: ${val} as ${name}`);
2438
- return val;
2439
- }).join(" | ");
2440
- statements.push({
2441
- kind: import_ts_morph3.StructureKind.TypeAlias,
2442
- name,
2443
- type: unionType,
2444
- isExported: true,
2445
- docs
2446
- });
2447
- statements.push({
2448
- kind: import_ts_morph3.StructureKind.VariableStatement,
2449
- declarationKind: import_ts_morph3.VariableDeclarationKind.Const,
2450
- isExported: true,
2451
- declarations: [
2452
- {
2453
- name,
2454
- initializer: `{ ${objectProperties.join(",\n")} }`
2455
- }
2456
- ]
2457
- });
2458
- return statements;
2459
- }
2460
- buildEnumMembers(name, definition) {
2461
- if (definition.description && this.config.options.generateEnumBasedOnDescription) {
2462
- try {
2463
- const enumValueObjects = JSON.parse(definition.description);
2464
- return enumValueObjects.map((obj) => ({
2465
- name: obj.Name,
2466
- value: obj.Value
2467
- }));
2468
- } catch {
2469
- if (/^\s*[[{]/.test(definition.description)) {
2470
- this.onWarning?.(`Enum "${name}": description looks like JSON (generateEnumBasedOnDescription) but could not be used \u2014 falling back to raw enum values`);
2471
- }
2523
+ docs
2524
+ },
2525
+ {
2526
+ kind: import_ts_morph3.StructureKind.VariableStatement,
2527
+ declarationKind: import_ts_morph3.VariableDeclarationKind.Const,
2528
+ isExported: true,
2529
+ declarations: [
2530
+ {
2531
+ name,
2532
+ initializer: `{ ${objectProperties.join(",\n")} }`
2533
+ }
2534
+ ]
2472
2535
  }
2473
- }
2474
- return definition.enum?.map((value) => ({
2475
- name: toEnumKey(value),
2476
- value
2477
- }));
2536
+ ];
2478
2537
  }
2479
2538
  };
2480
2539
 
@@ -2678,7 +2737,7 @@ var TypeGenerator = class {
2678
2737
  overwrite: true
2679
2738
  });
2680
2739
  this.resolver = new TypeResolver(config, onWarning);
2681
- this.enumBuilder = new EnumBuilder(config, onWarning);
2740
+ this.enumBuilder = new EnumBuilder(config);
2682
2741
  this.interfaceBuilder = new InterfaceBuilder(this.resolver);
2683
2742
  }
2684
2743
  async generate() {
@@ -4979,6 +5038,7 @@ var NAMING_KEYS = [
4979
5038
  ];
4980
5039
  var NAME_PREFIX_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
4981
5040
  var NAME_SUFFIX_PATTERN = /^[A-Za-z0-9_]*$/;
5041
+ var VENDOR_EXTENSION_PATTERN = /^x-./;
4982
5042
  function validateGeneratorConfig(config) {
4983
5043
  if (!config || typeof config !== "object") {
4984
5044
  throw new ConfigValidationError([
@@ -5026,6 +5086,9 @@ function validateGeneratorConfig(config) {
5026
5086
  issues.push(`\`options.${key}\` must be a boolean`);
5027
5087
  }
5028
5088
  }
5089
+ if (options.enumNameExtensions !== void 0 && !(Array.isArray(options.enumNameExtensions) && options.enumNameExtensions.every((name) => typeof name === "string" && VENDOR_EXTENSION_PATTERN.test(name)))) {
5090
+ issues.push(`\`options.enumNameExtensions\` must be an array of vendor extension names like ["x-enum-varnames", "x-enumNames"], got ${JSON.stringify(options.enumNameExtensions)}`);
5091
+ }
5029
5092
  if (options.customizeMethodName !== void 0 && typeof options.customizeMethodName !== "function") {
5030
5093
  issues.push("`options.customizeMethodName` must be a function (operationId) => string");
5031
5094
  }
package/index.d.ts CHANGED
@@ -89,6 +89,12 @@ interface SwaggerDefinition {
89
89
  maxProperties?: number | undefined;
90
90
  minProperties?: number | undefined;
91
91
  enum?: Array<string | number> | undefined;
92
+ /**
93
+ * One identifier per `enum` value, set by `normalizeSpec` on named enum
94
+ * schemas when `enumNameExtensions` or `generateEnumBasedOnDescription`
95
+ * yields usable names. Normalizer-owned: never read from the spec.
96
+ */
97
+ enumMemberNames?: string[] | undefined;
92
98
  /** OpenAPI 3.1 (JSON Schema); normalizeSchema folds it into a single-value `enum`. */
93
99
  const?: unknown;
94
100
  items?: SwaggerDefinition | SwaggerDefinition[] | undefined;
@@ -150,11 +156,12 @@ interface SwaggerSpec {
150
156
  /**
151
157
  * Shape of a JSON-encoded enum description consumed when
152
158
  * `generateEnumBasedOnDescription` is enabled: the description holds
153
- * `[{"Name":"First","Value":1}, …]` and supplies the member names.
159
+ * `[{"Name":"First","Value":1}, …]` and names the `enum` member whose value
160
+ * equals `Value`.
154
161
  */
155
162
  type EnumValueObject = {
156
163
  Name: string;
157
- Value: number;
164
+ Value: string | number;
158
165
  };
159
166
 
160
167
  type ResponseKind = "json" | "blob" | "arraybuffer" | "text";
@@ -354,6 +361,13 @@ interface GeneratorConfig {
354
361
  generateServices?: boolean;
355
362
  /** Read enum member names from JSON-encoded descriptions (see EnumValueObject). */
356
363
  generateEnumBasedOnDescription?: boolean;
364
+ /**
365
+ * Vendor extensions holding enum member names, checked in order — e.g.
366
+ * `["x-enum-varnames", "x-enumNames"]`. The first one that is a string
367
+ * array as long as the schema's `enum` names its members; it wins over
368
+ * `generateEnumBasedOnDescription`. Default: none.
369
+ */
370
+ enumNameExtensions?: string[];
357
371
  /** Default headers added to every request when not already present. */
358
372
  customHeaders?: Record<string, string>;
359
373
  /**
@@ -414,6 +428,13 @@ interface TypeMappingConfig {
414
428
  };
415
429
  };
416
430
  }
431
+ /** Options consumed by spec normalization: where enum member names come from. */
432
+ interface EnumNamingOptions {
433
+ options: {
434
+ enumNameExtensions?: string[];
435
+ generateEnumBasedOnDescription?: boolean;
436
+ };
437
+ }
417
438
  /** Options consumed by model/interface generation (TypeGenerator). */
418
439
  interface TypeGenOptions {
419
440
  options: {
@@ -517,6 +538,7 @@ declare class SwaggerParser {
517
538
  private normalized?;
518
539
  /** Non-fatal problems found while normalizing — a parameter with no usable name, for one. */
519
540
  private readonly onWarning?;
541
+ private readonly enumNaming;
520
542
  private constructor();
521
543
  /**
522
544
  * Loads, parses and wraps a spec.
@@ -561,7 +583,7 @@ declare class SwaggerParser {
561
583
  * http-resource body, overloads) — computing it once keeps the derivations
562
584
  * identical by construction.
563
585
  */
564
- declare function normalizeSpec(spec: SwaggerSpec, onWarning?: (message: string) => void): NormalizedSpec;
586
+ declare function normalizeSpec(spec: SwaggerSpec, onWarning?: (message: string) => void, enumNaming?: EnumNamingOptions): NormalizedSpec;
565
587
  /**
566
588
  * Normalizes the JSON-Schema constructs OpenAPI 3.1 introduced so generators
567
589
  * never see them:
@@ -1378,4 +1400,4 @@ declare function validateGeneratorConfig(config: unknown): asserts config is Gen
1378
1400
  */
1379
1401
  declare function loadConfigFile(configPath: string): Promise<GeneratorConfig>;
1380
1402
 
1381
- export { type ArgumentNameProfile, type ArgumentNames, BASE_INTERCEPTOR_HEADER_COMMENT, CONTENT_TYPES, type ComponentResolution, type ComponentResolvers, ConfigLoadError, ConfigValidationError, DuplicateGeneratedNameError, type EnumValueObject, type GenerationPhase, type GenerationResult, type GeneratorConfig, type GetMethodGenerationContext, HTTP_RESOURCE_GENERATOR_HEADER_COMMENT, type HeadersEmitOptions, type IPluginGenerator, type IPluginGeneratorClass, InvalidIdentifierError, MAIN_INDEX_GENERATOR_HEADER_COMMENT, type MethodGenOptions, type MethodGenerationContext, type NameDecoration, type NamingOptions, NgOpenApiError, type NgOpenapiClientConfig, type NormalizedOperation, type NormalizedSpec, type OpenApiSecurityScheme, type OperationRef, OutputConflictError, PROVIDER_GENERATOR_HEADER_COMMENT, type PackageConfig, type PackageGenOptions, type Parameter, type PathInfo, type PluginGeneratorContext, REQUEST_PARAMS_GENERATOR_HEADER_COMMENT, RESERVED_MEMBER_NAMES, RESOURCE_ARGUMENT_PROFILE, type RenamedArgument, type Reporter, type RequestBody, type ResolveComponent, type ResponseKind, type ResponseTypeInfo, SERVICE_ARGUMENT_PROFILE, SERVICE_GENERATOR_HEADER_COMMENT, SERVICE_INDEX_GENERATOR_HEADER_COMMENT, type ServiceDecoratorEmit, type ServiceDecoratorEmitOptions, type SpecInfo, SpecLoadError, SpecParseError, type SpecVersion, type SwaggerDefinition, SwaggerParser, type SwaggerResponse, type SwaggerSpec, TYPE_GENERATOR_HEADER_COMMENT, type TypeGenOptions, type TypeMappingConfig, type TypeSchema, UnresolvedPathTemplateError, ZOD_PLUGIN_GENERATOR_HEADER_COMMENT, ZOD_PLUGIN_INDEX_GENERATOR_HEADER_COMMENT, assertDistinctMemberNames, camelCase, capitalizeFirst, clientNameIdentifier, createComponentResolvers, defineConfig, describeOperation, effectiveClientName, emitDefaultHeadersMerge, emitDocs, emitHeaders, emitJsonFile, emitObjectKey, emitPropertyName, emitQueryParams, emitResponseTypeOption, emitServiceDecorator, emitSignalAwareQueryParams, emitTextFile, emitUrlConstruction, emitUrlExpression, escapeDoubleQuoted, escapeJsDoc, escapeSingleQuoted, escapeSingleQuoted as escapeString, escapeTemplateLiteral, extractPaths, generateFromConfig, generateParseRequestTypeParams, getBasePathTokenName, getClientContextTokenName, getInterceptorsTokenName, getModelTypeName, getOperationMethodName, getRequestBodyType, getResourceClassName, getResponseInfoFromResponse, getResponseType, getResponseTypeFromResponse, getServiceClassName, getTypeScriptType, groupOperationsByController, hasDuplicateFunctionNames, inferResponseTypeFromContentType, isDataTypeInterface, isPlainObject, isPrimitiveType, isSemver, isUrl, isValidIdentifier, joinRequestOptionEntries, kebabCase, listGeneratedBarrelDirs, listGeneratedFileNames, listImportedPackageNames, loadConfigFile, normalizeSchema, normalizeSpec, nullableType, pascalCase, pascalCaseForEnums, plainParamValue, quoteLiteral, reservedMemberCollision, resolveArgumentNames, screamingSnakeCase, signalAwareParamValue, validateGeneratorConfig, validateInput };
1403
+ export { type ArgumentNameProfile, type ArgumentNames, BASE_INTERCEPTOR_HEADER_COMMENT, CONTENT_TYPES, type ComponentResolution, type ComponentResolvers, ConfigLoadError, ConfigValidationError, DuplicateGeneratedNameError, type EnumNamingOptions, type EnumValueObject, type GenerationPhase, type GenerationResult, type GeneratorConfig, type GetMethodGenerationContext, HTTP_RESOURCE_GENERATOR_HEADER_COMMENT, type HeadersEmitOptions, type IPluginGenerator, type IPluginGeneratorClass, InvalidIdentifierError, MAIN_INDEX_GENERATOR_HEADER_COMMENT, type MethodGenOptions, type MethodGenerationContext, type NameDecoration, type NamingOptions, NgOpenApiError, type NgOpenapiClientConfig, type NormalizedOperation, type NormalizedSpec, type OpenApiSecurityScheme, type OperationRef, OutputConflictError, PROVIDER_GENERATOR_HEADER_COMMENT, type PackageConfig, type PackageGenOptions, type Parameter, type PathInfo, type PluginGeneratorContext, REQUEST_PARAMS_GENERATOR_HEADER_COMMENT, RESERVED_MEMBER_NAMES, RESOURCE_ARGUMENT_PROFILE, type RenamedArgument, type Reporter, type RequestBody, type ResolveComponent, type ResponseKind, type ResponseTypeInfo, SERVICE_ARGUMENT_PROFILE, SERVICE_GENERATOR_HEADER_COMMENT, SERVICE_INDEX_GENERATOR_HEADER_COMMENT, type ServiceDecoratorEmit, type ServiceDecoratorEmitOptions, type SpecInfo, SpecLoadError, SpecParseError, type SpecVersion, type SwaggerDefinition, SwaggerParser, type SwaggerResponse, type SwaggerSpec, TYPE_GENERATOR_HEADER_COMMENT, type TypeGenOptions, type TypeMappingConfig, type TypeSchema, UnresolvedPathTemplateError, ZOD_PLUGIN_GENERATOR_HEADER_COMMENT, ZOD_PLUGIN_INDEX_GENERATOR_HEADER_COMMENT, assertDistinctMemberNames, camelCase, capitalizeFirst, clientNameIdentifier, createComponentResolvers, defineConfig, describeOperation, effectiveClientName, emitDefaultHeadersMerge, emitDocs, emitHeaders, emitJsonFile, emitObjectKey, emitPropertyName, emitQueryParams, emitResponseTypeOption, emitServiceDecorator, emitSignalAwareQueryParams, emitTextFile, emitUrlConstruction, emitUrlExpression, escapeDoubleQuoted, escapeJsDoc, escapeSingleQuoted, escapeSingleQuoted as escapeString, escapeTemplateLiteral, extractPaths, generateFromConfig, generateParseRequestTypeParams, getBasePathTokenName, getClientContextTokenName, getInterceptorsTokenName, getModelTypeName, getOperationMethodName, getRequestBodyType, getResourceClassName, getResponseInfoFromResponse, getResponseType, getResponseTypeFromResponse, getServiceClassName, getTypeScriptType, groupOperationsByController, hasDuplicateFunctionNames, inferResponseTypeFromContentType, isDataTypeInterface, isPlainObject, isPrimitiveType, isSemver, isUrl, isValidIdentifier, joinRequestOptionEntries, kebabCase, listGeneratedBarrelDirs, listGeneratedFileNames, listImportedPackageNames, loadConfigFile, normalizeSchema, normalizeSpec, nullableType, pascalCase, pascalCaseForEnums, plainParamValue, quoteLiteral, reservedMemberCollision, resolveArgumentNames, screamingSnakeCase, signalAwareParamValue, validateGeneratorConfig, validateInput };
package/index.js CHANGED
@@ -1460,13 +1460,102 @@ function getResponseType(response, config) {
1460
1460
  }
1461
1461
  __name(getResponseType, "getResponseType");
1462
1462
 
1463
+ // ../shared/src/core/enum-member-names.ts
1464
+ function resolveEnumMemberNames(schemaName, definition, config, onWarning) {
1465
+ const values = definition.enum;
1466
+ if (!Array.isArray(values) || values.length === 0) {
1467
+ return void 0;
1468
+ }
1469
+ const { enumNameExtensions = [], generateEnumBasedOnDescription } = config.options;
1470
+ const warn = /* @__PURE__ */ __name((message) => onWarning == null ? void 0 : onWarning(`Enum "${schemaName}": ${message}`), "warn");
1471
+ for (const extension of enumNameExtensions) {
1472
+ const names = namesFromExtension(definition, extension, values.length, warn);
1473
+ if (names) {
1474
+ return names;
1475
+ }
1476
+ }
1477
+ return generateEnumBasedOnDescription ? namesFromDescription(definition.description, values, warn) : void 0;
1478
+ }
1479
+ __name(resolveEnumMemberNames, "resolveEnumMemberNames");
1480
+ function namesFromExtension(definition, extension, valueCount, warn) {
1481
+ if (!Object.prototype.hasOwnProperty.call(definition, extension)) {
1482
+ return void 0;
1483
+ }
1484
+ const candidates = definition[extension];
1485
+ if (!Array.isArray(candidates) || candidates.length !== valueCount || !candidates.every((candidate) => typeof candidate === "string")) {
1486
+ warn(`\`${extension}\` must be an array of ${valueCount} strings, one per enum value \u2014 ignoring it`);
1487
+ return void 0;
1488
+ }
1489
+ return toMemberNames(`\`${extension}\``, candidates, warn);
1490
+ }
1491
+ __name(namesFromExtension, "namesFromExtension");
1492
+ function namesFromDescription(description, values, warn) {
1493
+ if (typeof description !== "string") {
1494
+ return void 0;
1495
+ }
1496
+ const reject = /* @__PURE__ */ __name((reason) => {
1497
+ if (/^\s*[[{]/.test(description)) {
1498
+ warn(`description looks like JSON (generateEnumBasedOnDescription) but could not be used: ${reason} \u2014 falling back to raw enum values`);
1499
+ }
1500
+ return void 0;
1501
+ }, "reject");
1502
+ let parsed;
1503
+ try {
1504
+ parsed = JSON.parse(description);
1505
+ } catch (e) {
1506
+ return reject("it does not parse");
1507
+ }
1508
+ if (!Array.isArray(parsed) || !parsed.every(isEnumValueObject)) {
1509
+ return reject('expected an array of { "Name": string, "Value": string | number } objects');
1510
+ }
1511
+ const nameByValue = /* @__PURE__ */ new Map();
1512
+ for (const { Name, Value } of parsed) {
1513
+ if (!nameByValue.has(Value)) {
1514
+ nameByValue.set(Value, Name);
1515
+ }
1516
+ }
1517
+ const candidates = [];
1518
+ for (const value of values) {
1519
+ const name = nameByValue.get(value);
1520
+ if (name === void 0) {
1521
+ return reject(`no Name for enum value ${JSON.stringify(value)}`);
1522
+ }
1523
+ candidates.push(name);
1524
+ }
1525
+ return toMemberNames("the description", candidates, warn);
1526
+ }
1527
+ __name(namesFromDescription, "namesFromDescription");
1528
+ function isEnumValueObject(candidate) {
1529
+ return isPlainObject(candidate) && typeof candidate["Name"] === "string" && (typeof candidate["Value"] === "string" || typeof candidate["Value"] === "number");
1530
+ }
1531
+ __name(isEnumValueObject, "isEnumValueObject");
1532
+ function toMemberNames(source, candidates, warn) {
1533
+ const names = candidates.map(toMemberName);
1534
+ const seen = /* @__PURE__ */ new Set();
1535
+ for (const name of names) {
1536
+ if (seen.has(name)) {
1537
+ warn(`names from ${source} are not unique ("${name}" occurs more than once) \u2014 falling back to raw enum values`);
1538
+ return void 0;
1539
+ }
1540
+ seen.add(name);
1541
+ }
1542
+ return names;
1543
+ }
1544
+ __name(toMemberNames, "toMemberNames");
1545
+ function toMemberName(name) {
1546
+ return isValidIdentifier(name) && name !== "__proto__" ? name : pascalCaseForEnums(name);
1547
+ }
1548
+ __name(toMemberName, "toMemberName");
1549
+
1463
1550
  // ../shared/src/core/normalize.ts
1464
- function normalizeSpec(spec, onWarning) {
1551
+ function normalizeSpec(spec, onWarning, enumNaming = {
1552
+ options: {}
1553
+ }) {
1465
1554
  var _a;
1466
1555
  const rawDefinitions = spec.definitions || ((_a = spec.components) == null ? void 0 : _a.schemas) || {};
1467
1556
  const definitions = Object.fromEntries(Object.entries(rawDefinitions).map(([name, definition]) => [
1468
1557
  name,
1469
- normalizeSchema(definition)
1558
+ nameEnumMembers(name, normalizeSchema(definition), enumNaming, onWarning)
1470
1559
  ]));
1471
1560
  const resolveReference = /* @__PURE__ */ __name((ref) => {
1472
1561
  const parts = ref.split("/");
@@ -1492,6 +1581,15 @@ function normalizeSpec(spec, onWarning) {
1492
1581
  };
1493
1582
  }
1494
1583
  __name(normalizeSpec, "normalizeSpec");
1584
+ function nameEnumMembers(name, definition, enumNaming, onWarning) {
1585
+ delete definition.enumMemberNames;
1586
+ const names = resolveEnumMemberNames(name, definition, enumNaming, onWarning);
1587
+ if (names) {
1588
+ definition.enumMemberNames = names;
1589
+ }
1590
+ return definition;
1591
+ }
1592
+ __name(nameEnumMembers, "nameEnumMembers");
1495
1593
  function infoText(value) {
1496
1594
  if (typeof value === "string") {
1497
1595
  return value;
@@ -1654,13 +1752,15 @@ __name(warnAboutUnboundParameters, "warnAboutUnboundParameters");
1654
1752
 
1655
1753
  // ../shared/src/core/swagger-parser.ts
1656
1754
  var _SwaggerParser = class _SwaggerParser {
1657
- constructor(spec, onWarning) {
1755
+ constructor(spec, onWarning, enumNaming) {
1658
1756
  __publicField(this, "spec");
1659
1757
  __publicField(this, "normalized");
1660
1758
  /** Non-fatal problems found while normalizing — a parameter with no usable name, for one. */
1661
1759
  __publicField(this, "onWarning");
1760
+ __publicField(this, "enumNaming");
1662
1761
  this.spec = spec;
1663
1762
  this.onWarning = onWarning;
1763
+ this.enumNaming = enumNaming;
1664
1764
  }
1665
1765
  /**
1666
1766
  * Loads, parses and wraps a spec.
@@ -1688,7 +1788,7 @@ var _SwaggerParser = class _SwaggerParser {
1688
1788
  } catch (error) {
1689
1789
  throw new SpecParseError(`Failed to inline nested $refs in the spec: ${error instanceof Error ? error.message : String(error)}`, swaggerPathOrUrl, error);
1690
1790
  }
1691
- return new _SwaggerParser(inlinedSpec, onWarning);
1791
+ return new _SwaggerParser(inlinedSpec, onWarning, config);
1692
1792
  });
1693
1793
  }
1694
1794
  /**
@@ -1698,7 +1798,7 @@ var _SwaggerParser = class _SwaggerParser {
1698
1798
  */
1699
1799
  getNormalizedSpec() {
1700
1800
  var _a;
1701
- (_a = this.normalized) != null ? _a : this.normalized = normalizeSpec(this.spec, this.onWarning);
1801
+ (_a = this.normalized) != null ? _a : this.normalized = normalizeSpec(this.spec, this.onWarning, this.enumNaming);
1702
1802
  return this.normalized;
1703
1803
  }
1704
1804
  /** Definition map regardless of version: 2.0 `definitions` or 3.x `components.schemas`. */
@@ -2614,101 +2714,57 @@ function toEnumKey(value) {
2614
2714
  }
2615
2715
  __name(toEnumKey, "toEnumKey");
2616
2716
  var _EnumBuilder = class _EnumBuilder {
2617
- constructor(config, onWarning) {
2717
+ constructor(config) {
2618
2718
  __publicField(this, "config");
2619
- __publicField(this, "onWarning");
2620
2719
  this.config = config;
2621
- this.onWarning = onWarning;
2622
2720
  }
2623
2721
  build(name, definition) {
2624
2722
  var _a;
2625
- if (!((_a = definition.enum) == null ? void 0 : _a.length)) return [];
2723
+ const values = definition.enum;
2724
+ if (!(values == null ? void 0 : values.length)) return [];
2725
+ const names = (_a = definition.enumMemberNames) != null ? _a : values.map((value) => toEnumKey(value));
2626
2726
  const docs = this.config.options.generateEnumBasedOnDescription ? void 0 : emitDocs(definition.description);
2627
- if (this.config.options.enumStyle === "enum") {
2628
- return this.buildEnumAsEnum(name, definition, docs);
2629
- } else {
2630
- return this.buildEnumAsUnion(name, definition, docs);
2631
- }
2727
+ return this.config.options.enumStyle === "enum" ? this.buildEnumAsEnum(name, values, names, docs) : this.buildEnumAsUnion(name, values, names, docs);
2632
2728
  }
2633
- buildEnumAsEnum(name, definition, docs) {
2634
- var _a;
2635
- if (!((_a = definition.enum) == null ? void 0 : _a.length)) throw Error("Enum definition has no values");
2636
- const statements = [];
2637
- const isStringEnum = definition.enum.some((value) => typeof value === "string");
2638
- if (isStringEnum) {
2639
- const members = definition.enum.map((value) => ({
2640
- name: toEnumKey(value),
2641
- value: `${String(value)}`
2642
- }));
2643
- statements.push({
2729
+ buildEnumAsEnum(name, values, names, docs) {
2730
+ const isStringEnum = values.some((value) => typeof value === "string");
2731
+ const members = values.map((value, index) => ({
2732
+ name: names[index],
2733
+ value: isStringEnum ? String(value) : value
2734
+ }));
2735
+ return [
2736
+ {
2644
2737
  kind: import_ts_morph3.StructureKind.Enum,
2645
2738
  name,
2646
2739
  isExported: true,
2647
2740
  docs,
2648
2741
  members
2649
- });
2650
- } else {
2651
- const members = this.buildEnumMembers(name, definition);
2652
- statements.push({
2653
- kind: import_ts_morph3.StructureKind.Enum,
2742
+ }
2743
+ ];
2744
+ }
2745
+ buildEnumAsUnion(name, values, names, docs) {
2746
+ const literals = values.map((value) => typeof value === "string" ? `'${escapeString(value)}'` : isNaN(value) ? `'${value}'` : `${value}`);
2747
+ const objectProperties = literals.map((literal, index) => `${names[index]}: ${literal} as ${name}`);
2748
+ return [
2749
+ {
2750
+ kind: import_ts_morph3.StructureKind.TypeAlias,
2654
2751
  name,
2752
+ type: literals.join(" | "),
2655
2753
  isExported: true,
2656
- docs,
2657
- members
2658
- });
2659
- }
2660
- return statements;
2661
- }
2662
- buildEnumAsUnion(name, definition, docs) {
2663
- var _a;
2664
- if (!((_a = definition.enum) == null ? void 0 : _a.length)) throw Error("Enum definition has no values");
2665
- const statements = [];
2666
- const objectProperties = [];
2667
- const unionType = definition.enum.map((value) => {
2668
- const key = toEnumKey(value);
2669
- const val = typeof value === "string" ? `'${escapeString(value)}'` : isNaN(value) ? `'${value}'` : `${value}`;
2670
- objectProperties.push(`${key}: ${val} as ${name}`);
2671
- return val;
2672
- }).join(" | ");
2673
- statements.push({
2674
- kind: import_ts_morph3.StructureKind.TypeAlias,
2675
- name,
2676
- type: unionType,
2677
- isExported: true,
2678
- docs
2679
- });
2680
- statements.push({
2681
- kind: import_ts_morph3.StructureKind.VariableStatement,
2682
- declarationKind: import_ts_morph3.VariableDeclarationKind.Const,
2683
- isExported: true,
2684
- declarations: [
2685
- {
2686
- name,
2687
- initializer: `{ ${objectProperties.join(",\n")} }`
2688
- }
2689
- ]
2690
- });
2691
- return statements;
2692
- }
2693
- buildEnumMembers(name, definition) {
2694
- var _a, _b;
2695
- if (definition.description && this.config.options.generateEnumBasedOnDescription) {
2696
- try {
2697
- const enumValueObjects = JSON.parse(definition.description);
2698
- return enumValueObjects.map((obj) => ({
2699
- name: obj.Name,
2700
- value: obj.Value
2701
- }));
2702
- } catch (e) {
2703
- if (/^\s*[[{]/.test(definition.description)) {
2704
- (_a = this.onWarning) == null ? void 0 : _a.call(this, `Enum "${name}": description looks like JSON (generateEnumBasedOnDescription) but could not be used \u2014 falling back to raw enum values`);
2705
- }
2754
+ docs
2755
+ },
2756
+ {
2757
+ kind: import_ts_morph3.StructureKind.VariableStatement,
2758
+ declarationKind: import_ts_morph3.VariableDeclarationKind.Const,
2759
+ isExported: true,
2760
+ declarations: [
2761
+ {
2762
+ name,
2763
+ initializer: `{ ${objectProperties.join(",\n")} }`
2764
+ }
2765
+ ]
2706
2766
  }
2707
- }
2708
- return (_b = definition.enum) == null ? void 0 : _b.map((value) => ({
2709
- name: toEnumKey(value),
2710
- value
2711
- }));
2767
+ ];
2712
2768
  }
2713
2769
  };
2714
2770
  __name(_EnumBuilder, "EnumBuilder");
@@ -2912,7 +2968,7 @@ var _TypeGenerator = class _TypeGenerator {
2912
2968
  overwrite: true
2913
2969
  });
2914
2970
  this.resolver = new TypeResolver(config, onWarning);
2915
- this.enumBuilder = new EnumBuilder(config, onWarning);
2971
+ this.enumBuilder = new EnumBuilder(config);
2916
2972
  this.interfaceBuilder = new InterfaceBuilder(this.resolver);
2917
2973
  }
2918
2974
  generate() {
@@ -5221,6 +5277,7 @@ var NAMING_KEYS = [
5221
5277
  ];
5222
5278
  var NAME_PREFIX_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
5223
5279
  var NAME_SUFFIX_PATTERN = /^[A-Za-z0-9_]*$/;
5280
+ var VENDOR_EXTENSION_PATTERN = /^x-./;
5224
5281
  function validateGeneratorConfig(config) {
5225
5282
  if (!config || typeof config !== "object") {
5226
5283
  throw new ConfigValidationError([
@@ -5268,6 +5325,9 @@ function validateGeneratorConfig(config) {
5268
5325
  issues.push(`\`options.${key}\` must be a boolean`);
5269
5326
  }
5270
5327
  }
5328
+ if (options.enumNameExtensions !== void 0 && !(Array.isArray(options.enumNameExtensions) && options.enumNameExtensions.every((name) => typeof name === "string" && VENDOR_EXTENSION_PATTERN.test(name)))) {
5329
+ issues.push(`\`options.enumNameExtensions\` must be an array of vendor extension names like ["x-enum-varnames", "x-enumNames"], got ${JSON.stringify(options.enumNameExtensions)}`);
5330
+ }
5271
5331
  if (options.customizeMethodName !== void 0 && typeof options.customizeMethodName !== "function") {
5272
5332
  issues.push("`options.customizeMethodName` must be a function (operationId) => string");
5273
5333
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ng-openapi",
3
- "version": "0.5.0",
3
+ "version": "0.5.1-pr-137-feat-enum-name-extensions-941f4c5.0",
4
4
  "description": "Generate Angular services and TypeScript types from OpenAPI/Swagger specifications",
5
5
  "keywords": [
6
6
  "ng-openapi",