Repository navigation
feat: support plain Node by running codec workers on node:worker_threads - #11
Conversation
Plain Node has no global `Worker`, so every pooled task that fell back to `new Worker(...)` threw `ReferenceError: Worker is not defined`. That made `getWorker`/`setWorker` unusable outside a browser, and nothing exercised the path, so it stayed broken silently. worker-pool (1.0.0 -> 1.1.0): - Add `WorkerLike`, the slice of the `Worker` API the pool and its tasks actually use, plus `WorkerMessageEventLike`/`WorkerErrorEventLike`. `WorkerPoolTask` and `WorkerPool.workerQueue` are typed against it rather than the DOM global, which is what lets one task function serve both runtimes. A browser `Worker` satisfies it structurally. - Add `NodeWorker`, a `node:worker_threads` adapter behind that interface, plus `createWorker` (picks per runtime) and `isNodeRuntime`. `node:worker_threads` is imported through a variable specifier carrying `@vite-ignore`/`webpackIgnore`, so browser bundles never resolve it. fizarrita (1.4.1 -> 1.5.0): - Lift the codec protocol and pipeline cache out of `codec-worker.ts` into `internals/codec-worker-core.ts`. `codec-worker.ts` is now a thin browser entry; `codec-worker-node.ts` is the `parentPort` equivalent. Both are exposed as subpath exports, as is `handleCodecMessage`. - Add `create-worker.ts` with a single `createDefaultWorker`/ `createCodecWorker`, replacing the copy that existed in each of get/set. The browser branch keeps the literal `new Worker(new URL(...))` form bundlers need to detect a worker entry; the Node branch is deliberately hidden from them behind a variable. Four ways a request could hang are closed, since a dropped message reads to an RPC caller as a request that never finishes: a startup failure landing before listeners attach is latched and replayed; an unrequested thread exit raises an error even at code 0; posting after `terminate()` raises rather than no-opping (a deliberate divergence from browser `Worker`); and a reply that fails to post is retried without its payload. Tests: 37 Node tests under `test/node/` covering pool scheduling, transfer lists, worker-path forms, `workerData`, the error/exit/terminate paths, and `setWorker`/`getWorker` round-trips through zstd, blosc, edge chunks, chunk cache, SharedArrayBuffer `decode_into`, and fill values. Four browser tests cover the other branch of `createWorker`. Wired into CI ahead of Playwright. Also fixes `pnpm install` exiting 1: pnpm 11 no longer reads `pnpm.onlyBuiltDependencies` from package.json, leaving esbuild unapproved and every pnpm script failing. Moved to `allowBuilds` in pnpm-workspace.yaml. Note for consumers: a task callback annotated `(worker: Worker | null)` no longer typechecks under strictFunctionTypes and must say `WorkerLike | null`. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
📝 WalkthroughWalkthroughThe PR adds cross-runtime worker support through ChangesCross-runtime worker support
Estimated code review effort: 4 (Complex) | ~60 minutes PoemPoem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Pull request overview
Adds first-class Node.js support for the worker-pool runtime path by introducing a WorkerLike abstraction plus a node:worker_threads adapter, and refactors fizarrita’s codec worker into shared core logic with separate browser/Node entries. This makes getWorker/setWorker and pooled tasks usable in plain Node without a global Worker.
Changes:
- Introduce
WorkerLike,NodeWorker,createWorker(), andisNodeRuntime(); update the pool/task typing to be runtime-agnostic. - Split fizarrita’s codec worker into a shared core (
handleCodecMessage) and thin browser/Node entry points; add runtime-aware codec worker creation helpers. - Add comprehensive Node test suite and wire it into CI; update docs and pnpm build-allowlist config.
Reviewed changes
Copilot reviewed 28 out of 28 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| test/node/worker-pool.test.js | Node integration tests for WorkerPool scheduling, transfers, and NodeWorker behaviors. |
| test/node/square-worker.mjs | Minimal worker_threads worker used by Node pool tests. |
| test/node/node-worker-api.test.js | NodeWorker/createWorker API-surface tests (URL/path handling, workerData, terminate semantics). |
| test/node/fizarrita.test.js | End-to-end Node tests for fizarrita get/set through the pool with real zarrita arrays. |
| test/node/exiting-worker.mjs | Worker that exits without replying to validate “reject not hang” behavior. |
| test/node/echo-worker.mjs | Worker that echoes workerData to validate constructor option pass-through. |
| test/node/codec-worker-core.test.js | Direct tests of handleCodecMessage protocol/core logic without a worker thread. |
| test/browser/runtime-worker.spec.ts | Browser coverage for runtime-aware worker factories and fizarrita default worker protocol. |
| test/app/zarrita/index.ts | Update test app typings from Worker to WorkerLike for task signatures. |
| test/app/main.ts | Expose runtime helpers to Playwright and update task helpers to use WorkerLike + event listeners. |
| src/worker-pool.ts | Retype worker slots/queue to WorkerLike and update docs to reflect non-browser workers. |
| src/types.ts | Add WorkerLike + event-like types; update WorkerPoolTask contract to use WorkerLike. |
| src/node-worker.ts | Implement NodeWorker adapter + createWorker()/isNodeRuntime() runtime selection. |
| src/index.ts | Export new Node runtime APIs and the new public types. |
| README.md | Document Node support, WorkerLike, and recommended termination patterns (finally blocks). |
| pnpm-workspace.yaml | Add pnpm build allowlist for esbuild to keep installs/scripts working. |
| package.json | Bump version, add node-related keywords, add test:node script, update package description. |
| fizarrita/src/worker-rpc.ts | Retype dispatcher to WorkerLike and use shared event-like types. |
| fizarrita/src/set-worker.ts | Switch worker construction to createCodecWorker; update task slot typing to WorkerLike. |
| fizarrita/src/internals/codec-worker-core.ts | New shared codec worker core (handleCodecMessage) and pipeline caching/protocol handling. |
| fizarrita/src/index.ts | Re-export new worker creation helpers and codec worker core types/handler. |
| fizarrita/src/get-worker.ts | Switch worker construction to createCodecWorker; update task slot typing to WorkerLike. |
| fizarrita/src/create-worker.ts | Add runtime-aware createDefaultWorker/createCodecWorker and keep bundler-detectable browser worker form. |
| fizarrita/src/codec-worker.ts | Make browser worker entry a thin wrapper over handleCodecMessage with retry-on-post failure. |
| fizarrita/src/codec-worker-node.ts | Add Node worker_threads entry point that wires parentPort to handleCodecMessage. |
| fizarrita/README.md | Document Node behavior and new subpath exports for browser + node codec workers. |
| fizarrita/package.json | Bump version and add exports for node worker and codec-worker core. |
| .github/workflows/ci.yml | Add Node test step before Playwright; rename browser test step for clarity. |
Suppressed comments (1)
fizarrita/src/internals/codec-worker-core.ts:317
- Same issue in the encode path: when
metaIdisn't registered andmetais absent,meta = msg.meta!produces an unhelpful runtime error message that gets surfaced to callers. Prefer an explicit check and a stable, actionable error string.
if (msg.metaId !== undefined && pipelineByMetaId.has(msg.metaId)) {
pipeline = getPipeline(msg.metaId)
meta = metaByMetaId.get(msg.metaId)!
} else {
meta = msg.meta!
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
A decode or encode naming an unregistered `metaId` with no inline `meta` fell through to the legacy path with `meta` undefined, so the failure surfaced as `Cannot read properties of undefined (reading 'data_type')`. That names nothing the caller can act on, and it moves with any refactor of the pipeline builder. Both call sites now go through `resolvePipeline`, which reports the actual cause: a request referencing codec metadata the worker was never sent. The existing test asserted only that some error came back, which is what let the unhelpful message through; it now asserts the specific text. Raised by Copilot on #11. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
|
Review round addressed — pushed c1d45bd. Copilot: 1 comment, valid, fixed. Unregistered The useful part of that finding was the second half — that the error string was unstable. It had already caught me out: I hit that exact message while writing CodeRabbit: no review. Both the CLI and the GitHub app returned rate-limit errors with The gap that leaves is specific: an earlier CLI run did review the tracked modified files and produced three valid Anyone wanting real CodeRabbit coverage of the new files can comment 38 Node + 123 browser tests pass. |
|
Tip For best results, initiate chat on the files or code changes.
I noted that the new worker and codec files did not receive CodeRabbit coverage. I also noted the ✏️ Learnings added
You are interacting with an AI system. |
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (5)
fizarrita/src/codec-worker.ts (1)
19-37: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: move the post-and-fallback block into the shared core.
codec-worker-node.tslines 40-55 contain the same reply-posting and fallback logic. Export a helper frominternals/codec-worker-core.tsthat takes a post function, then both entries call it. This keeps the two runtimes from drifting.♻️ Sketch
// internals/codec-worker-core.ts export async function dispatchCodecMessage( msg: CodecWorkerMessage, post: (response: Record<string, unknown>, transfer?: ArrayBuffer[]) => void, ): Promise<void> { const reply = await handleCodecMessage(msg) if (!reply) return try { post(reply.response, reply.transfer) } catch (error) { post({ type: reply.response.type, id: reply.response.id, error: error instanceof Error ? error.message : String(error), }) } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@fizarrita/src/codec-worker.ts` around lines 19 - 37, Move the shared reply-posting and fallback behavior from the codec worker entrypoints into a new exported dispatchCodecMessage helper in codec-worker-core, accepting the message and post callback. Update the browser worker’s message listener and codec-worker-node to call this helper, preserving the existing transfer handling and fallback error response.fizarrita/src/internals/codec-worker-core.ts (1)
120-156: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winThe pipeline caches grow without bound.
pipelineByMetaId,metaByMetaId, andpipelineByKeyare module-level maps and no entry is ever removed. A worker thread is long-lived and is reused across arrays, so each newmetaIdor inlinemetaadds a permanent entry. Add an eviction policy, for example a bounded LRU, or add areleasemessage type that deletes ametaId.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@fizarrita/src/internals/codec-worker-core.ts` around lines 120 - 156, Add bounded cache eviction for the module-level pipelineByMetaId, metaByMetaId, and pipelineByKey maps, or implement a release message that removes associated metaId entries and pipelines. Ensure cleanup is triggered as arrays are discarded so long-lived workers do not retain every created pipeline indefinitely, while preserving current getPipeline and getOrCreatePipelineLegacy behavior for active entries.test/node/worker-pool.test.js (1)
162-180: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: resolve from the listener instead of polling.
The poll loop adds latency and extra timers. Resolve the promise directly in the
messagelistener when four results arrive.♻️ Proposed refactor
- const seen = [] - worker.addEventListener('message', (event) => seen.push(event.data.result)) + const seen = [] + const done = new Promise((resolve) => { + worker.addEventListener('message', (event) => { + seen.push(event.data.result) + if (seen.length === 4) resolve() + }) + }) // All four are posted synchronously, before the dynamic import of // node:worker_threads has even resolved. for (const value of [1, 2, 3, 4]) worker.postMessage({ value }) - await new Promise((resolve) => { - const check = () => (seen.length === 4 ? resolve() : setTimeout(check, 10)) - check() - }) + await done assert.deepEqual(seen, [1, 4, 9, 16])🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/node/worker-pool.test.js` around lines 162 - 180, Update the message-waiting logic in the test around createWorker and the seen listener to resolve the promise directly when the fourth result is received, rather than polling with setTimeout. Preserve the existing result collection, ordering assertion, timeout, and worker termination behavior.test/browser/runtime-worker.spec.ts (2)
46-53: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winRemove the stale error listener when a pooled task completes.
Line 52 adds an error listener, but Line 48 removes only
onMessage.WorkerPoolreuses the worker for later tasks, so each successful task leaves an error listener attached. Use onedetach()function that removes both listeners before resolving or rejecting.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/browser/runtime-worker.spec.ts` around lines 46 - 53, Update the worker task setup around the onMessage listener to define a shared detach() function that removes both the message and error listeners. Call detach() before resolving on successful completion and before rejecting on worker errors, ensuring pooled Worker instances do not retain listeners between tasks.
43-57: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winKeep the pool test type-safe.
Lines 43, 46, and 57 bypass the
WorkerLikeandWorkerPoolTask<number>contracts withunknown, a browserWorkercast, andas never. The test can pass while returning an incompatible worker. Type the slot asWorkerLike | null, keep the local worker asWorkerLike, and callrunTasks<number>(tasks)without the cast.Proposed fix
+import type { WorkerLike } from '../../src/index.js' ... - const tasks = [2, 3, 4].map((value) => async (slot: unknown) => { - const worker = slot ?? window.createWorker(window.testWorkerUrl) + const tasks = [2, 3, 4].map((value) => async (slot: WorkerLike | null) => { + const worker: WorkerLike = + slot ?? window.createWorker(window.testWorkerUrl) ... - const w = worker as Worker + const w = worker ... - const { promise } = pool.runTasks(tasks as never) + const { promise } = pool.runTasks<number>(tasks)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/browser/runtime-worker.spec.ts` around lines 43 - 57, Make the pool test type-safe by typing the task slot as WorkerLike | null and keeping the local worker variable as WorkerLike instead of using unknown or casting to the browser Worker type. Update the task array and invoke pool.runTasks<number>(tasks) directly, removing the as never cast while preserving the existing worker creation and result handling.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@fizarrita/README.md`:
- Around line 252-261: Clarify the subpath worker documentation near the
codec-worker examples: state that these modules are worker entry points only and
that bare imports execute them in the current context, or document
createDefaultWorker() as the supported API for creating workers and obtaining a
workerUrl. Avoid implying that importing either subpath creates a worker.
In `@fizarrita/src/internals/codec-worker-core.ts`:
- Around line 45-78: Update fixEdgeChunkShapeStride to explicitly reject decoded
chunks whose actualElements are less than expectedElements, before returning the
unchanged chunk. Throw a clear error for this undersized-data case, while
preserving the existing shape/stride correction for matching or padded chunks
and the fallback behavior when actualChunkShape is absent.
In `@package.json`:
- Around line 3-4: Update the package version from 1.1.0 to 2.0.0 to reflect the
breaking public WorkerLike type change; do not release this incompatible API
under the 1.x version range.
In `@src/node-worker.ts`:
- Around line 169-176: Update NodeWorker.terminate() and its thread-exit
handling to reject all active WorkerDispatcher requests with a termination error
once the thread stops, instead of suppressing the error when terminated is true.
Preserve idempotency for repeated terminate() calls, and add coverage that waits
for startup, sends a delayed request, terminates the worker, and asserts the
request rejects.
In `@test/app/main.ts`:
- Around line 44-45: Update the intentionally failing task returned by the
worker callback to terminate the created or borrowed worker before rejecting.
Ensure the worker referenced by w is terminated on every failure path, including
when the task does not return a resolved worker, while preserving the existing
rejection behavior.
- Line 19: Update the worker construction around testWorkerUrl and the
corresponding usage near the second Worker creation to use Vite’s worker-entry
syntax, such as a worker-emitting import or literal new Worker(new URL(...),
...) form. Ensure test-worker.ts is compiled and emitted as JavaScript, and that
window.testWorkerUrl references the emitted worker asset rather than a generic
TypeScript asset.
---
Nitpick comments:
In `@fizarrita/src/codec-worker.ts`:
- Around line 19-37: Move the shared reply-posting and fallback behavior from
the codec worker entrypoints into a new exported dispatchCodecMessage helper in
codec-worker-core, accepting the message and post callback. Update the browser
worker’s message listener and codec-worker-node to call this helper, preserving
the existing transfer handling and fallback error response.
In `@fizarrita/src/internals/codec-worker-core.ts`:
- Around line 120-156: Add bounded cache eviction for the module-level
pipelineByMetaId, metaByMetaId, and pipelineByKey maps, or implement a release
message that removes associated metaId entries and pipelines. Ensure cleanup is
triggered as arrays are discarded so long-lived workers do not retain every
created pipeline indefinitely, while preserving current getPipeline and
getOrCreatePipelineLegacy behavior for active entries.
In `@test/browser/runtime-worker.spec.ts`:
- Around line 46-53: Update the worker task setup around the onMessage listener
to define a shared detach() function that removes both the message and error
listeners. Call detach() before resolving on successful completion and before
rejecting on worker errors, ensuring pooled Worker instances do not retain
listeners between tasks.
- Around line 43-57: Make the pool test type-safe by typing the task slot as
WorkerLike | null and keeping the local worker variable as WorkerLike instead of
using unknown or casting to the browser Worker type. Update the task array and
invoke pool.runTasks<number>(tasks) directly, removing the as never cast while
preserving the existing worker creation and result handling.
In `@test/node/worker-pool.test.js`:
- Around line 162-180: Update the message-waiting logic in the test around
createWorker and the seen listener to resolve the promise directly when the
fourth result is received, rather than polling with setTimeout. Preserve the
existing result collection, ordering assertion, timeout, and worker termination
behavior.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 4293e585-361d-4c86-9823-c200643f1d1f
📒 Files selected for processing (28)
.github/workflows/ci.ymlREADME.mdfizarrita/README.mdfizarrita/package.jsonfizarrita/src/codec-worker-node.tsfizarrita/src/codec-worker.tsfizarrita/src/create-worker.tsfizarrita/src/get-worker.tsfizarrita/src/index.tsfizarrita/src/internals/codec-worker-core.tsfizarrita/src/set-worker.tsfizarrita/src/worker-rpc.tspackage.jsonpnpm-workspace.yamlsrc/index.tssrc/node-worker.tssrc/types.tssrc/worker-pool.tstest/app/main.tstest/app/zarrita/index.tstest/browser/runtime-worker.spec.tstest/node/codec-worker-core.test.jstest/node/echo-worker.mjstest/node/exiting-worker.mjstest/node/fizarrita.test.jstest/node/node-worker-api.test.jstest/node/square-worker.mjstest/node/worker-pool.test.js
CodeRabbit's review of the new files (its earlier run only covered tracked modified files) raised six findings. All were valid. Reject in-flight requests when a live worker is terminated (major). A message already delivered to a running thread is never answered once that thread is killed, and the 'exit' handler stays quiet because the exit was requested — so the request hung. `terminate()` now raises a termination error, and is idempotent. The earlier fixes covered posting *after* terminate and terminate racing thread startup; this is the third case, where the message reached the thread first. The regression test for it initially passed without the fix, because postMessage hands off on a microtask and terminating in the same tick is caught by the queued-message guard instead. It now waits for the message to actually reach the thread; verified failing at the timeout without the fix. Fail explicitly when a decoded chunk holds fewer elements than its edge shape requires. `fixEdgeChunkShapeStride` returned it unchanged, so the reply carried a shape that overstated its data and `set_from_chunk_binary` would read past the end. Bump both packages to 2.0.0. `WorkerLike` is a documented breaking change for TypeScript consumers, and SemVer wants a major for that — a `^1` consumer running `npm update` would otherwise hit a compile error. Emit the test worker as JavaScript via `?worker&url`. The comment claimed that suffix was already in use, but it was not, so Vite treated the TypeScript worker as a generic asset that a production build could not parse. Terminate the worker in `createFailingTask`. The pool only recycles workers returned by resolved tasks and does not terminate the one it lent out, so the failing task leaked it. Document the codec-worker subpaths as worker entry modules. The README showed bare imports, which do not create a worker — the browser entry would bind its handler to the page and the Node entry throws. Raised by CodeRabbit on #11. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
|
CodeRabbit's review completed and covered the new files this time. Six findings, all valid, all fixed in 7d34e97 — threads answered individually and resolved.
Two are worth calling out beyond the table. The terminate hang was a real miss. I had already closed two variants — posting after terminate, and terminate racing thread startup — and assumed that covered it. It did not. If the message reaches a running thread first, killing that thread destroys the reply, and the My regression test for it passed without the fix. On the version bump, I had originally reasoned that type-only widening is conventionally a minor. That convention is real but does not survive the concrete case: a consumer on One deliberate non-fix: the pool permanently loses a slot when a task rejects ( 39 Node + 123 browser tests pass; production bundle still builds clean. |
Why
The worker path was entirely broken outside a browser. Plain Node has no global
Worker, so the moment a pooled task fell back tonew Worker(...)it threw:That made
getWorker/setWorkerunusable in Node, and because nothing in the suite ran outside Chromium, the breakage was invisible. This addsnode:worker_threadssupport behind the existing interface and puts the path under test.What changed
@fideus-labs/worker-pool(1.0.0 → 2.0.0)WorkerLike(src/types.ts) — the slice of theWorkerAPI the pool and its tasks actually use:postMessage,terminate,addEventListener,removeEventListener.WorkerPoolTaskandWorkerPool.workerQueueare now typed against it instead of the DOM global, which is what lets a single task function serve both runtimes. A browserWorkersatisfies it structurally, so the pool is unchanged at runtime. Ships alongsideWorkerMessageEventLike/WorkerErrorEventLike, since browsers deliver aMessageEvent/ErrorEventand Node delivers a raw value/Error.NodeWorker(src/node-worker.ts) — aworker_threadsadapter behind that interface, pluscreateWorker(url)(picks per runtime) andisNodeRuntime().@fideus-labs/fizarrita(1.4.1 → 2.0.0)internals/codec-worker-core.ts— the message protocol and pipeline cache, lifted out ofcodec-worker.ts.codec-worker.tsis now a thin browser entry overself;codec-worker-node.tsis theparentPortequivalent. Both are exposed as subpath exports, as ishandleCodecMessage, so a custom worker can extend the protocol without reimplementing it.create-worker.ts— onecreateDefaultWorker/createCodecWorker, replacing the copy that previously existed in bothget-worker.tsandset-worker.ts.Implementation details worth reviewing
Keeping Node out of browser bundles.
node:worker_threadsis imported through a variable specifier carrying@vite-ignoreandwebpackIgnore, so bundlers never try to resolve it. Verified against a real production build (vite buildon the benchmark): the specifier survives only as an inert string inside the branch guarded bytypeof Worker, and no Node module is pulled in.Keeping bundler worker-detection working. The two branches need opposite treatment, which is why
createDefaultWorkerlooks asymmetric on purpose:Confirmed in the built output:
codec-worker-*.jsis still emitted as a proper worker chunk with its dependency graph.Synchronous constructor over an async import.
NodeWorkercan't get the ctor synchronously, but it must be a drop-in fornew Worker(...). Messages posted before the thread exists queue on the same promise chain, which preserves their order (covered by a test).Five ways a request could hang, closed. These callers are RPC layers waiting on a reply, so a dropped message reads to them as a request that never finishes — silence is worse than an error:
postMessagepostMessageafterterminate()Workerterminate()races thread startup, stranding a queued messageterminate()kills a thread with a request already on itterminate()raises; theexithandler cannot, since that exit was requestedThe last three are adjacent and were closed at different times — the third and fourth during self-review, the fifth from CodeRabbit's finding. Each regression test was verified by removing its fix and confirming the test fails; a test asserting "this does not hang" is worth little until you have watched it hang.
Testing
Node tests run against the built
dist/of both packages — what npm consumers actually get — and cover pool scheduling, transfer lists, worker-path forms (file:URL string vs. filesystem path),workerData, every error/exit/terminate path, andsetWorker/getWorkerround-trips through zstd, blosc, edge chunks, chunk cache,SharedArrayBufferdecode_into, and fill values. The four new browser tests cover the other branch ofcreateWorker, which had no coverage at all. Wired into CI ahead of the Playwright step.Settle-sensitive tests carry explicit timeouts: a regression in this area hangs rather than fails, which would block CI instead of reporting. Verified by patching the terminate-race fix back out — the regression test hung, reproducing the defect exactly.
Breaking change (types only) — hence the major bumps
A task callback annotated
(worker: Worker | null)no longer typechecks understrictFunctionTypesand must sayWorkerLike | null. fizarrita breaks more narrowly:createDefaultWorker()returnsWorkerLikewhere it returnedWorker.Both packages go to 2.0.0. The break is compile-time only, but a consumer on
^1runningnpm updatewould hit it with no opt-in, and there is no shim that avoids it — the break is contravariance inWorkerPoolTask's parameter, so preserving compatibility means keepingWorker, which is what made the pool unusable in Node. Also note thatconst w = worker ?? new Worker(...)infers the unionWorkerLike | Worker, from which TypeScript picks the wrongpostMessageoverload — annotate the local. Both are documented in the README; in-repo callers are updated.Incidental
pnpm installwas exiting 1 before any of this: pnpm 11 no longer readspnpm.onlyBuiltDependenciesfrompackage.json, leaving esbuild unapproved and every pnpm script failing. Moved toallowBuildsinpnpm-workspace.yaml. Not part of the feature, but nothing ran without it.Note on codec availability
Which codecs work in Node is zarrita's business, not ours:
zstd,blosc,lz4, andbyteshave real implementations, whilegzip,zlib, andcrc32cthrow "not enabled by default" and need anumcodecscodec registered inside a custom worker. Documented rather than worked around.🤖 Generated with Claude Code