diff --git a/src/tsWorker.ts b/src/tsWorker.ts index f4079ae..c785d75 100644 --- a/src/tsWorker.ts +++ b/src/tsWorker.ts @@ -37,7 +37,7 @@ export class TypeScriptWorker implements ts.LanguageServiceHost, monaco.language return models.concat(Object.keys(this._extraLibs)); } - _getModel(fileName: string): monaco.worker.IMirrorModel | null { + private _getModel(fileName: string): monaco.worker.IMirrorModel | null { let models = this._ctx.getMirrorModels(); for (let i = 0; i < models.length; i++) { if (models[i].uri.toString() === fileName) { @@ -257,22 +257,28 @@ export interface ICreateData { customWorkerPath?: string } +/** The shape of the factory */ +export interface CustomTSWebWorkerFactory { + (TSWorkerClass: typeof TypeScriptWorker, ts: typeof import("typescript"), libs: Record): typeof TypeScriptWorker +} + export function create(ctx: IWorkerContext, createData: ICreateData): TypeScriptWorker { let TSWorkerClass = TypeScriptWorker if (createData.customWorkerPath) { - // @ts-ignore - This is available in a webworker if (typeof importScripts === "undefined") { console.warn("Monaco is not using webworkers for background tasks, and that is needed to support the customWorkerPath flag") } else { // @ts-ignore - This is available in a webworker importScripts(createData.customWorkerPath) + // @ts-ignore - This should come from the above eval - if (!self.customTSWorkerFactory) { + const workerFactoryFunc: CustomTSWebWorkerFactory | undefined = self.customTSWorkerFactory + if (!workerFactoryFunc) { throw new Error(`The script at ${createData.customWorkerPath} does not add customTSWorkerFactory to self`) } - // @ts-ignore - The throw validates this - TSWorkerClass = self.customTSWorkerFactory(TypeScriptWorker, ts, libFileMap) + + TSWorkerClass = workerFactoryFunc(TypeScriptWorker, ts, libFileMap) } } diff --git a/test/custom-worker.js b/test/custom-worker.js index ccc7e0f..3eeacd1 100644 --- a/test/custom-worker.js +++ b/test/custom-worker.js @@ -1,19 +1,14 @@ // This example uses @typescript/vfs to create a virtual TS program // which can do work on a bg thread. +// This version of the vfs edits the global scope (in the case of a webworker, this is 'self') 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} libFileMap - * - */ -const worker = (TypeScriptWorker, ts, libFileMap) => { - /** @type { import("@typescript/vfs") } */ - const tsvfs = globalThis.tsvfs +/** @type { import("@typescript/vfs") } */ +const tsvfs = globalThis.tsvfs +/** @type {import("../src/tsWorker").CustomTSWebWorkerFactory }*/ +const worker = (TypeScriptWorker, ts, libFileMap) => { return class MonacoTSWorker extends TypeScriptWorker { // Adds a custom function to the webworker @@ -59,7 +54,6 @@ const worker = (TypeScriptWorker, ts, libFileMap) => { recurse(mainSrcFile, 0) return miniAST } - } }