Repository navigation
Conversation
A require() of a bundled ES module whose result is unused printed wrong or unparsable code when it was an operand. - The conditional and index arms passed the flags of the parent to their operands. With ExprResultIsUnused, the test of a conditional and the target of an index printed as init_x() alone, or as nothing when the module has no wrapper. The operands now get only the flags that apply to them, as in esbuild. - When the module has no wrapper to call, an unused require() printed nothing. The comma operator marks its operands as unused, so --minify-syntax printed `a(), , b()`, and --minify-whitespace printed `if(c)}`. It now prints 0.
|
Status: the fix is complete and ready for review. The branch has main (179664e) merged in. CI (132712): the diff is green. The merge of main
How to reproduce (any directory, Bun 1.1.21 to 1.4.4, and main): The bundle has For the This PR: #42448. The tests are |
|
No actionable comments were generated in the recent review.
|
| Layer / File(s) | Summary |
|---|---|
Preserve unused require expressions src/js_printer/lib.rs, test/bundler/bundler_edgecase.test.ts |
The printer records the output position and emits 0 when an unused internal require() produces no output. Tests cover conditional, member, comma, loop, destructuring, and minified contexts. |
Restrict operand flags src/js_printer/lib.rs, test/bundler/bundler_edgecase.test.ts |
Indexed-expression targets receive only HasNonOptionalChainParent and ForbidCall. Conditional tests receive only ForbidIn. Tests cover wrapped ESM require() results and module initialization side effects. |
Suggested reviewers: jarred-sumner
Priority:
Merge Risk: 
Minimal · up to 6e463
-
No actionable merge-blocking issue is identified; the change is mergeable after normal checks.
Pre-merge checks: 
4
-
Full details: Description check
-
Explanation
The description clearly explains the problem, the implementation, expected behavior changes, limitations, and verification results. It does not use the template headings exactly, but it provides the required information through the Problem, Fix, and Notes sections.
-
Finishing Touches: 💡 1
-
🛠️ Fix failing CI checks: 💡
-
- Commit to this branch
- Create a new PR
-
- 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.
There was a problem hiding this comment.
I reviewed this and didn't find any bugs. The printer is output-critical for every bundle and the EIf/EIndex flag masks change parenthesization for all conditionals and index expressions (not just the require() case), so a maintainer should confirm the mask choice and the open question about always emitting a wrapper.
What was reviewed:
- The
0fallback is gated onExprResultIsUnusedandwritten() == start, so a usedrequire()with nothing to print stays a loud syntax error rather than a silent0; the dynamic-import path printsPromise.resolve()beforestartis compared, so it's unaffected. - The new
EIndexmask is byte-identical to the existingEDotmask atsrc/js_printer/lib.rs:3697;EBinaryalready rebuilds flags from empty, soEIf/EIndexwere the remaining leak sites forExprResultIsUnused. e.nostill receivesForbidInunconditionally after the mask (pre-existing behavior preserved);e.yeswas alreadyExprFlag::none().- Read the inline snapshot:
const { name } = require("./b.js")→0;withnamebound toname2is the linker's namespace-unused rewrite, and therun:stdout assertion confirms it executes correctly.
Extended reasoning...
Overview
The PR fixes bun build emitting syntactically invalid JavaScript when a bundled require() of a wrapper-eliminated ESM module appears as an operand whose result is unused (comma arm, ternary branch, for-init, bare statement). Three changes in src/js_printer/lib.rs: (1) print_require_or_import_expr captures the writer position and prints 0 if nothing was emitted under ExprResultIsUnused; (2) EIndex now masks flags to HasNonOptionalChainParent | ForbidCall before printing its target, matching the existing EDot arm; (3) EIf masks flags to ForbidIn before printing its test, so caller-context flags like ExprResultIsUnused and ForbidCall no longer leak into operands whose values are read. Three itBundled tests are added to test/bundler/bundler_edgecase.test.ts covering the unminified snapshot, a --minify variant, and the wrapper-present case where init_w()'s undefined return was previously used as a conditional test.
Security risks
None. This is code-generation correctness in the bundler's printer; no auth, crypto, network, or filesystem trust boundaries are involved. The change cannot introduce injection — it only affects whether a placeholder token is emitted and which parent flags propagate to child expressions.
Level of scrutiny
Medium-high. The JS printer is on the hot path for every bun build and every runtime transpile, and incorrect output silently breaks user applications. The EIf and EIndex flag masks are not scoped to the require() bug — they change flag propagation for every conditional and index expression, with observable side effects on parenthesization (the PR's own table shows new ((a()) ? c : d) → new (a() ? c : d), etc.). REVIEW.md directs that for ported code "the reference implementation (esbuild) is the spec"; the PR claims esbuild uses the same masks, and the EIndex mask does match the existing EDot arm exactly, but a maintainer should confirm the EIf mask against esbuild's printExpr and weigh the open design question the author raised (always emit the wrapper vs. print a filler 0).
Other factors
The tests are well-placed (existing bundler_edgecase.test.ts, itBundled helper), exercise both run: execution and an inline output snapshot, and cover the variant matrix (minified/unminified, wrapper/no-wrapper, comma/ternary/index/for-init/destructure positions). I traced the 0 fallback's guards: ExprResultIsUnused sets meta.exports_ref = Ref::NONE earlier, wrap_comma_operator and wrap_with_to_esm would each move written() past start before the check, and the dynamic-import branch prints Promise.resolve() first — so the fallback fires only in the exact nothing-printed case. print_space_before_identifier() before 0 handles else0/do0 hazards using the same pattern the printer already uses for number literals. The written() position-compare idiom is already used in this file (e.g., prev_num_end). The added per-call cost is one i32 read on the internal-require path only.
|
Reference for the mask check. These are the same arms in esbuild,
Bun has no |
|
Updated 12:57 PM PT - Oct 25th, 2026
❌ @robobun, your commit 6e463b9 has 1 failures in
🧪 To try this PR locally: bunx bun-pr 42448That installs a local version of the PR into your bun-42448 --bun |
…ed-require-empty-expr
… of a const export Since #42471 a destructured require() local is bound only to an export that has its value from the start. `const { name } = require("./b.js")` of a `const` export no longer folds to an unused require(), so the snapshot of edgecase/EsmWrapperEliminationUnusedRequire now has the pattern itself, and the local keeps its own name.
There was a problem hiding this comment.
I reviewed the merged tree (through 6e463b9) and found no bugs; because this changes bundler output for every unused require() of a wrapper-less ES module and the 0 filler is a design choice the description leaves to a maintainer (versus always emitting an __esm wrapper), a human look is still worthwhile.
What was reviewed:
print_require_or_import_expr: thestartmarker is taken after thewrapparen and0is emitted only whenExprResultIsUnusedis set and nothing was written, so(0),0,,0;,for (0;;)andreturn 0,are all well-formed;Promise.resolve()/__toESM(paths always write bytes first and are unaffected.ExprResultIsUnusedis consumed only in this function and in comma-operand propagation, so the newEIndex/EIfmasks change nothing except require printing; droppingForbidInfrom anEIndextarget atLevel::Postfixis safe since anyinthere is already parenthesized, matching the existingEDotarm and esbuild.- The filler
0can never become a./[target becauseEDot,EIndex,ECalland tagged-template targets never carry the unused flag, so the missingprev_num_endupdate is not reachable. - All three tests execute the bundle (
run.stdout), so the syntax-error and wrong-branch regressions cannot pass on the unfixed printer; the inline snapshot output was read and is consistent with the runtime expectations.
Extended reasoning...
The change touches two files: three small hunks in src/js_printer/lib.rs (a 0 filler for an unused require() that printed nothing, and flag masks on the EIndex target and EIf test) and three new itBundled cases in test/bundler/bundler_edgecase.test.ts. It touches no security-sensitive surface. The code mirrors esbuild's flag handling and the only consumer of the masked flag is the require printer, so the behavior change is narrow and verified by executed bundles. Defer rather than approve because the output of every bundled project with this pattern changes (extra 0; statements, fewer redundant parentheses) and the author explicitly offers the alternative of always creating the wrapper for a maintainer to decide; no CODEOWNERS entry covers these paths and no CHANGES_REQUESTED review is outstanding.
Problem
bun buildprints wrong or unparsable code when arequire()of a bundled ES module is an operand of an expression statement.c ? require("./a") : require("./b");printsc ? __toCommonJS(exports_a) : ;(SyntaxError: Unexpected token ';').require("./a") ? x() : y();always callsy().EIfandEIndexarms (src/js_printer/lib.rs:3803,:3739) pass the printer flagExprResultIsUnusedto their operands.print_require_or_import_expr(lib.rs:2780) prints nothing for a module with noinit_*wrapper.Fix
EIfpasses onlyForbidInto its test.EIndexpasses onlyHasNonOptionalChainParent | ForbidCallto its target. esbuild has the same masks.require()that printed nothing now prints0, which nothing reads:log(1),0,log(2),if(c)0,0;.test/bundler/bundler_edgecase.test.tsfail on main (179664e). Other suites: Notes. Self-reviewed: 10 concerns raised, 9 addressed, 1 rejected (Notes).Background
require()of a wrapped ES module prints(init_x(), __toCommonJS(exports_x)), or onlyinit_x()(undefined) when unused. Bun emits no wrapper when every top-level statement can be hoisted (needs_wrapper_ref,src/js_parser/p.rs:9488, fix(bundler): become smarter with__esmwrappers #12729).__esmwrappers #12729 removed that empty wrapper on purpose.Downsides
require()statement with nothing to print is0;, not;(90 to 91 bytes in the Notes example). Four transpiler forms lose redundant parentheses (Notes).--react-compiler,const m = flag ? require("./a") : require("./b")failed to parse after bundling. It now parses, andmis always moduleauntil react-compiler: do not fold a local that holds a different module on each path #42376 lands.Notes
Merge of main (179664e). The branch was 596 commits behind. The merge has no conflict, and the diff of
src/js_printer/lib.rsis the same. Two lines of the inline snapshot ofedgecase/EsmWrapperEliminationUnusedRequirechanged. They are the output ofconst { name } = require("./b.js"); log.push(name);:0;andlog.push(name2);const { name } = __toCommonJS(exports_b);andlog.push(name);The cause is #42471. It binds a
require()pattern local only to a function declaration or a namespace object. The pattern of aconstexport is a copy again, so it does not fold to an unusedrequire(). The local has the namenamebecause #41286 (1.4.1) lets a nested binding keep its name. No other line of the snapshot changed.The byte count in Downsides. A pattern of a function export is still folded.
b.jsisexport function name() { return "b"; }.entry.jsisexport function f() { const { name } = require("./b.js"); return name(); } console.log(f());. With--target=bun --minify-syntax --minify-whitespace, 1.4.4 printsfunction f(){;return name()}(90 bytes for the file). This PR printsfunction f(){0;return name()}(91 bytes).Cost when the bug is not hit, from the diff. Each printed
require()orimport()of a bundled module reads the output length one time and tests one flag. Each conditional applies one mask. No allocation.History. No user report exists. #42376 found the first form and left it for a separate change. So did #41638, for the mask. The wrong branch (
init_a() ? x() : y()) is in 1.0.0. The unparsable forms start in v1.1.21, the first release with #12729. 1.1.20 printsflag ? (init_st(), __toCommonJS(exports_st)) : init_ot();.Before and after,
bun build --target=bun../aand./bhave no wrapper,./whas one. 1.4.3 prints the same as 1.4.4:flag ? require("./a") : require("./b");flag ? __toCommonJS(exports_a) : ;flag ? __toCommonJS(exports_a) : __toCommonJS(exports_b);require("./a") ? x() : y();? x() : y();__toCommonJS(exports_a) ? x() : y();require("./a")[k];[k];__toCommonJS(exports_a)[k];require("./a"), x();, x();0, x();x(), require("./b");x(), ;x(), 0;require("./a");;0;for (require("./a");;)for (;; )for (0;; )require("./w") ? x() : y();init_w() ? x() : y();(callsy)(init_w(), __toCommonJS(exports_w)) ? x() : y();require("./w")[k];init_w()[k];(TypeError)(init_w(), __toCommonJS(exports_w))[k];With
--minify:function f(c){if(c)}is nowif(c)0,while(c)}is nowwhile(c)0,if(c);else}is nowif(c)0;else 0,return,String(c)is nowreturn 0,String(c), andlog(1),,log(2)is nowlog(1),0,log(2).Why
0also for a whole statement. A first version kept;for a statement that is only therequire(). That is not valid under--minify-whitespace: the printer drops the;before}, soif (c) require("./a")as the last statement printsif(c)}. One rule for every position is smaller and has no such case.The filler applies only when the result is unused. A used
require()that has nothing to print stays a loud syntax error and does not become a silent0. The known case wasvar R = ;for a CommonJS module with no wrapper (#16941). #46021 gave that module a wrapper, and 1.4.4 printsvar b = require_b();.The masks also remove redundant parentheses in plain transpiler output. All forms are valid before and after:
new (a() ? c : d)()new ((a()) ? c : d)new (a() ? c : d)(a?.b ? c : d).e((a?.b) ? c : d).e(a?.b ? c : d).e(a?.b ? c : d)[e]((a?.b) ? c : d)[e](a?.b ? c : d)[e](a.b?.c ? d : e)()((a.b?.c) ? d : e)()(a.b?.c ? d : e)()The no branch of a conditional still gets
ForbidInin every context (a ? b : (c in d)). esbuild passes it only inside aforinitializer. This PR does not change that.Rejected review concern.
return require("./a")with--minify-whitespaceprintedreturn__toCommonJS(exports_a). The cause is different: the arm printed a used result with noprint_space_before_identifier(). This PR left it out. #42681 has since put that call in on main.Related. #27176 fixed the
import()form of cause 2 in the same function (Promise.resolve().then(() => )).With
--react-compilerand without #42376, the compiler foldsconst m = flag ? require("./a") : require("./b")to the first module and leaves the statement from the first table row. On main that is a syntax error. With this PR alone the bundle hasflag ? __toCommonJS(exports_a) : __toCommonJS(exports_b);and reads__toCommonJS(exports_a).nameon both paths.The other fix for cause 2 is to always create the wrapper, as esbuild does (the gate at
src/js_parser/p.rs:9264). Thenrequire()always printsinit_x()and no filler is needed. The cost is an empty__esmwrapper for each such module, which #12729 removed on purpose. This PR does not do that. A maintainer can ask for it.Suites on the merged tree, debug build.
test/bundler/bundler_edgecase.test.ts: 191 pass, 0 fail.bundler_dynamic_import_dce,bundler_minify,bundler_cjs2esm,bundler_cjs: 575 pass, 0 fail.transpiler/{transpiler,react-compiler,runtime-transpiler,function-tostring-require,simplifier-side-effects},transpiler_constant_fold_eqeq,test/regression/issue/24709.test.ts: 398 pass, 0 fail.bundler_bun,bundler_browser,bundler_splitting,bundler_promiseall_deadcode,bundler_loader,bundler_plugin,bundler_naming,bundler_defer,bundler_allow_unresolved,metafile,bundler_regressions,bundler_barrel,bundler_jsx,bundler_string,bundler_comments,bundler_drop,bundler_feature_flag,bundler_merged_enum,bundler_minify_symbol_for,bundler_banner,bundler_footer,bundler_env: 847 pass, 0 fail.test/bundler/esbuild/(13 files): 865 pass, 0 fail in the latest run. An earlier run had 864 pass, 1 fail:default/TopLevelAwaitForbiddenRequireSourceMapCLItimed out. It starts 40bun buildprocesses and has the default 5 s timeout. On the debug build it takes 3.9 s to 5.0 s (4.5 s in the latest run), with and without this PR: a debug build of main also timed out one time in two runs.[human-review] gate passed · iteration 0 · 2 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 1 passed · 0 rejected · iteration 0
evidence per changed file