No description
Find a file
2025-04-06 17:32:15 +02:00
dist Fix typing for promises 2025-04-02 18:38:49 +02:00
tests Add tests 2025-04-06 17:32:15 +02:00
.gitignore Build 2025-04-02 18:10:06 +02:00
.npmignore Update tsconfig and package.json to build properly 2025-03-27 09:06:02 +00:00
biome.json Initial commit 2025-03-08 12:48:37 +01:00
index.ts Fix typing for promises 2025-04-02 18:38:49 +02:00
package-lock.json Initial commit 2025-03-27 09:37:57 +01:00
package.json Add tests 2025-04-06 17:32:15 +02:00
README.md Add README 2025-04-03 09:09:03 +01:00
tsconfig.json Update tsconfig and package.json to build properly 2025-03-27 09:06:02 +00:00

worker.rpc

This project is a work in progress and is still undergoing much change

A simple library that provides a typesafe rpc interface to web workers.

Install

To add it to your project simply run (not yet published to npm) :

$ npm i git+https://git.suroh.tk/suroh/worker.rpc.git

Usage

You will import the library into both the file that instantiates the worker, as well as the worker itself. Let's create the worker in our client.js file, set some methods that can be called from the worker itself and call a method from the webWorker itself :

Pre-emptively we are importing the types back from the worker.ts file so that our calls to the worker are also typesafe.

// client.js
import { WorkerRpc } from 'worker.rpc'
// types from the worker
import { type WorkerMethods } from './worker.ts'

const webWorker = new Worker('./worker.ts')
const workerRpc = new WorkerRpc<WorkerMethods>(webWorker)

const mainMethods = workerRpc.set({
    hello: (name: string) => {
        console.log(`Hello ${name}!`)
        // calling the method goodBye set in the worker
        workerRpc.call.goodBye(name)
    }
})

// export the method type
export type MainMethods = typeof mainMethods

Note that we export the type of workerMethods so that we can safely type the rpc from the worker. The code for this is more or less the same

// worker.js
import { WorkerRpc } from 'worker.rpc'
// types from client.ts
import { type MainMethods } from './client.ts'

const mainRpc = new WorkerRpc<MainMethods>(self)

const workerMethods = mainRpc.set({
    goodBye: (name: string) => `Goodbye ${name}!`
})

// calling the method hello set in the client
mainRpc.call.hello('Bob')

// export the method type
export type WorkerMethods = typeof workerMethods

Desires

It would be better if the class could export its own types, or infer the remote types on creation. Right now creating a variable to only export it as typeof seems clunky. A workaround for this would be setting the methods in the constructor.