npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

blue-tie

v1.3.0

Published

Simple typed Worker abstractions for Node.js and browser

Downloads

5

Readme

Blue Tie

Blue Tie creates simple typed abstractions over JavaScript Worker threads, compatible with both Node.js and browser applications.

Installation

npm install --save blue-tie

Usage

Define a worker:

// fibonacci-worker.ts
import { defineWorker, getBrowserScript, isNode } from "blue-tie"

export const fibonacciWorker = defineWorker(
  "fibonacci-worker",
  isNode ? __filename : getBrowserScript(),
  {
    fibonacci: async (n: number) => {
      return doFibonacci(n)
    },
  }
)

// This is an intentionally naive Fibonacci implementation.
function doFibonacci(n: number): number {
  if (n < 1) {
    return 0
  }
  if (n === 1) {
    return 1
  }
  return doFibonacci(n - 1) + doFibonacci(n - 2)
}

Create and use the worker:

// main.ts
import { isMainThread } from "blue-tie"
import { fibonacciWorker } from "./fibonacci-worker.ts"

// Guard against running this code in worker threads.
// Note: This guard is not necessary in every setup.
if (isMainThread) {
  // Instantiate a worker.
  const worker = fibonacciWorker.create()

  // Call functions in the worker.
  const result = await worker.fibonacci(19)
  console.log(`Fibonacci with n 19 is ${result}`)

  // Clean up when you're done.
  await fibonacciWorker.close(worker)
}

Examples

Some fully functional examples are available in the examples/ directory.

Implementation Notes

Passing Values

It should be noted that all values transferred between worker and main thread are copied by value. This library attempts to hide that and make everything feel like native shared-memory multithreaded programming, but it is merely made to look that way.

As such, be careful not to assume that pointers are equivalent, and be aware that passing functions may not behave entirely as expected.

Worker File Name

The second parameter (fileName) of the defineWorker() function is important to get right.

For Node.js, this value should almost always be __filename. This values makes the library load the Worker using the literal same script containing the worker definition, which is exactly what needs to be run. In the event that the application is bundled, this value could instead be a literal pointing to a separate bundle created specifically for the worker(s).

For the browser, this value may be set to getBrowserScript() (exported from this library) if the worker script is going to be the exact same script as the parent application. Typically, such a setup would require gating the main startup logic behind some if (isMainThread) ... construct. Alternatively, this value could point to a separate bundle created specifically for the worker(s).

Bundling

This library necessitates using a bundler to function in the browser. There are two completely separate implementations of the code specific to the APIs available in Node.js and the browser. Bundlers like esbuild will respect the package definition and pick the appropriate implementation for the bundle.

Stateful Workers

The primary examples for this library demonstrate farming out pure functions to background worker threads. However, this library does enable preserving state by returning functions from the worker.

// remote-function-worker.ts
import { defineWorker, getBrowserScript, isNode } from "blue-tie"

const { strictEqual, test } = testLib

const remoteFunctionWorker = defineWorker(
  "remote-functions-worker",
  isNode ? __filename : getBrowserScript(),
  {
    getStatefulFunc: async () => {
      let state = 0
      return async () => {
        state++
        return state
      }
    },
  }
)

The function returned from the worker will be proxied, so that it may be called as if directly.

// main.ts
import { remoteFunctionWorker } from "remote-function-worker"

await remoteFunctionWorker.withInstance(async (worker) => {
  const f = await worker.getStatefulFunc()
  await f() // 1
  await f() // 2
  await f() // 3
})

If using a long-lived worker with lots of stateful functions, function references should be freed to avoid memory leaks. (They will be cleaned up automatically when the worker is closed.)

// main.ts
import { remoteFunctionWorker } from "remote-function-worker"

const worker = remoteFunctionWorker.create()
const f1 = await worker.getStatefulFunc()
const f2 = await worker.getStatefulFunc()
await f1() // 1
await f1() // 2
await f2() // 1
await f2() // 2
await remoteFunctionWorker.free(worker, f1)
await remoteFunctionWorker.free(worker, f2)