microsoft/qdk
Publicmirrored from https://github.com/microsoft/qdkAvailable
npm/src/worker-browser.ts
47lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | // This module supports running the compiler inside a browser WebWorker. This is set as |
| 5 | // the "qsharp/worker" entry point using 'conditional exports' in package.json. |
| 6 | // The worker script to be loaded in the browser should import the handler via |
| 7 | // `import { messageHandler } from "qsharp/worker"` and assign this to 'self.onmessage'. |
| 8 | |
| 9 | import * as wasm from "../lib/web/qsc_wasm.js"; |
| 10 | import { log } from "./log.js"; |
| 11 | import { Compiler } from "./compiler.js"; |
| 12 | import { |
| 13 | getWorkerEventHandlers, |
| 14 | handleMessageInWorker, |
| 15 | } from "./worker-common.js"; |
| 16 | |
| 17 | // Used to sent messages back to the client when events occur during request processing |
| 18 | const evtTarget = getWorkerEventHandlers(self.postMessage); |
| 19 | |
| 20 | let compiler: Compiler | null = null; |
| 21 | |
| 22 | // This export should be assigned to 'self.onmessage' in a WebWorker |
| 23 | export function messageHandler(e: MessageEvent) { |
| 24 | const data = e.data; |
| 25 | |
| 26 | if (!data.type || typeof data.type !== "string") { |
| 27 | log.error(`Unrecognized msg: ${data}`); |
| 28 | return; |
| 29 | } |
| 30 | |
| 31 | switch (data.type) { |
| 32 | case "init": |
| 33 | log.setLogLevel(data.qscLogLevel); |
| 34 | wasm.initSync(data.wasmModule); |
| 35 | compiler = new Compiler(wasm); |
| 36 | break; |
| 37 | default: |
| 38 | if (!compiler) { |
| 39 | log.error( |
| 40 | `Received message before the compiler was initialized: %o`, |
| 41 | data |
| 42 | ); |
| 43 | } else { |
| 44 | handleMessageInWorker(data, compiler, self.postMessage, evtTarget); |
| 45 | } |
| 46 | } |
| 47 | } |