custom-worker.js 1.9 KB

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