Feature: Normalize TypeScript Enum Key Names
Introduction
The @openapi-codegen/typescript library currently generates enum keys directly from the string values of the enums. This behavior causes issues when the enum values include characters that are not allowed in TypeScript identifiers, such as spaces or hyphens.
Problem
When the enum values contain characters like -, , or any character not allowed in a TypeScript identifier, the generated enum keys are invalid and cause syntax errors.
Solution
This update introduces a .replace(/[^a-z0-9_]/gi, "_") transformation in the enum key generation logic. This sanitization ensures that all generated enum keys are valid TypeScript identifiers, replacing any disallowed characters with an underscore (_).
Changes
- Extended the enum key generation logic to include the
.replace(/[^a-z0-9_]/gi, "_")transformation for string enums. - Extended tests to ensure that the generated enum keys are valid TypeScript identifiers and that they correspond correctly to their associated values.
Impact
These changes will allow the @openapi-codegen/typescript library to handle a broader set of enum values without failing and will prevent issues with TypeScript compilation for users of the library. However, it's important to note that in scenarios where enum values only differ by characters that are sanitized into underscores (e.g., A/B and A:B both becoming A_B), this can lead to identifier collisions. Despite this, such collisions should be a rare edge case and, importantly, the previous behavior where these values resulted in invalid TypeScript identifiers meant that the generation process would fail in any case. This change ensures that generation succeeds and produces a valid TypeScript code, albeit with potential naming conflicts that can be addressed in subsequent iterations or through manual intervention in the spec if they arise.
How to Test
- Run the updated codegen against an OpenAPI spec with enums that contain disallowed characters.
- Ensure that the generated code compiles without errors in TypeScript.
- Verify that the enum values are correctly matched to the transformed enum keys in the generated code.
@fabien0102 , Please review the changes and provide feedback.