-
Notifications
You must be signed in to change notification settings - Fork 500
Expand file tree
/
Copy paththesys-c1-converter.ts
More file actions
47 lines (40 loc) · 1.12 KB
/
thesys-c1-converter.ts
File metadata and controls
47 lines (40 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
type JsonRecord = Record<string, unknown>;
function isRecord(value: unknown): value is JsonRecord {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function isElementNode(
value: unknown,
): value is { type: "element"; typeName: string; props?: unknown } {
return isRecord(value) && value["type"] === "element" && typeof value["typeName"] === "string";
}
function convertValue(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(convertValue);
}
if (isElementNode(value)) {
return {
component: value.typeName,
props: isRecord(value.props) ? (convertValue(value.props) as JsonRecord) : {},
};
}
if (isRecord(value)) {
const result: JsonRecord = {};
for (const [key, nestedValue] of Object.entries(value)) {
if (key === "__typename") continue;
result[key] = convertValue(nestedValue);
}
return result;
}
return value;
}
export function astToThesysC1Json(astRoot: unknown): string {
const component = convertValue(astRoot);
return JSON.stringify(
{
component,
error: null,
},
null,
2,
);
}