Generic environment runner for Node.js. Ported from the nitro env runner concept into a standalone package.
Note: Keep
AGENTS.mdupdated with project status and structure.
Note: Keep
README.mdusage section updated when adding/changing public API, CLI flags, or runner behavior.
src/
├── common/
│ ├── base-runner.ts # BaseEnvRunner abstract class
│ ├── worker-utils.ts # AppEntry interface, resolveEntry(), parseServerAddress(), toServerOptions() (+ LISTEN_DATA_KEY), shutdownWorker(), formatInitError()
│ ├── runtime-deps.ts # resolveRuntimeDep()/resolveRuntimeDepSpecifier() — "module | specifier | false" resolver
│ ├── errors.ts # errorWithCause()/closedBeforeReadyError() — `<message>: <cause message>` errors (`waitForReady()` rejections)
│ ├── host-env.ts # hostEnv() — worker/child env: host env + FORCE_COLOR/COLUMNS from the host TTY
│ ├── process-data.ts # receiveProcessData() — runner data over IPC for process workers
│ ├── ws-proxy.ts # createRunnerWSProxyPlugin() — runtime-native WS upgrade proxy
│ └── virtual-modules.ts # registerVirtualModules() — registerHooks()/Bun.plugin wiring for node/bun/deno workers; registerOwnedVirtualModules() for the self runner (host process)
├── plugin/ # host-side `plugins` runner option (see .agents/PLUGINS.md)
│ ├── pipeline.ts # public plugin types + createPluginPipeline() (host: filters, ordering, source maps, `this.resolve()`, `fallback` resolveId phase; async + `sync` drivers) + transformVirtualModules()
│ ├── filter.ts # filter matching shared by host and worker (candidates, serialized filters + expressions, prefilters)
│ ├── glob.ts # host: resolveGlob() + globToRegExp() — `id` globs compiled to RegExps for host and workers
│ ├── hooks.ts # worker: registerPluginHooks() — registerHooks/Bun.plugin resolve + load hooks that send imports/modules to the runner
│ └── channel.ts # sync resolve/load requests: MessagePort (node-worker) / local socket + helper thread (process workers) / direct sync pipeline calls (self)
├── runners/
│ ├── node-worker/ # NodeWorkerEnvRunner + worker (parentPort)
│ ├── node-process/ # NodeProcessEnvRunner + worker (process.send)
│ ├── bun-process/ # BunProcessEnvRunner + worker
│ ├── deno-process/ # DenoProcessEnvRunner + worker
│ ├── self/ # SelfEnvRunner (in-process, no worker; virtual modules + sync plugins via host-process hooks)
│ ├── miniflare/ # MiniflareEnvRunner + wrapper.ts (in-memory workerd wrapper) + wrangler.ts (config → Miniflare options) + exports.ts (declared Worker exports) + exports-runtime.ts (lazy DO/entrypoint/workflow stubs, inlined into the wrapper) + dotenv.ts (minimal-reader dev vars)
│ ├── vercel/ # VercelEnvRunner (extends node-worker) + worker, oidc.ts, queue-dev.ts
│ └── netlify/ # NetlifyEnvRunner (extends node-worker) + worker
├── types.ts # Core interfaces
├── virtual-loader.ts # Virtual module formats/validation/JSON transport + createVirtualHooks() — ESM resolve/load hooks
├── index.ts # Public API exports
├── loader.ts # Dynamic runner loader
├── manager.ts # RunnerManager for hot-reload
├── server.ts # EnvServer (high-level API with watch mode)
└── cli.ts # CLI entry point
Exports: see package.json exports (., ./runners/<name>, ./runners/<name>/worker, ./vite).
Each IPC-based runner defaults to its co-located src/runners/<name>/worker.ts (so entry is optional; data.entry points to the user module). Workers let users write a plain export default { fetch } module and start it with srvx.
export default {
fetch(request: Request): Response | Promise<Response>,
websocket?: Partial<Hooks>, // crossws hooks (recommended)
upgrade?: (ctx: { node: { req, socket, head } }) => void, // raw upgrade (Node-only)
middleware?: [], plugins?: [],
...ServerOptions, // other srvx options are forwarded to serve()
ipc?: { onOpen?({ sendMessage }), onMessage?(message), onClose?() },
resolveExports?: () => Record<string, unknown> | Promise<...>, // miniflare: Worker classes (default: entry namespace)
};toServerOptions()strips env-runner keys and pins/drops listener options (RESERVED_SERVER_OPTIONS,RESERVED_RUNTIME_OPTIONSfor nestednode/bun/deno) since the worker listens on127.0.0.1:0behind the runner proxy, or on the runner'slistenaddress (see Key patterns). Behind the proxy,bun.idleTimeoutdefaults to0(Bun's 10s default closed slow responses, nitrojs/nitro#4874);listenkeeps Bun's default. Server options are read once at start;reloadModule()only swapsfetch.websocketusescrossws/server, which picks the adapter matching the host runtime (so node-worker/node-process use native Bun/Deno adapters when the host is Bun/Deno).ipc.onMessagereceives only user messages (ping/pong/shutdown are filtered);onOpenruns before the ready signal.- Worker flow: (process workers: receive data over IPC) → import entry →
serve()+ready()→ wireupgrade→ipc.onOpen→ post{ address }. Any init failure posts{ event: "init-error", error }(formatInitError(): the message, plus where it was thrown if it doesn't say), logs one[env-runner] worker init failed: ...line and exits 1.
Details in .agents/MINIFLARE.md. In short: the wrapper handles requests like srvx/cloudflare (plugins/middleware/error, request.runtime/ip/waitUntil, internal __ENV_RUNNER_* bindings hidden from env; the crossws option sets crossws Cloudflare bindingName/instanceName under the entry's websocket.options.cloudflare, whose defined values win); wrangler (true | path | inline config) + wranglerConfigPath/wranglerEnv/wranglerEnvFiles load wrangler configs into Miniflare options, with unsupported bindings dropped (warned) and user miniflareOptions winning; Worker classes are exported as lazy stubs that follow reloadModule(): the config's ∪ the entry's (es-module-lexer at startup, then the loaded module after the first load and each reload, restarting Miniflare when the set changes); other classes are Durable Objects unless they extend a built-in (Error, EventTarget, ...): auto-bound in zero-config mode, else unbound namespaces (additionalUnboundDurableObjects, for ctx.exports). exports takes false (no detection) or a module specifier (disk or virtual) re-exported with export * whose bindings come from wrangler/miniflareOptions (its export names are fixed at startup). Supports miniflare v4 and v5: options are built in the v4 format and converted with v5's convertV4MiniflareOptions.
ARCHITECTURE.md— core source-file notes,BaseEnvRunnerlifecycle,RunnerManager/EnvServerNODE-RUNNERS.md— node-worker, node-process, bun-process, deno-process, self (+ orphan tests)MINIFLARE.md— Miniflare internals,MiniflareEnvRunner, wrangler config + testsVERCEL.md—VercelEnvRunner(env vars, headers, OIDC, Queues) + testsNETLIFY.md—NetlifyEnvRunner+ testsVIRTUAL-MODULES.md— virtual modules across Node/Bun/Deno/Miniflare + testsPLUGINS.md— host-sidepluginsrunner option, the sync transform channel, per-runtime load hooks + tests
- Runner tests spawn workers from
dist/(resolved via the self-linkedenv-runnerpackage), so runpnpm buildafter worker-side changes beforepnpm vitest run test/runners.test.tsis the cross-runner suite; bun/deno cases auto-skip when the runtime is missing. Runner-specific test notes live in each runner doc
pnpm build— obuildpnpm dev— Vitest watchpnpm test— lint + typecheck + vitest with coveragepnpm typecheck— tsgopnpm fmt— automd + oxlint fix + oxfmtpnpm lint— oxlint + oxfmt checkpnpm release— test + build + changelog + publish + push
crossws,httpxy,srvx— WebSocket hooks, HTTP/WS proxy, server frameworkcjs-module-lexer/es-module-lexer— devDependencies inlined intodist(miniflare module fallback service)- No peer dependencies.
miniflare,wrangler,@netlify/runtime,@vercel/queueare installed by the app and passed as runner options (miniflare,wranglerModule,netlifyRuntime, queuesdk), resolved viaresolveRuntimeDep(): imported module | specifier (resolved from cwd) |false(opt out) | omitted (optional import). If nothing resolves: miniflare throws; wrangler → minimal JSON/JSONC reader; netlify → shim; queue → warn-once no-op.netlifyRuntimemust be a specifier (imported inside the worker, viaresolveRuntimeDepSpecifier()). These packages must stay listed as external inbuild.config.mjs.
- Message-driven readiness — workers post
{ address }when ready - WebSocket proxying —
RunnerManager.wsSrvxPlugin(): Node host proxies the raw upgrade socket (httpxy); Bun/Deno host terminates with crossws and bridges via aWebSocketclient. Reads the active runner lazily (survives hot-reload) and awaits readiness - Immediate close, graceful
shutdown()—close()terminates the worker/process;shutdown(timeout)first sendsshutdown(worker:server.close(), bounded to half the timeout →ipc.onClose→exit), also onRunnerManager/EnvServer - Drained reload —
RunnerManager.reload(runner, { drain })(EnvServer:drainoption) counts each runner's requests (until the response body settles) and WebSockets, and shuts the previous runner down once they settle instead of closing it at the swap (closes it aftertimeout, default 60s). SeeARCHITECTURE.md - Public listener — the
listenrunner option (node-worker, node-process, bun-process, deno-process) makes the worker's srvx server bind the public address (no proxy hop); sent asdata[LISTEN_DATA_KEY], the reportedaddressis loopback for wildcards and hasprotocol: "https"with TLS.selfserves it from the host process (serve(toServerOptions(entry, listen))); miniflare closes with an error. SeeNODE-RUNNERS.md - Orphan protection — node-process/bun-process/deno-process workers call
process.on("disconnect", () => process.exit(0))before the data handshake and entry import - Data passing —
workerData(threads), IPC handshake (processes: worker listens, sendsrequest-init-data, host replies{ event: "init-data", data: "<JSON>" }; env vars are size-limited, seeNODE-RUNNERS.md), direct in-process import (self), in-memoryscript+unsafeModuleFallbackService(miniflare) - Host-side plugins — the
pluginsrunner option (not part ofdata) stays on the host (resolveId,load,transformhooks). Worker resolve/load hooks send matching imports and modules over a dedicated sync channel (Atomics.wait+receiveMessageOnPort, since the runner IPC listener can't run while the loader blocks); virtual modules are transformed on the host before they are sent.resolveIdhooks withfallback: trueonly get imports the runtime failed to resolve; handlers getthis.resolve(). The self runner registers the same hooks in the host and runs the pipeline's sync driver in them (synchronous handlers only, except for virtual modules). SeePLUGINS.md - Virtual module updates —
updateVirtualModules()sets/removes (null) keys in oneupdate-virtual-modulesround trip (miniflare: host-side);invalidateModule()is the same update with the current source. The host keeps its own map in sync, seeVIRTUAL-MODULES.md - Terminal capabilities — spawned workers get piped stdout, so
hostEnv()forwardsFORCE_COLOR/COLUMNSfrom the host TTY - Stdio forwarding — all runners forward entry stdout/stderr to the host
- Socket cleanup —
_closeSocket()skips Windows named pipes and abstract sockets - Adding a new runner —
src/runners/<name>/runner.tsextendingBaseEnvRunner(+ optionalworker.ts), addpackage.jsonexport, add toloadersinsrc/loader.ts, re-export fromsrc/index.ts