Repository navigation
Conversation
A bundle has one `require` for all of its files. An assignment to the free `require` in one file changed it for every file, and for the calls that the bundler writes itself: the load of a copied `.node` file, and an `import` of an external package that the linker lowers to a call. A file that assigns the free `require` now declares `var require2 = <the bundle's require>` and reads and writes that variable. The calls that the bundler writes keep the bundle's `require`. This applies to `--target=node` and `--target=bun` in esm and cjs output, and to the dev server. Browser output and iife output do not change.
|
Updated 3:48 AM PT - Oct 24th, 2026
❌ @robobun, your commit 97a35ba has 2 failures in
🧪 To try this PR locally: bunx bun-pr 46640That installs a local version of the PR into your bun-46640 --bun |
|
Status: ready for review. How the bug was reproduced:
CI on 97a35ba (build 131776): 179 of 181 jobs passed, and no bundler test failed. The two failed jobs do not touch this change:
Build 131625, on the commit before the last test-only commit, passed with 181 of 181 jobs. |
|
No actionable comments were generated in the recent review.
|
| Layer / File(s) | Summary |
|---|---|
Assignment detection and per-file binding src/ast/ast_result.rs, src/ast/nodes.rs, src/js_parser/*, src/bundler/ParseTask.rs |
The parser tracks live assignments to free require. When enabled, it creates a per-file binding and records its ownership in the AST. |
Bundler and printer reference selection src/bundler/bundled_ast.rs, src/bundler/LinkerContext.rs, src/bundler/linker_context/generateCodeForFileInChunkJS.rs, src/js_printer/lib.rs |
The bundler carries the ownership flag. Linker and printer code select the file-owned or bundle-level reference for generated calls and properties. Code generation also adjusts entry-point part processing and ESM wrapper hoisting. |
Assignment behavior tests test/bake/dev/bundle.test.ts, test/bundler/bundler_cjs.test.ts, test/bundler/bundler_loader.test.ts |
Tests exercise assigned require behavior across targets, formats, loaders, generated calls, and dev-server updates. |
Suggested reviewers: jarred-sumner
Priority:
Merge Risk: 
Minimal · up to 97a35
-
No actionable merge-blocking risk is established by the reviewed changes.
Pre-merge checks: 
4
-
Full details: Description check
-
Explanation
The description is detailed and covers the problem, fix, scope, limitations, and verification results. It does not use the exact template headings, but it includes the required information, including extensive test evidence.
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands.
Finishing Touches: 💡 1
🛠️ Fix failing CI checks: 💡
-
- Commit to this branch
- Create a new PR
There was a problem hiding this comment.
Beyond the inline findings, I also checked that the needs_wrapper_ref rewrite in src/js_parser/p.rs and the hoisting loop in src/bundler/linker_context/generateCodeForFileInChunkJS.rs stay complementary for non-own-require declarations (same predicate, negated), and that the generated require symbol goes through the linker's renamer so a user binding named require2 in the same file does not collide with it.
Extended reasoning...
The change adds a per-file require variable for files that assign the free require, touching the parser (new flag and part), the linker's hoisting condition, the printer's require spelling, and Ast/BundledAst flags, with no security-sensitive surface. Three inline findings were posted, including a behavior change for cjs entry files that rebind require, so a human look is already signaled; this note only records the two sibling-site checks that were ruled out.
Findings marked 🟡 are optional suggestions and need no follow-up push.
In cjs output the entry point is the output file itself. Its `require` is the one that every file of the bundle reads, and the main script of a Node.js single executable application assigns it there for the whole bundle. The entry point of an output file now prints without its own `require` variable. The same file keeps its variable where it is a dependency in another output file. Use `or_else` for the runtime `require` fallback (clippy `or_fun_call`). Tests: remove the directories of the source and bundle comparison, and keep the files that assign `require` off the entry point where the test is about the variable.
|
A note on the red That status comes from one release-build run of the three changed test files on a test machine. Three new tests went over the 5 second limit that
The machine was slow during that run. The same three tests take 20 to 120 ms in every other run:
|
There was a problem hiding this comment.
Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.
Beyond the inline finding, I checked the new commits against my earlier comments: the cjs entry-point case is now handled in generateCodeForFileInChunkJS.rs (the OWNS_REQUIRE_REF flag is cleared on the local BundledAst view that print_code_for_file_in_chunk_js reads, so the entry prints the ambient require and its own-require part is skipped), and the require_assignment test matrix now disposes its temp directories in afterAll. I also confirmed the AstFlags::OWNS_REQUIRE_REF bit round-trips in both BundledAst conversions and that js_printer::Options::default() initializes the new bundle_require_ref field.
Extended reasoning...
The change spans the parser (new assigns_free_require flag and declare_own_require part), the linker (entry-point special case, wrapper hoisting), and the printer (bundle_require_ref split), with a stated behavior change for esm output; it touches no security-sensitive surface. Two of three concerns from the prior review are addressed in the follow-up commits and the third was a deliberate design choice per the author; the one inline finding this run is a test-coverage nit. The size and the cross-crate semantics make this a change a human bundler owner should still read.
…pped without Node.js The table left the Node.js cases out when the machine has no Node.js, so a run passed with half of the table absent. They are now registered and show as skipped.
There was a problem hiding this comment.
I re-reviewed the latest push and found no new bugs; the points from my earlier passes (cjs entry point keeping the bundle's require, disposal of the matrix temp dirs, Node cases registered as skipped) are addressed in the code. Because this changes what require means inside bundled files across the parser, printer, and linker, a human maintainer should still weigh in on the design before merging.
What was reviewed:
declare_own_requireinitializers per output format and theunreachable!for IIFE —ParseTask.rsnever turnsper_file_requireon for IIFE or browser targets, so it is not reachable from user input.- Part-index handling in
generateCodeForFileInChunkJS.rs: theconstassert pinsOWN_REQUIRE_PART_INDEX == NAMESPACE_EXPORT_PART_INDEX + 1, and theindex < first_other_part_indexguard only skips the dropped part for the cjs entry-point case. - Printer split between
require_refandbundle_require_ref(): loweredimportrecords andimport.meta.mainuse the bundle's ref,require()calls use the file's own;require_ref_for_propertyfalls back to the bundle ref only for dev-server output. needs_wrapper_refand the linker's hoist loop use the samecan_be_moved() || own_require_refpredicate, so the two stay in sync.
Extended reasoning...
The change spans the JS parser (new assigns_free_require flag and declare_own_require synthetic part), the AST/BundledAst flags, the linker (per-file vs bundle require_ref, cjs entry-point exception, wrapper hoisting), the printer (new bundle_require_ref option and two helpers), and about 1,000 lines of new bundler, loader and dev-server tests. It touches no auth, crypto, or input-parsing surface; the reachable unreachable! was checked against the only setter of per_file_require. All three inline findings from prior runs are now addressed in code, and the most recent commit only touches test registration. Deferring rather than approving because the PR intentionally changes observable bundle semantics (a require assignment in one file no longer reaches other files in esm output) and introduces a format-dependent exception for cjs entry points, which is a design call for a bundler maintainer.
|
A note on the "Still fails" line: a literal I built the opposite rule on top of this PR: a literal call after a store calls the stored function, as in Node.js. I do not propose it for merge. The branch is What the branch does
Why it is not a PR
What works today, with no change in Bun
Question for a maintainer After |
|
A note on the "Left as on main" line: with The case // a.js
import { publish, load } from "./writer.cjs";
publish(function (name) { return "published " + name; });
console.log("a:", load("x"));
// b.js
import { load } from "./reader.cjs";
console.log("b:", typeof load);
// writer.cjs
exports.publish = function (fn) { require = fn; };
exports.load = function (name) { return require(name); };
// reader.cjs
exports.load = function (name) { return require(name); };
The page of a server build is the same case, with one entry point. Build a server that imports What I built A fix on a branch. I do not propose it for merge:
Why it is not a PR
What works today, with no change in Bun A module that every entry point imports, with Question for a maintainer For a browser target, does a store into
|
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-10-24. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Problem
bun buildof@node-rs/xxhash1.7.6 exits 0. The bundle throws:Error: Failed to load native binding.require = createRequire(__filename). A bundle has onerequire(src/js_parser/visit/visit_expr.rs:319), so the copied.nodefile loads through the assigned one.Fix
requiredeclaresvar require2 = <the bundle's require>and uses it. Node gives each CommonJS module its ownrequire. Calls that the bundler writes keep the bundle'srequire.test/bundler/bundler_cjs.test.ts,bundler_loader.test.ts,test/bake/dev/bundle.test.ts), 51 fail on main. Alsobundler_edgecase,bundler_splitting,esbuild/default.Background
requireintoERequireCallTarget. The printer spells it fromOptions.require_ref:__requirein esm,requirein cjs.requireparameter on__commonJS(one of five file shapes).Downsides
require = xin the entry point no longer reaches other files..text+7,504 B, one statement per assigning file (+22 to +75 B). Other files: +0 to +16 instructions per parse, +31 per print job, +6 per externalrequire.require("./bundled")after the assignment loads the bundled file (lazy-cache, TypeError: Attempted to assign to readonly property. #11754).Notes
Reproduction without native code
Run
bun build ./app.mjs --target=node --external ext --outdir=o. Copy the bundle andextto a second folder. Move the source folder away. Run the bundle with Node.js.Error: Cannot find module 'ext'Error: Cannot find module 'ext'loader ok | ext of x/deployloader ok | ext of x/deploy@node-rs/xxhash1.7.6,xxh32("made up", 7), node and bun targets, esm and cjs output: main fails in 4 of 4 cells (causeCannot find module './xxhash.linux-x64-gnu-<hash>.node'). This PR prints3318369215in 4 of 4. esbuild 0.21.5 prints the same shared store as main (require = ...in cjs output,__require = ...in esm output).The loader line comes from NAPI-RS (added 2024-10, removed 2025-10). Packages that were published in between carry it.
Output of the assigning file (node, esm)
Rules
requirethat can run, in any write form (=,||=,++, a destructuring target,for (require of ...)). The visit pass setsP::assigns_free_requireat the place where the identifier becomesERequireCallTarget. A store in dead code, in awithbody, or one that adefinereplaced does not count.Features::per_file_require). Not for a browser target: thererequireis a global that scripts share, and abrowserify -rprelude assigns it for the other files. Not in iife output: the__requirehelper for node cannot load in a script (bundler: define __require in iife output #38077).requireis therequirethat every file reads. The main script of a Node.js single executable application assigns it there (require = createRequire(__filename)), and main and esbuild 0.21.5 give that assignment to the whole bundle.generate_code_for_file_in_chunk_jsdrops the variable forchunk.is_entry_point_file(..). The same file keeps its variable where it is a dependency in a second output file.__requirein esm output.typeof require === "undefined" ? undefined : requirein cjs output, because cjs output can run where there is norequire.hmr.require.bind(hmr)in the dev server.__esmwrapper. In an import cycle another file can call a function of this file before its statements run.Options.bundle_require_refis whatrequire_refis for every other file. A loweredimportorexport * from, andimport.meta.main, print it. In dev server output.resolveand.mainkeep the dev server form.require("literal")that the bundler resolved at build time does not go through the variable. NAPI-RS loaders need that. The lazy-cache idiom breaks on it.Also fixed
--splitting: the store went to an imported__requireand threwTypeError: Assignment to constant variable.(Attempted to assign to readonly property.in Bun).--compile,--minify,Bun.build.hmr.require = xreplaced the method that also loads the bundled requires of the same module, and stayed on the module across hot updates.Left as on main
.nodefile (pinned by tests). A NAPI-RS loader that is itself the entry point of a cjs bundle still fails.--target=browser --splittingthe store into an imported__requirestill throws (no test).require("./bundled")after the assignment (todorow). TypeError: Attempted to assign to readonly property. #11754 and Attempting to compile puppeteer-extra-stealth-plugin fails (Attempted to assign to readonly property.) #13036 reported this idiom (clone-deep) for--compile, and Fixes #11754 #14948 answered the error they showed.typeof requireafterrequire = 1folds to"function"(todorow).require.foo = xwithout an assignment lands on the shared function (todorow).eval("require")or awithread in the assigning file reads therequireof the output file (todorows). In cjs output main gave the assigned value there. bundler: declare require inside a CommonJS wrapper whose body contains direct eval #35581 declares a variable namedrequirefor a wrapper with a direct eval.__dirnameand__filenameare one variable per chunk: __dirname handled incorrectly when building #17188, bundler: give each module its own __dirname and __filename binding #39714.var requireagain gets an undefined variable (no test)..nodefiles do not load in the dev server (no test).require = createRequire(__filename)the file's own requires of external packages resolve from the build machine's path, which the bundler inlines on purpose. External platform package: in place 6 of 6, moved to another folder 0 of 6, same as main.__requirehelper comes in), node cjs 63 to 132 B, bun esm 71 to 135 B.Measurements
Release builds. Tools:
llvm-size,llvm-nm,gdb,perf_eventinstructions:u.valgrind,perf,straceandbloatyare not on the machine. The per-call counts are from the last commit. The other numbers are from the first commit against its base (5c6d4e2)..text: +7,424 B for the first commit (82,231,705 to 82,239,129,llvm-size -A). The later commits add 80 B of symbol size (llvm-nm -S:generate_code_for_file_in_chunk_js+112,to_ast+11 and -43).declare_own_requireis 2,059 B in each of 2 monomorphs and#[cold].src/js_parser/visit(one branch on therequirepath).visit_expr_in_out+77 B in each of 2 monomorphs.js_printer::Options216 to 224 B.BundledAst+0 B (flag bit 3 of the existing u16).Ast+0 B.P+0 B.Exprunchanged at 16 B.gdbstepi, callees included, filemodule.exports = 1;, cjs output, 3 runs each):_parse: 34,862 to 34,878 on main, 34,878 with this PR (+0 to +16).print_code_for_file_in_chunk_js: 2,005 to 2,033 (+28).generate_code_for_file_in_chunk_js, which calls it: +31. Its own instructions go from 402 to 405 for the entry point rule, with no cost per part.print_require_or_import_exprfor one externalrequire("node:fs"): 510 to 516 (+6).require): esm -565,649 of 1.0943e9 instructions, cjs -569,051 of 1.0921e9 (A/A floor 2,598 min, 284,464 median).--no-bundle: 200,000 assignments -199,963 of 595.9M (floor 330). 10,000 requires -102 of 102.8M (floor 57).requireover 500,000 printed (whole process), 0 perrequirewith--no-bundle.gdbcounts on the 15 mimalloc entry points, wholebun buildof one file): +0 for a file that does not assignrequire. +8 (esm) and +17 (cjs) for a file that does.sha256sum, 252 builds: 12 entries, esm, cjs and iife, node, bun and browser, plain,--minifyand--splitting). 0 existing bundler snapshots changed.requireleft in 15 of 15.__commonJS(and__toESM(counts unchanged.require, 18 fields against Node.js: 16 of 18 equal (main 14 of 18). Still different: thetypeoffold and the property write above.Tests
test/bundler/bundler_cjs.test.ts: 69 new tests, 44 fail on main. The other 25 pin what must not change: the entry point of a cjs bundle, browser and iife output, import cycles, dead code,define,--banner, awithstore, a direct eval, an unwrapped package. 20todorows record where a bundle still prints something else than its source.The table
requireAssignmentProgramsruns each program from source and from its bundle, with Bun and with Node.js, and compares the output.test/bundler/bundler_loader.test.ts: 4 new tests with a copied.nodefile, 4 fail on main.test/bake/dev/bundle.test.ts: 3 new tests (a server CommonJS file, a client module, a server ES module), 3 fail on main.Other suites on the last commit:
bundler_cjs2esm,bundler_edgecase,bundler_splitting,esbuild/default,esbuild/splitting. Four tests in them exceed a time limit in the debug build on the test machine and do not involverequire:edgecase/DeepImportDiamondDAG(also on main's debug build),default/TopLevelAwaitForbiddenRequireSourceMapCLI, and twosplitting/FoldingNeverMakesABundleWorsegraphs that pass alone.Self-review, not done
require. The cost of the fixed statement is in the list above.require_reffor that file inprint_code_for_file_in_chunk_js.--banner, and an import record flag in place ofwas_unwrapped_require(it has no second reader).Differences from the first design
has_been_assigned_toof therequiresymbol is also set by a store in dead code, in awithbody, and by one that adefinereplaced.require. The first version gave it a variable too, which broke the single-executable idiom in a run with arequirefor built-in modules only.hmr.require.bind(hmr).hmr.importMeta.requirethrowsReferenceError: location is not definedon the server side.Other open PRs at the same code
var requirefor a wrapper with a direct eval): the PR that lands second adds the join described above.__requirein iife output): after it, iife output can get the variable too.require_refexpression inprint_code_for_file_in_chunk_js. The PR that lands second computesbundle_require_reffrom the output format of the file.import.meta.requireas therequireof node, CommonJS and dev-server output #46299 (import.meta.require): its printer arm must printbundle_require_ref().import.meta.mainarm), bundler: give each module its own __dirname and __filename binding #39714 (__dirnameand__filename), bundler: hoistvarfor sloppy-mode implicit global assignment in ESM output #35684 (implicit globals), dev server: load the imports of a CommonJS module from inside its wrapper #46615 (same test files).