Adds a vfs project

This commit is contained in:
Orta 2020-08-31 13:09:47 -04:00
parent 89fdcf5424
commit 166e63b991
5 changed files with 117 additions and 30 deletions

View file

@ -1,4 +1,19 @@
self.customTSWorkerFactory = (TypeScriptWorker) => {
// This example uses @typescript/vfs to create a virtual TS program
// which can do work on a bg thread.
importScripts("https://unpkg.com/@typescript/vfs@1.3.0/dist/vfs.globals.js")
/**
*
* @param {import("../src/tsWorker").TypeScriptWorker} TypeScriptWorker
* @param {import("typescript")} ts
* @param {Record<string, string>} libFileMap
*
*/
const worker = (TypeScriptWorker, ts, libFileMap) => {
/** @type { import("@typescript/vfs") } */
const tsvfs = globalThis.tsvfs
return class MonacoTSWorker extends TypeScriptWorker {
// Adds a custom function to the webworker
@ -8,5 +23,44 @@ self.customTSWorkerFactory = (TypeScriptWorker) => {
return (firstDTS && firstDTS.text) || ""
}
async printAST(fileName) {
console.log("Creating virtual TS project")
const compilerOptions = this.getCompilationSettings()
const fsMap = new Map()
for (const key of Object.keys(libFileMap)) {
fsMap.set(key, "/" + libFileMap[key])
}
const thisCode = await this.getScriptText(fileName)
fsMap.set("index.ts", thisCode)
console.log("Starting up TS program")
const system = tsvfs.createSystem(fsMap)
const host = tsvfs.createVirtualCompilerHost(system, compilerOptions, ts)
const program = ts.createProgram({
rootNames: [...fsMap.keys()],
options: compilerOptions,
host: host.compilerHost,
})
// Now I can look at the AST for the .ts file too
const mainSrcFile = program.getSourceFile("index.ts")
let miniAST = "SourceFile"
const recurse = (parent, depth) => {
if (depth > 5) return
ts.forEachChild(parent, node => {
const spaces = " ".repeat(depth + 1)
miniAST += `\n${spaces}${ts.SyntaxKind[node.kind]}`
recurse(node, depth + 1)
})
}
recurse(mainSrcFile, 0)
return miniAST
}
}
}
self.customTSWorkerFactory = worker