Skip to content

Commit

Permalink
fix: enum key safe
Browse files Browse the repository at this point in the history
  • Loading branch information
morlay committed Dec 17, 2024
1 parent 2ca318f commit c760a68
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
2 changes: 1 addition & 1 deletion nodepkg/typedef/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@innoai-tech/typedef",
"version": "0.3.7",
"version": "0.3.8",
"monobundle": {
"exports": {
".": "./src/index.ts"
Expand Down
32 changes: 20 additions & 12 deletions nodepkg/typedef/src/encoding/TypeScriptEncoder.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Schema, t, type Type } from "../core";
import { isNumber, isString } from "../core/util";
import { camelCase } from "@innoai-tech/lodash";

export class TypeScriptEncoder {
static encode(type: Type, all = true): string {
Expand Down Expand Up @@ -40,7 +41,7 @@ export ${t} ${name}${t === "enum" ? " " : " = "}${decl}`;

const decl = this._encode(
Schema.schemaProp(type, Schema.unwrap)(),
refName,
refName
);

if (decl) {
Expand Down Expand Up @@ -81,13 +82,20 @@ export ${t} ${name}${t === "enum" ? " " : " = "}${decl}`;
return false;
};

const toSafeID = (v: string) => {
if (/[-!~]/.test(v)) {
return camelCase(v);
}
return v;
};

this.def.set(declName, [
"enum",
`{
${Schema.schemaProp(type, "enum")
.map((v: any) => `${isPrefixDigit(v) ? `_${v}` : v} = ${JSON.stringify(v)}`)
.join(",\n")}
}`,
.map((v: any) => `${isPrefixDigit(v) ? `_${toSafeID(v)}` : toSafeID(v)} = ${JSON.stringify(v)}`)
.join(",\n")}
}`
]);

const enumLabels = rawType.meta["enumLabels"] as any[];
Expand All @@ -98,13 +106,13 @@ ${Schema.schemaProp(type, "enum")
`(v: ${declName}) => {
return ({
${Schema.schemaProp(type, "enum")
.map(
(v: any, i: number) =>
`${JSON.stringify(v)}: ${JSON.stringify(enumLabels[i])}`,
)
.join(",\n")}
.map(
(v: any, i: number) =>
`${JSON.stringify(v)}: ${JSON.stringify(enumLabels[i])}`
)
.join(",\n")}
})[v] ?? v
}`,
}`
]);
}

Expand All @@ -118,7 +126,7 @@ ${Schema.schemaProp(type, "enum")

case "record": {
const keyType = this._encode(
Schema.schemaProp(type, "propertyNames") ?? t.string(),
Schema.schemaProp(type, "propertyNames") ?? t.string()
);

if (keyType.startsWith("/* @type:enums */")) {
Expand All @@ -133,7 +141,7 @@ ${Schema.schemaProp(type, "enum")
`;

for (const [p, propType] of Object.entries(
(Schema.schemaProp(type, "properties") ?? {}) as Record<string, Type>,
(Schema.schemaProp(type, "properties") ?? {}) as Record<string, Type>
)) {
ts += ` ${JSON.stringify(p)}`;
if (Schema.schemaProp(propType, Schema.optional)) {
Expand Down

0 comments on commit c760a68

Please sign in to comment.