Skip to content

Commit 94592a4

Browse files
authored
fix: replace special characters using SPECIAL_CHARACTER_MAP for dup… (#1877)
* fix: replace special characters using `SPECIAL_CHARACTER_MAP` for duplicate-identifiers * chore: optimized code * Create slimy-points-learn.md
1 parent 9c93cfd commit 94592a4

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

.changeset/slimy-points-learn.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"openapi-typescript": patch
3+
---
4+
5+
fix: replace special characters using `SPECIAL_CHARACTER_MAP` for duplicate-identifiers

packages/openapi-typescript/src/lib/ts.ts

+7-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ import ts, { type LiteralTypeNode, type TypeLiteralNode } from "typescript";
44
export const JS_PROPERTY_INDEX_RE = /^[A-Za-z_$][A-Za-z_$0-9]*$/;
55
export const JS_ENUM_INVALID_CHARS_RE = /[^A-Za-z_$0-9]+(.)?/g;
66
export const JS_PROPERTY_INDEX_INVALID_CHARS_RE = /[^A-Za-z_$0-9]+/g;
7+
export const SPECIAL_CHARACTER_MAP: Record<string, string> = {
8+
"+": "Plus",
9+
// Add more mappings as needed
10+
};
711

812
export const BOOLEAN = ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword);
913
export const FALSE = ts.factory.createLiteralTypeNode(ts.factory.createFalse());
@@ -308,7 +312,9 @@ export function tsEnumMember(value: string | number, metadata: { name?: string;
308312
if (invalidCharMatch[0] === name) {
309313
name = `"${name}"`;
310314
} else {
311-
name = name.replace(JS_PROPERTY_INDEX_INVALID_CHARS_RE, "_");
315+
name = name.replace(JS_PROPERTY_INDEX_INVALID_CHARS_RE, (s) => {
316+
return s in SPECIAL_CHARACTER_MAP ? SPECIAL_CHARACTER_MAP[s] : "_";
317+
});
312318
}
313319
}
314320
}

packages/openapi-typescript/test/lib/ts.test.ts

+8
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,14 @@ describe("tsEnum", () => {
208208
NotFound = 101,
209209
// User doesn't have permissions
210210
PermissionDenied = 102
211+
}`);
212+
});
213+
214+
test("replace special character", () => {
215+
expect(astToString(tsEnum("FOO_ENUM", ["Etc/GMT+0", "Etc/GMT+1", "Etc/GMT-1"])).trim()).toBe(`enum FOO_ENUM {
216+
Etc_GMTPlus0 = "Etc/GMT+0",
217+
Etc_GMTPlus1 = "Etc/GMT+1",
218+
Etc_GMT_1 = "Etc/GMT-1"
211219
}`);
212220
});
213221
});

0 commit comments

Comments
 (0)