-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathts-ast.ts
61 lines (56 loc) · 2.06 KB
/
ts-ast.ts
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { toMetadataTypes } from "./cs-ast.js"
import { createTdAstFromAIAst, transformUserRefs } from "./ts-once.js"
import { ParseResult, TypeScriptParser } from "./ts-parser.js"
import { toTsd } from "./tsd-gen.js"
import { ProjectInfo } from "./types.js"
import { getGroupName } from "./utils.js"
// Extract TypeScript source code from a AI Response
export function extractTypeScriptSrc(msg:string) {
msg = msg.trim()
const startPos = msg.indexOf("```typescript")
if (startPos >= 0) {
const ts = msg.substring(msg.indexOf('\n', startPos) + 1)
const src = ts.substring(0, ts.indexOf("```"))
return src
}
if (msg.startsWith("//") || msg.startsWith("/*") || msg.startsWith("export ")
|| msg.startsWith("interface ") || msg.startsWith("class ") || msg.startsWith("type ")) {
return msg
}
}
// Parse TypeScript source code into AST
export function toAst(src:string) {
const parser = new TypeScriptParser();
return parser.parse(src)
}
// Transforms that are only applied once on AI TypeScript AST
export function createAstFromAITypeScript(ts:string) {
const parser = new TypeScriptParser()
const tdAst = parser.parse(ts)
return createTdAstFromAIAst(tdAst)
}
// Apply Project Info to the AST once after it's downloaded
export function astForProject(tsAst:ParseResult, info:ProjectInfo) {
transformUserRefs(tsAst, info)
return tsAst
}
// Convert User TypeScript into CS AST and Updated TSD
export function generateCsAstFromTsd(userTs:string, opt?:{references:string[]}) {
const userTsAst = toAst(userTs) // user modified tsd
if (opt?.references) {
userTsAst.references = userTsAst.references || []
opt.references
.filter(x => !userTsAst.references.some(y => y.path === x))
.forEach(path => userTsAst.references.push({ path }))
}
const tsd = toTsd(userTsAst)
const tsdAst = toAst(tsd)
const csAst = toMetadataTypes(tsdAst)
const result = {
tsdAst,
tsd,
csAst,
groupName: getGroupName(csAst)
}
return result
}