-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathts-parser.js
54 lines (50 loc) · 1.39 KB
/
ts-parser.js
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
import { loadMonacoEngine } from "./monaco-loader"
import {
createProgram,
createCompilerOptions,
createVirtualCompilerHost,
} from "./ts-create-program.mts"
let tsParserCache = null
export function loadTsParser() {
return (tsParserCache ??= loadTsParserImpl())
}
async function loadTsParserImpl() {
await loadMonacoEngine()
const [ts, tsvfs, tsParser] = await Promise.all([
import("typescript"),
import("@typescript/vfs"),
import("@typescript-eslint/parser"),
])
if (typeof window === "undefined") {
return tsParser
}
window.define("typescript", ts)
const compilerOptions = createCompilerOptions(ts)
const filePath = "/demo.ts"
const host = await createVirtualCompilerHost(
{ ts, tsvfs, compilerOptions },
{ filePath },
)
return {
parseForESLint(code, options) {
host.fsMap.set(filePath, code)
// Requires its own Program instance to provide full type information.
const program = createProgram(
{ ts, compilerHost: host.compilerHost, compilerOptions },
{ filePath },
)
try {
const result = tsParser.parseForESLint(code, {
...options,
filePath: filePath.replace(/^\//u, ""),
programs: [program],
})
return result
} catch (e) {
// eslint-disable-next-line no-console -- Demo debug
console.error(e)
throw e
}
},
}
}