| 6 | * while the main thread's event loop remains blocked. |
| 7 | */ |
| 8 |
| 9 | import { parentPort } from "node:worker_threads"; |
| 10 | import type { MessagePort } from "node:worker_threads"; |
| 11 | import { fetchModule } from "./fetch.ts"; |
| 12 | import type { FetchOptions } from "./fetch.ts"; |
| 13 | import type { CacheEntry } from "./cache.ts"; |
| 14 |
| 15 | interface FetchRequest { |
| 16 | url: string; |
| 17 | options: FetchOptions; |
| 18 | signal: SharedArrayBuffer; |
| 19 | port: MessagePort; |
| 20 | } |
| 21 |
| 22 | type FetchResponse = { entry: CacheEntry } | { error: string }; |
| 23 |
| 24 | parentPort!.on("message", async ({ url, options, signal: buffer, port }: FetchRequest) => { |
| 25 | const signal = new Int32Array(buffer); |
| 26 | let response: FetchResponse; |
| 27 | try { |
| 28 | response = { entry: await fetchModule(url, options) }; |
| 29 | } catch (error) { |
| 30 | response = { error: error instanceof Error ? error.message : String(error) }; |
| 31 | } |
| 32 | try { |
| 33 | port.postMessage(response); |
| 34 | } finally { |
| 35 | // Always release the wait, including when sending the response fails. |
| 36 | port.close(); |
| 37 | Atomics.store(signal, 0, 1); |
| 38 | Atomics.notify(signal, 0); |
| 39 | } |
| 40 | }); |
| 41 |