@omniblack/worker
v0.0.1
Published
A basic typed worker for Bun. Gives you a type-safe request/response interface over Bun's `Worker`, so you can `send` a message and `await` the result.
Readme
worker_ts
A basic typed worker for Bun. Gives you a type-safe request/response interface over Bun's Worker, so you can send a message and await the result.
Install
bun add worker_tsUsage
1. Define your worker
Create a worker file that defines handler functions and calls process. The handler signatures become your message/return types automatically.
// my-worker.ts
import { process } from "worker_ts/worker";
import type { HandlersToMessages, HandlersToReturns } from "worker_ts";
interface AddMessage {
a: number;
b: number;
}
function add(msg: AddMessage): number {
return msg.a + msg.b;
}
async function greet(msg: { name: string }): Promise<string> {
return `Hello, ${msg.name}!`;
}
const handlers = {
add,
greet,
};
// Export these so the main thread can reference them
export type Messages = HandlersToMessages<typeof handlers>;
export type Returns = HandlersToReturns<typeof handlers>;
await process(handlers);2. Use the worker from the main thread
import { TypedWorker } from "worker_ts";
import type { Messages, Returns } from "./my-worker.ts";
await using worker = new TypedWorker<Messages, Returns>("./my-worker.ts");
const sum = await worker.send("add", { a: 1, b: 2 });
console.log(sum); // 3
const greeting = await worker.send("greet", { name: "world" });
console.log(greeting); // "Hello, world!"Message types and return types are fully inferred — send("add", ...) expects AddMessage and returns Promise<number>.
3. Cleanup
TypedWorker implements AsyncDisposable, so await using will automatically shut the worker down when it goes out of scope. You can also dispose manually:
const worker = new TypedWorker<Messages, Returns>("./my-worker.ts");
// ... do work ...
await worker[Symbol.asyncDispose]();Checking if the worker is busy
worker.busy; // true if any sent messages are still awaiting a response