custom-worker.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // This example uses @typescript/vfs to create a virtual TS program
  2. // which can do work on a bg thread.
  3. importScripts("https://unpkg.com/@typescript/vfs@1.3.0/dist/vfs.globals.js")
  4. /**
  5. *
  6. * @param {import("../src/tsWorker").TypeScriptWorker} TypeScriptWorker
  7. * @param {import("typescript")} ts
  8. * @param {Record<string, string>} libFileMap
  9. *
  10. */
  11. const worker = (TypeScriptWorker, ts, libFileMap) => {
  12. /** @type { import("@typescript/vfs") } */
  13. const tsvfs = globalThis.tsvfs
  14. return class MonacoTSWorker extends TypeScriptWorker {
  15. // Adds a custom function to the webworker
  16. async getDTSEmitForFile(fileName) {
  17. const result = await this.getEmitOutput(fileName)
  18. const firstDTS = result.outputFiles.find(o => o.name.endsWith(".d.ts"))
  19. return (firstDTS && firstDTS.text) || ""
  20. }
  21. async printAST(fileName) {
  22. console.log("Creating virtual TS project")
  23. const compilerOptions = this.getCompilationSettings()
  24. const fsMap = new Map()
  25. for (const key of Object.keys(libFileMap)) {
  26. fsMap.set(key, "/" + libFileMap[key])
  27. }
  28. const thisCode = await this.getScriptText(fileName)
  29. fsMap.set("index.ts", thisCode)
  30. console.log("Starting up TS program")
  31. const system = tsvfs.createSystem(fsMap)
  32. const host = tsvfs.createVirtualCompilerHost(system, compilerOptions, ts)
  33. const program = ts.createProgram({
  34. rootNames: [...fsMap.keys()],
  35. options: compilerOptions,
  36. host: host.compilerHost,
  37. })
  38. // Now I can look at the AST for the .ts file too
  39. const mainSrcFile = program.getSourceFile("index.ts")
  40. let miniAST = "SourceFile"
  41. const recurse = (parent, depth) => {
  42. if (depth > 5) return
  43. ts.forEachChild(parent, node => {
  44. const spaces = " ".repeat(depth + 1)
  45. miniAST += `\n${spaces}${ts.SyntaxKind[node.kind]}`
  46. recurse(node, depth + 1)
  47. })
  48. }
  49. recurse(mainSrcFile, 0)
  50. return miniAST
  51. }
  52. }
  53. }
  54. self.customTSWorkerFactory = worker