Skip to content

node-fallbacks: route the stream polyfill's process shim to require('process') and forward nextTick args - #35484

Closed
robobun wants to merge 3 commits into
mainfrom
farm/00430d0a/node-fallbacks-globalthis-process
Closed

robobun wants to merge 3 commits into
mainfrom
farm/00430d0a/node-fallbacks-globalthis-process

Conversation

@robobun

@robobun robobun commented Jul 24, 2026 •

Copy link
Copy Markdown
Collaborator

Repro

cat > t.js <<'JS'
import { Readable } from "stream";
const r = Readable.from(["a"]);
r.on("data", () => {});
JS
bun build t.js --target browser --outfile out.js
node -e 'delete globalThis.process; import("./out.js")'
# TypeError: Cannot read properties of undefined (reading 'nextTick')

The browser node:stream polyfill is unusable in an environment without a real globalThis.process (i.e. an actual browser).

Cause

readable-stream depends on the process npm package, whose index.js is just module.exports = global.process. build-fallbacks.ts bundles with --define=global:globalThis, so that becomes module.exports = globalThis.process in the output. The post-processing step then does .replaceAll("global.process", "require('process')"), which no longer matches because the define already ran. The embedded stream.js therefore ships module2.exports = globalThis.process as its process shim, and every process.nextTick inside the stream implementation reads undefined.

Once that routed to the node:process polyfill, a second pre-existing bug surfaced: the polyfill's nextTick pushes { fun, args } onto the queue, but drainQueue reads item.array, so every callback was invoked with zero arguments. This broke Readable's resume_(stream, state) the moment the first bug was fixed.

Fix

  • build-fallbacks.ts: also rewrite globalThis.process to require('process'), so the stream (and crypto) polyfills pull in the browser node:process polyfill instead of the host global.
  • process.js: read item.args in drainQueue, matching what nextTick pushes.

Verification

New tests in test/bundler/bundler_browser.test.ts:

  • browser/NodeStreamWithoutGlobalProcess bundles a Readable.from() consumer for --target browser, asserts the output contains no globalThis.process, and runs it after delete globalThis.process. Before this change the bundle throws undefined is not an object (evaluating 'process.nextTick').
  • browser/NodeProcessNextTickForwardsArgs checks that nextTick(cb, a, b, c) forwards its extra arguments. Before this change the callback receives undefined, undefined, undefined and the test prints NaN.
bun bd test test/bundler/bundler_browser.test.ts   # 15 pass, 0 fail

[review] gate passed · iteration 1 · 3 files touched

fails on main (without fix)
ASAN without fix: 2 failed, 2 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/bundler/bundler_browser.test.ts
bun test v1.4.0 (a30ba1d52)

test/bundler/bundler_browser.test.ts:
(pass) bundler > browser/NodeBuffer#21522 [2022.50ms]
(pass) bundler > browser/NodeBuffer#12272 [993.73ms]
(pass) bundler > browser/NodeFS [505.18ms]
127 |       file: "/exec.js",
128 |       stdout: "got:a,b",
129 |     },
130 |     onAfterBundle(api) {
131 |       api.expectFile("out.js").not.toInclude("import ");
132 |       api.expectFile("out.js").not.toInclude("globalThis.process");
                                         ^
error: expect(received).not.toInclude(expected)

Expected to not include: "globalThis.process"
Received: "var __create = Object.create;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nfunction __accessProp(key) {\n  return this[key];\n}\nvar __toESMCache_node;\nvar __toESMCache_esm;\nvar __toESM = (mod, isNodeMo
... (truncated)

release without fix: 2 skipped
bun test v1.4.0-canary.1 (ac9962ca6)

test/bundler/bundler_browser.test.ts:
(pass) bundler > browser/NodeBuffer#21522 [45.05ms]
(pass) bundler > browser/NodeBuffer#12272 [28.22ms]
(pass) bundler > browser/NodeFS [15.14ms]
(pass) bundler > browser/NodeStreamWithoutGlobalProcess [58.29ms]
(pass) bundler > browser/NodeProcessNextTickForwardsArgs [18.55ms]
(pass) bundler > browser/NodeTTY [14.61ms]
(pass) bundler > browser/NodeUrlProtocolTablesIgnorePrototype [18.75ms]
(pass) bundler > browser/NodePolyfills [223.76ms]
(todo) bundler > browser/NodePolyfillExternal
(skip) bundler > browser/BunPolyfill
(pass) bundler > browser/ImportBunError [4.41ms]
(pass) bundler > browser/BunPolyfillExternal [9.40ms]
(pass) bundler > browser/ImportNonExistentNodeBuiltinShouldError [2.59ms]
(pass) bundler > browser/ImportNonExistentWithoutNodePrefix [3.01ms]
(pass) bundler > browser/TargetNodeNonExistentBuiltinShouldBeExternal [4.32ms]
(pass) bundler > browser/AwaitUsingStatement [15.92ms]
(pass) bundler > browser/UsingStatement [15.90ms]

 15 pass
 1 skip
 1 todo
 0 fail
 18 expect() calls
Ran 17 tests across 1 file. [738.00ms]
__F:0:S:2
passes on PR (with fix)
ASAN with fix: 2 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/bundler/bundler_browser.test.ts
bun test v1.4.0 (a30ba1d52)

test/bundler/bundler_browser.test.ts:
(pass) bundler > browser/NodeBuffer#21522 [1461.13ms]
(pass) bundler > browser/NodeBuffer#12272 [731.30ms]
(pass) bundler > browser/NodeFS [405.95ms]
(pass) bundler > browser/NodeStreamWithoutGlobalProcess [2021.72ms]
(pass) bundler > browser/NodeProcessNextTickForwardsArgs [570.84ms]
(pass) bundler > browser/NodeTTY [455.99ms]
(pass) bundler > browser/NodeUrlProtocolTablesIgnorePrototype [838.07ms]
(pass) bundler > browser/NodePolyfills [7899.96ms]
(todo) bundler > browser/NodePolyfillExternal
(skip) bundler > browser/BunPolyfill
(pass) bundler > browser/ImportBunError [124.76ms]
(pass) bundler > browser/BunPolyfillExternal [513.45ms]
(pass) bundler > browser/ImportNonExistentNodeBuiltinShouldError [76.94ms]
(pass) bundler > browser/ImportNonExistentWithoutNodePrefix [74.01ms]
(pass) bundler > browser/TargetNodeNonExistentBuiltinShouldBeExternal [93.80ms]
(pass) bundler > browser/AwaitUsingStatement [395.78ms]
(pass) bundler > brows
... (truncated)

release with fix: 2 skipped
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 894ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/136] cc obj/packages/bun-usockets/src/context.c.o
[2/136] cc obj/packages/bun-usockets/src/eventing/libuv.c.o
[3/136] cc obj/packages/bun-usockets/src/bsd.c.o
[4/136] cc obj/packages/bun-usockets/src/crypto/openssl.c.o
[5/136] cc obj/packages/bun-usockets/src/eventing/epoll_kqueue.c.o
[6/136] cc obj/packages/bun-usockets/src/loop.c.o
[7/136] cc obj/packages/bun-usockets/src/socket.c.o
[8/136] cc obj/src/jsc/bindings/node/http/llhttp/api.c.o
[9/136] cc obj/src/jsc/bindings/node/http/llhttp/http.c.o
[10/136] cc obj/src/jsc/bindings/node/http/llhttp/llhttp.c.o
[11/136] cc obj/src/jsc/bindings/uv-posix-polyfills.c.o
[12/136] cc obj/src/jsc/bindings/uv-posix-stubs.c.o
[13/136] cc obj/packages/bun-usockets/src/fault_inject.c.o
[14/136] cc obj/packages/bun-usockets/src/udp.c.o
[15/136] cc obj/packages/bun-usockets/src/quic.c.o
[16/136] cc obj/vendor/picohttpparser/picohttpparser.c.o
[17/136] gen cpp.rs (cppbind)
[18/136] gen node-fallbacks/*.js
[18/136] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-
... (truncated)
diff hotspot
src/node-fallbacks/build-fallbacks.ts |  7 ++++-
 src/node-fallbacks/process.js         |  2 +-
 test/bundler/bundler_browser.test.ts  | 53 +++++++++++++++++++++++++++++++++++
 3 files changed, 60 insertions(+), 2 deletions(-)

gate history · 2 passed · 0 rejected · iteration 1

evidence per changed file
file                                   reads  edits  tests
src/node-fallbacks/build-fallbacks.ts      2      3      0
src/node-fallbacks/process.js              1      1      0
test/bundler/bundler_browser.test.ts       3      3      0

…process') and forward nextTick args

The browser node:stream polyfill (readable-stream) pulls in the process
npm package's index.js, which is 'module.exports = global.process'. The
build step's --define=global:globalThis rewrites that to
'globalThis.process' before the post-processing .replaceAll runs, so the
'global.process' -> require('process') rewrite never matched. The result
was a stream polyfill whose internal process.nextTick read from
globalThis.process, which is undefined in a browser:

  import { Readable } from 'stream';
  Readable.from(['a']).on('data', () => {});
  // TypeError: Cannot read properties of undefined (reading 'nextTick')

Once that resolved to the process polyfill, a second bug surfaced: the
polyfill's nextTick pushes { fun, args } but drainQueue reads item.array,
so every callback was invoked with no arguments.

Both fixes are in the fallback sources, so the embedded polyfills are
regenerated on build.
@robobun

robobun commented Jul 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

Reproduced with bun build --target browser + delete globalThis.process; both new tests fail on main and pass on this branch.

Self-review flagged the pre-existing .replaceAll("global.process", ...) line as dead (the --define=global:globalThis pass rewrites every global identifier before the post-processing runs), so ac9962c drops it and tightens the comment to describe the one form that actually appears. Full bundler_browser.test.ts suite still green.

@robobun

robobun commented Jul 24, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 6:18 PM PT - Jul 24th, 2026

@robobun, your commit a30ba1d is building: #79918

@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The bundler now rewrites globalThis.process references to the process fallback, and drainQueue() forwards queued callback arguments from item.args. Browser bundler tests cover stream usage and nextTick execution without a global process.

Changes

Browser process fallback fixes

Layer / File(s) Summary
Process fallback rewriting
src/node-fallbacks/build-fallbacks.ts, test/bundler/bundler_browser.test.ts
Generated bundles rewrite globalThis.process to require('process'); browser stream bundling is tested without a global process.
Next-tick argument forwarding
src/node-fallbacks/process.js, test/bundler/bundler_browser.test.ts
Queued callbacks use item.args, with browser coverage verifying forwarded nextTick arguments.

Possibly related PRs

  • oven-sh/bun#34876: Updates related process-reference post-processing in the bundler.

Suggested reviewers: jarred-sumner

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title succinctly captures the main change: routing the process shim to require('process') and fixing nextTick argument forwarding.
Description check ✅ Passed It explains the bug, the fix, and how it was verified, though it uses custom headings instead of the template labels.

Comment @coderabbitai help to get the list of available commands.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — two one-line fixes with a clear root cause and tests that cover each independently.

What was reviewed:

  • build-fallbacks.ts: the new globalThis.process rewrite sits alongside the existing global.process one; checked that no fallback source file contains globalThis.process literally, so process.js won't self-require after the rewrite.
  • process.js: item.array → item.args matches the { fun, args } shape pushed by nextTick.
  • Tests follow the neighboring itBundled pattern, wire error to reject, and the not.toInclude("globalThis.process") assertion guards the regression directly. The existing browser/NodePolyfills snapshot still passing indicates the blanket replace didn't change any other polyfill's exported shape.
Extended reasoning...

Overview

This PR fixes the browser-target node:stream polyfill, which currently crashes in any environment without a real globalThis.process (i.e., an actual browser). Three files touched:

  • src/node-fallbacks/build-fallbacks.ts — adds one more .replaceAll to the post-bundle text-munging step so globalThis.process (the result of --define=global:globalThis running over the process npm package's module.exports = global.process) is rewritten to require('process'), same as the pre-existing global.process rewrite that no longer matched.
  • src/node-fallbacks/process.js — fixes an obvious typo in drainQueue: it read item.array but nextTick pushes { fun, args }. Callbacks scheduled via the polyfill's nextTick were receiving zero arguments.
  • test/bundler/bundler_browser.test.ts — two new itBundled cases: one runs a bundled Readable.from() after delete globalThis.process and asserts the output contains no globalThis.process; the other verifies nextTick(cb, a, b, c) forwards its args.

Security risks

None. This is build-time text post-processing of vendored browser polyfills plus a property-name typo fix in a browser shim. No auth, crypto, filesystem, or untrusted-input parsing is involved.

Level of scrutiny

Low-to-moderate. The replaceAll approach is admittedly brittle (the file itself says so on the line above), but this change extends an existing pattern by one entry rather than introducing a new mechanism. The main risk — that the blanket replace hits an unintended globalThis.processXxx identifier or causes process.js to require itself — was checked: no fallback source contains globalThis.process, and the identical risk already exists for the pre-existing global.process line. The full bundler_browser.test.ts suite (including the large NodePolyfills snapshot that exercises every polyfill's export shape) passes per the PR description, which would catch shape changes in crypto/stream/etc.

Other factors

  • Root cause is well-explained and the fix lands at the layer that owns the bug (the post-processing step whose match went stale, and the queue drain that read the wrong field).
  • Tests await real events (data/end), wire error to reject, and assert exact stdout — no sleeps or vacuous checks.
  • robobun confirmed both tests fail on main and pass on this branch.
  • No prior reviews or outstanding comments.

--define=global:globalThis rewrites every global.process to
globalThis.process before the post-processing runs, so there is nothing
left for the old replaceAll to match. The comment now describes the one
form that actually appears in the bundled text.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — two one-line fixes to the browser node-fallbacks with solid itBundled coverage.

What was reviewed:

  • build-fallbacks.ts: confirmed --define=global:globalThis runs before post-processing, so the old global.process search was dead; checked all global.process occurrences in node_modules/ (process, setimmediate, pbkdf2) — each rewrite to require('process') is semantically correct or improved for the browser target.
  • process.js: nextTick pushes { fun, args }, so item.array was always undefined — straightforward typo fix; verified the source file itself contains no globalThis.process so no self-referential rewrite.
  • Tests wire error to reject, await the resolved event, and assert exact stdout — matches the existing browser/Node* test shape in this file.
Extended reasoning...

Overview

This PR fixes two bugs in Bun's browser-target node polyfills (src/node-fallbacks/):

  1. build-fallbacks.ts: The post-processing step .replaceAll("global.process", "require('process')") never matched because --define=global:globalThis runs first during bundling, turning every global.process into globalThis.process before the string replacement sees it. The fix updates the search string to globalThis.process. This makes the embedded stream.js (and crypto.js via pbkdf2) route their process references to the node:process polyfill instead of relying on globalThis.process existing at runtime.
  2. process.js: drainQueue read item.array, but nextTick pushes { fun, args }. A one-token typo fix (item.array → item.args) so callback arguments are actually forwarded.

Two new itBundled tests in test/bundler/bundler_browser.test.ts cover both fixes end-to-end by bundling for --target browser, deleting globalThis.process in the runner, and asserting exact stdout.

Security risks

None. This is build-time string post-processing of vendored polyfill bundles that ship inside the Bun binary, plus a typo fix in a browser-only process shim. No auth, crypto correctness, filesystem, or untrusted-input parsing is touched.

Level of scrutiny

Low-to-medium. The build-fallbacks.ts post-processing is explicitly labelled "very brittle" in-file, and the change swaps one exact-string search for another that the existing --define pass guarantees is the actual form present. I grepped src/node-fallbacks/node_modules/ for all global.process/globalThis.process occurrences — the collateral rewrites in setimmediate (Node feature-detect stays false) and pbkdf2 (.browser check now correctly true, .nextTick uses the polyfill) are all semantically correct or better than the previous undefined. The process.js fix is a self-evident field-name mismatch between producer and consumer in the same file.

Other factors

  • The PR replaces the dead global.process line rather than adding alongside it, and documents why in a comment — consistent with REVIEW.md's "delete dead code in the same PR".
  • Tests follow the existing browser/Node* shape in the same file: itBundled with runtimeFiles, error handlers wired to reject, exact-stdout assertion, plus a static not.toInclude("globalThis.process") guard on the bundle.
  • Verified process.js itself contains no globalThis.process, so the blanket replaceAll cannot introduce a self-referential require('process') in the process polyfill.
  • No outstanding reviewer comments; CodeRabbit was rate-limited and left no findings.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — two clear browser-polyfill bugfixes with end-to-end tests that fail on main.

What was reviewed:

  • build-fallbacks.ts: confirmed --define=global:globalThis runs before post-processing, so the old global.process replaceAll was dead; the new globalThis.process rewrite is applied post-bundle and resolves to the process polyfill at user-bundle time. Checked that process.js itself contains no globalThis.process, so no self-reference.
  • process.js: nextTick pushes {fun, args}, so item.args is the right read; .apply(null, undefined) was the previous silent zero-arg behavior.
  • Tests wire error to reject, assert exact stdout after delete globalThis.process, and the not.toInclude("globalThis.process") guard catches future regressions in the rewrite.
Extended reasoning...

Overview

Two-line fix in the browser polyfill build pipeline plus two itBundled regression tests. src/node-fallbacks/build-fallbacks.ts swaps a dead .replaceAll("global.process", ...) for .replaceAll("globalThis.process", ...) so the bundled readable-stream (and any other polyfill that transitively pulls in the process npm shim) routes to the node:process polyfill instead of reading globalThis.process at runtime. src/node-fallbacks/process.js fixes drainQueue to read item.args (matching what nextTick pushes) instead of the nonexistent item.array.

Security risks

None. This only affects the build-time text post-processing of browser polyfills embedded in the binary and a queue-item property read in the browser process shim. No auth, crypto, filesystem, or network paths involved.

Level of scrutiny

Low-medium. The replaceAll post-processing is self-described as "very brittle", so the concern is unintended matches — but the old global.process line had identical brittleness and simply never fired because --define=global:globalThis ran first. The new form is what the old code always intended. The blast radius is bounded by the browser/NodePolyfills test, which imports and evaluates every polyfill; that test still passes, and the two new tests exercise the previously-broken path end-to-end (bundle → delete globalThis.process → run) with exact stdout assertions. The item.array → item.args change is a trivially-verifiable typo fix against the queue.push({ fun, args }) two functions down.

Other factors

PR evidence shows both new tests fail on main (debug+ASAN and release) and the full bundler_browser.test.ts suite passes on the branch. Tests follow the existing itBundled conventions in the same file, wire error to reject the awaited promise, and add a not.toInclude("globalThis.process") bundle assertion as a build-time regression guard. No CODEOWNERS on these paths, no outstanding reviewer comments.

@robobun

robobun commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Closing in favor of #41533. It contains this fix and both tests from this PR, unchanged, together with the other browser polyfill fixes. There, the stream polyfill's process shim binds to the node:process polyfill through a --define entry, and nextTick forwards its arguments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant