Skip to content

Commit

Permalink
Prototyping TS Server plugins on web
Browse files Browse the repository at this point in the history
This is a first exploration for  microsoft#47376 microsoft/vscode#140455

It implements a very basic version of `require` for the web that lets us load plugins with a very specific structure. `require` being sync limits our options here, so I'm using `importScripts` plus a global to get the exports of a plugin. The plugin must also be compiled down to a single file at the moment
  • Loading branch information
mjbvz committed Jan 11, 2022
1 parent 852b1c2 commit ba3586a
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion src/webServer/webServer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/*@internal*/
/// <reference lib="dom" />

namespace ts.server {
export interface HostWithWriteMessage {
writeMessage(s: any): void;
Expand Down Expand Up @@ -136,7 +138,34 @@ namespace ts.server {
clearImmediate: handle => clearTimeout(handle),
/* eslint-enable no-restricted-globals */

require: () => ({ module: undefined, error: new Error("Not implemented") }),
require: (initialPath: string, moduleName: string) => {
// TODO: figure out how to implement this without having to implement
// all of 'require'

// TODO: Path is currently hardcoded
const fullPath = initialPath + "/" + moduleName + "/lib/index.js";
if (fullPath.startsWith("http://") || fullPath.startsWith("https://")) {
try {
// Sync load the script into the current scope
(globalThis as any).importScripts(fullPath);
}
catch (e) {
return ({ module: undefined, error: new Error(`Could not evaluate module ${e}`) });
}

// Try to get export from global. Use the module name for this.
// Not sure a better way to do this synchronously
const module = (globalThis as any)[moduleName];
if (module) {
return ({ module, error: undefined });
}
else {
return ({ module: undefined, error: new Error(`Could not find module export for ${moduleName}`) });
}
}

return ({ module: undefined, error: new Error("Could not resolve module") });
},
exit: notImplemented,

// Debugging related
Expand Down

0 comments on commit ba3586a

Please sign in to comment.