microsoft/qdk
Publicmirrored from https://github.com/microsoft/qdkAvailable
source/npm/qsharp/src/workers/adapters/node.ts
44lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | import { Worker } from "node:worker_threads"; |
| 5 | import type { IWorkerHost } from "./types.js"; |
| 6 | |
| 7 | export class NodeWorkerHost implements IWorkerHost { |
| 8 | private worker: Worker; |
| 9 | |
| 10 | constructor(url: string | URL) { |
| 11 | const workerUrl = typeof url === "string" ? new URL(url) : url; |
| 12 | const bootstrap = ` |
| 13 | import { parentPort } from 'node:worker_threads'; |
| 14 | globalThis.WorkerSelf = { |
| 15 | postMessage(msg) { parentPort.postMessage(msg); }, |
| 16 | onMessage(handler) { |
| 17 | parentPort.on('message', (data) => handler({ data })); |
| 18 | } |
| 19 | }; |
| 20 | await import("${workerUrl.href}"); |
| 21 | `; |
| 22 | this.worker = new Worker( |
| 23 | new URL(`data:text/javascript,${encodeURIComponent(bootstrap)}`), |
| 24 | ); |
| 25 | } |
| 26 | |
| 27 | postMessage(msg: unknown): void { |
| 28 | this.worker.postMessage(msg); |
| 29 | } |
| 30 | |
| 31 | onMessage(handler: (e: MessageEvent) => void): void { |
| 32 | this.worker.on("message", (data) => { |
| 33 | handler({ data } as MessageEvent); |
| 34 | }); |
| 35 | } |
| 36 | |
| 37 | onError(handler: (e: Event) => void): void { |
| 38 | this.worker.on("error", handler); |
| 39 | } |
| 40 | |
| 41 | terminate(): void { |
| 42 | this.worker.terminate(); |
| 43 | } |
| 44 | } |