interface IWorkerHandle
Since 0.1.0

Handle to one spawned worker thread, normalized across web Worker (Deno/Bun) and node:worker_threads (Node).

Messages travel by structured clone. Listeners receive the message payload directly (already unwrapped from MessageEvent on web-worker runtimes).

Methods

postMessage(message: unknown): void

Posts a structured-clonable message to the worker.

onMessage(listener: (message: unknown) => void): void

Registers a listener for messages from the worker.

onError(listener: (error: Error) => void): void

Registers a listener for worker-level errors (module evaluation failure, uncaught error in the worker).

Since 0.3.0
optional
onExit(listener: (code: number | null) => void): void

Registers a listener for the worker's THREAD ENDING, however it ended — a clean self-termination included. This is distinct from onError, which reports a failure the worker survived long enough to report; a worker that simply stops raises no error at all.

Optional, and its absence is load-bearing information rather than a shortfall to work around: a host omits it when its runtime emits nothing when a worker ends, so a consumer MUST treat absence as "this runtime cannot tell me a worker died" and not as "no worker has died". Ask IWorkerHost.reportsExit before spawning if the answer changes what you configure.

Fires for a host-requested terminate() too on runtimes that implement it that way, so a consumer that terminates deliberately must track that itself rather than reading every exit as a crash.

terminate(): Promise<void>

Terminates the worker immediately.

Usage

import { type IWorkerHandle } from "common/src/index.ts";