Repository navigation
Conversation
|
No actionable comments were generated in the recent review.
|
| Layer / File(s) | Summary |
|---|---|
Printer precedence and cache version src/js_printer/lib.rs, src/jsc/RuntimeTranspilerCache.rs |
The printer adjusts exponentiation left-operand precedence and moves main-module expression output into a helper that applies precedence-based wrapping. The transpiler cache version changes to 44. |
Bundler and transpiler regression coverage test/bundler/bundler_edgecase.test.ts, test/bundler/transpiler/transpiler.test.js |
Tests cover main-module expression output across targets and minification settings, plus exponentiation with unary expressions, enum values, and literals. |
CLI main-module runtime coverage test/cli/run/run-importmetamain.test.ts, test/cli/run/run-importmetamain.ts |
The new CLI suite checks main and imported-file behavior in ESM and CommonJS, expression contexts, inspector mode, and transpiler-cache restore. The prior CLI test file is removed. |
Suggested reviewers: jarred-sumner, dylan-conway
Priority:
Severity of issue fixed: Medium
Merge Risk: 
Minimal · up to a8d1f
-
No concrete issue in the changed printing behavior is established. The change is mergeable after normal validation, including the deferred bundler tests.
Pre-merge checks: 
3 · 
1
-
Failed checks: 1 warning Passed checks: 3 passed-
Full details: Description check
-
Explanation
The description is complete and relevant. It explains the problem, the implementation, known limitations, cache impact, and verification results, including the tests added and the cases that still require CI validation.
Full details: Linked Issues check
-
Explanation
Issue
#45776requires correct values forrequire.main === moduleand its negation inside larger expressions.src/js_printer/lib.rsnow wraps the folded comparison atLevel::Equalsand the inverted form atLevel::Prefix.test/cli/run/run-importmetamain.test.tscovers the issue reproduction and entry versus required files. The implementation meets the linked coding requirement.
-
Full details: Out of Scope Changes check
-
Explanation
The folded-node printer and related tests support
#45776. TheBinPowchange insrc/js_printer/lib.rsis a separate general rule for left operands of**. The addedExponentLeftInlinedEnumandExponentLeftUndefinedMinifytests cover enum and undefined-like operands, not the linked issue. These changes are unrelated to#45776.Resolution
Move the
BinPowrule and its exponentiation tests to a separate pull request, or link an active issue that requires this behavior and keep that scope explicitly approved.
-
- 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.
|
Updated 1:09 AM PT - Oct 25th, 2026
✅ @robobun, your commit a8d1f21e104a152be21e3816485ca3a2700a92d7 passed in 🧪 To try this PR locally: bunx bun-pr 33447That installs a local version of the PR into your bun-33447 --bun |
|
Status: rebased onto main 179664e, head a8d1f21. Ready for review. This PR fixes #45776. Reproduced with the script of #45776 on bun 1.4.3-canary (367d939) and on a release build of main 179664e, against node v26.3.0: Fail before, pass after, with debug builds of main and of this head:
Two items for a maintainer:
|
There was a problem hiding this comment.
No bugs found — the precedence-wrap logic and BinPow special case follow the established printer patterns and tests are thorough, but since this changes transpiler output for every module (plus the == → === emission change), it's worth a quick human sanity check.
Extended reasoning...
Overview
This PR fixes a precedence bug in src/js_printer/lib.rs where EImportMetaMain (the folded form of require.main === module / import.meta.main) was printed without consulting the surrounding level, so enclosing operators re-associated around it. The fix adds level.gte(...) wrap checks to both the ESM (!import.meta.main, wrap at Level::Prefix) and non-ESM (require.main === module, wrap at Level::Equals) branches, adds the inverted form to the BinPow left-operand special case (matching the existing EUnary arm), switches emitted ==/!= to ===/!==, bumps the runtime transpiler cache version, and renames a previously-uncollected test file to .test.ts while adding runtime and itBundled coverage.
Security risks
None. This is a JS-printer precedence fix; no auth, crypto, filesystem, or network surface is touched.
Level of scrutiny
Moderate. The change is small (~30 printer lines) and follows the printer's established let wrap = level.gte(...) idiom exactly, and the BinPow addition mirrors the neighboring EUnary/EAwait/ENumber arms. However, the JS printer runs on every transpiled/bundled file, so any regression has wide blast radius. The == → === emission change is argued to be behavior-neutral (both operands are objects or undefined), which looks right, but is a judgment call worth a maintainer confirming. The cache version bump is correct and necessary.
Other factors
- No CODEOWNER covers the touched paths.
- Tests are comprehensive: runtime spawns for CJS entry, required non-main module, ESM inverted form, and the
**SyntaxError case, plus twoitBundledcapture tests for both printer branches. The existingImportMetaMainTargetNode/build-cjs-module#20308snapshots were updated for the===change. - The rename of
run-importmetamain.ts→.test.tsis a good catch (the file was never being collected). - No prior human review comments; CI build was still in progress at review time.
0329c21 to
bd486cc
Compare
Agreed, and to make that check cheap, here is the full argument for the
What it buys: the output now matches the lowering already documented above The precedence wrap itself is the part that has to land: without it Rebased onto |
|
@coderabbitai review |
✅ Action performedReview finished.
|
|
@robobun please check what esbuild does. if they don't have this bug we want the same exact solution has esbuild for preventing the bug |
|
Checked esbuild. Short version: esbuild cannot have this exact bug because it never folds What esbuild doesesbuild leaves the expression as a normal binary AST node and prints it through its precedence-aware printer, so it parenthesizes for free: // esbuild es-in.js --format=cjs --platform=node
const concat = "x=" + (require.main === module) + "!";
const arith = 1 + (require.main === module);The same holds for the two edge cases in this PR. esbuild parenthesizes a unary on the left of // esbuild es4.mjs
export const a = (!x) ** 2;
// esbuild es5.js --minify (input: 'x' + !(a === b) + '!')
const n="x"+(a!==b)+"!";When esbuild itself synthesizes an expression (e.g. lowering // esbuild es3.js --format=cjs --platform=node
const import_meta = {};
const u = "url=" + import_meta.url + "!";So esbuild's rule is: every synthesized/lowered expression is a real AST node, printed recursively with a Why Bun can't just build a real binary node instead
The choice reads So a fixed real-binary AST at parse time isn't possible for the bundler path. The node has to stay a print-time leaf. The fix is esbuild's mechanism applied to that leafGiven the leaf has to render a compound expression, the fix makes it honor the same
That If you would still prefer I avoid the manual wrap entirely, the only way to do that is to push the shape decision into the linker and have it rewrite |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 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 `@test/bundler/bundler_edgecase.test.ts`:
- Line 2101: Remove the leftover debug logging from the test by deleting the
console.log call in the bundler edgecase test; keep the surrounding test logic
intact and rely on the existing assertions instead. Locate it in the test case
that reads "/out.js" via api.readFile, and ensure no other stray debug output
remains in that block.
In `@test/cli/run/run-importmetamain.test.ts`:
- Around line 6-137: The four subprocess-based tests in import.meta.main are
independent and should run concurrently instead of sequentially. Update each
test definition to use test.concurrent (or wrap them in describe.concurrent if
you prefer grouping) so the Bun.spawn/Bun.spawnSync and temp file setup in these
cases can execute in parallel. Keep the existing test bodies and assertions
intact, just change the test registration for the import.meta.main, common.js,
precedence CJS, precedence ESM, and exponent ESM cases.
- Around line 13-20: The spawn-based tests in the run-importmetamain suite only
validate stdout and ignore whether the child process succeeded. Update the
affected test cases that call Bun.spawnSync to also capture and assert the
exitCode is 0, using the Bun.spawnSync result alongside stdout so failures in
index1.js or the related spawned script are not missed. Keep the check close to
the existing Bun.spawnSync assertions in the test body.
- Around line 6-38: The two import.meta.main tests are creating temporary
directories with tmpdirSync() but never disposing them, and the extra
mkdirSync(dir, { recursive: true }) is redundant. Update the test bodies to
match the tempDir/using pattern used by the other cases in
run-importmetamain.test.ts so the directories are automatically cleaned up, and
keep the rest of the test logic unchanged around Bun.write, Bun.spawnSync, and
the assertions.
🪄 Autofix (Beta)
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: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 21458186-7d21-4e10-9adb-b0c3d4258e4e
📒 Files selected for processing (6)
src/ast/e.rssrc/js_printer/lib.rssrc/jsc/RuntimeTranspilerCache.rstest/bundler/bundler_edgecase.test.tstest/cli/run/run-importmetamain.test.tstest/cli/run/run-importmetamain.ts
💤 Files with no reviewable changes (1)
- test/cli/run/run-importmetamain.ts
4174cf9 to
9b51c9e
Compare
There was a problem hiding this comment.
I didn't find any bugs, but deferring for a human sign-off: dylan-conway asked for parity with esbuild's approach and hasn't yet confirmed the answer (that esbuild never synthesizes this node, so the fix applies esbuild's level.gte(...) idiom to the print-time leaf instead). Given this changes transpiler output for every occurrence of require.main === module / import.meta.main (including the == → === emission), a maintainer ack seems warranted.
What was reviewed:
- Wrap thresholds match the
Levelenum:Equalsfor the binary form,Prefixfor!import.meta.main, and theBinPowleft-operand carve-out routes throughLevel::Callso(…) ** 2is legal. - Non-inverted ESM (
import.meta.main, a member expr) correctly needs no wrap; right-of-**cases checked for both branches. - Cache version bump to 24 covers the emission change; the two updated
capturestrings in existing bundler tests were checked. - The renamed
run-importmetamain.test.tspreserves the two pre-existing tests' assertions and adds fail-before/pass-after coverage for CJS entry, required non-main, ESM inverted, and**.
Extended reasoning...
Overview
The PR fixes a printer-precedence bug in src/js_printer/lib.rs: EImportMetaMain (the folded form of require.main === module / import.meta.main) was emitted as raw text without consulting the surrounding level, so enclosing operators re-associated around it. The fix adds let wrap = level.gte(...) guards to both printer branches, adds the inverted form to the BinPow left-operand special case, switches the emitted comparison to strict equality, updates a doc comment in src/ast/e.rs, bumps RuntimeTranspilerCache to v24, and adds bundler + runtime tests (including renaming a previously-uncollected run-importmetamain.ts to .test.ts).
Security risks
None. This is JS printer output correctness; no auth, crypto, filesystem, or untrusted-input parsing surface.
Level of scrutiny
Medium-high. The printer change is small and follows the file's existing let wrap = level.gte(...) idiom used by EAwait/EYield/EUnary/etc., and I verified the thresholds against src/ast/op.rs's Level ordering (Equals=12 for the binary form, Prefix=18 for !import.meta.main, BinPow left carve-out bumps to Call=21). But it changes emitted JS for a very common idiom in every transpiled module, and the == → === change — while argued to be behavior-neutral (both operands are Module|undefined) — is a deliberate output-format decision the author flagged as worth a human check.
Other factors
- Outstanding maintainer question: dylan-conway asked to verify esbuild's approach and use "the same exact solution". The author's reply explains esbuild never folds this into a special node (so it can't hit the bug) and that a "real AST node at link time" alternative exists but is a larger change. That design call — accept the leaf-level wrap vs. rewrite in the linker — hasn't been acknowledged by the maintainer.
- All CodeRabbit and comment-cop threads are resolved; the debug
console.log,tmpdirSync→tempDir, exit-code assertions, anddescribe.concurrentfeedback were addressed. - Tests cover both printer branches (CJS/ESM/target-node), both polarity, the
**syntax-error case, member access, string concat, and the required-non-main path. The bundlercaptureassertions and the newrun:{stdout}case give both textual-output and behavioral coverage. - No prior review from me on this PR.
There was a problem hiding this comment.
I didn't find any bugs, but this changes printer output for every EImportMetaMain occurrence and dylan-conway asked for an esbuild comparison that hasn't been explicitly signed off on — worth a quick human look before merging.
What was reviewed:
- Verified the
Levelthresholds againstsrc/ast/op.rs:Equalsfor the===shape andPrefixfor!import.meta.mainare the correct wrap points; theBinPowleft-operand carve-out is needed becauseExponentiation < Prefix. - Checked that non-inverted
EImportMetaMainon the left of**(both ESM and CJS shapes) is already handled by the existingleft_level/newEqualswrap, so theif left.invertedguard is not a gap. - Confirmed
print_space_before_identifier()after the new(is a no-op (prev char is not an identifier-continue), so no stray space. - The renamed
run-importmetamain.test.tswas previously never collected (no.testsuffix); the two migrated tests preserve the original assertions.
Extended reasoning...
Overview
This PR fixes a precedence bug in js_printer where EImportMetaMain (the folded form of require.main === module / import.meta.main) was printed as raw text without consulting the surrounding level, so enclosing operators re-associated around it. Changes: src/js_printer/lib.rs (three wrap points + ==→===), a doc comment in src/ast/e.rs, a RuntimeTranspilerCache version bump (23→24), three new itBundled cases in bundler_edgecase.test.ts, and a renamed/extended run-importmetamain.test.ts (the old file was never collected by the runner).
Security risks
None. This is printer precedence logic; no untrusted-input parsing, auth, or I/O is touched.
Level of scrutiny
High. The JS printer runs on every transpiled module, and a wrong precedence threshold silently miscompiles user code. I traced the Level enum in src/ast/op.rs to confirm Equals < Add < Exponentiation < Prefix < Call, which validates all three thresholds: the CJS shape wraps at gte(Equals) (so +, typeof, member access all wrap it), the inverted ESM shape wraps at gte(Prefix) (so .toString() and ** wrap it via the new BinPow arm forcing left_level = Call), and the non-inverted ESM shape (import.meta.main, a member expression) correctly needs no wrap. I also checked that print_space_before_identifier() after the new ( doesn't emit a stray space (( is not identifier-continue), and that the BinPow guard if left.inverted doesn't leave a gap for the non-inverted CJS shape (that path already wraps because Exponentiation >= Equals).
Other factors
- dylan-conway asked to check what esbuild does and use "the same exact solution". robobun's response explains esbuild never folds this into a leaf node so can't hit the bug, and that the fix applies esbuild's own
level >= op.Levelidiom to Bun's print-time leaf. That reasoning is sound, but the maintainer hasn't confirmed acceptance of the approach vs. the alternative (rewriting to a real AST node in the linker). - The
==→===emission change is argued to be behavior-preserving (both operands are Module|undefined, never null), and matches the documented lowering inp.rs. I agree, but it does change bundler output byte-for-byte and updates two existingcapture:snapshots. - The cache-version bump invalidates every user's transpiler cache — appropriate here since stale entries would keep serving the miscompiled output.
- Test coverage is thorough: entry vs. required-dep CJS, ESM inverted form, the
**SyntaxError case, and--target=nodewithrun:executing the bundled output. All CodeRabbit threads are resolved.
Given this is a printer change on a critical path with an open maintainer thread on the approach, deferring rather than approving.
7819e49 to
ca4b646
Compare
There was a problem hiding this comment.
LGTM — the stale-comment nit from my earlier pass was addressed in 9640f46.
What was reviewed:
- Verified the
Levelenum ordering:Equals(12) andPrefix(18) are the correct wrap thresholds for the two printed shapes, and theBinPowleft-operand bump toLevel::Callcomposes with both branches. - Confirmed the
if wrap { print("(") }→print_space_before_identifier()ordering matches the existing pattern at lib.rs:3346/3377. - Checked that non-inverted ESM (
import.meta.main, a member expression) is never wrapped, and that non-inverted CJS under**still wraps viaExponentiation >= Equals. - All prior review threads (CodeRabbit ×4, comment-cop, my stale-comment note) are resolved in the current diff.
Extended reasoning...
Overview
This PR fixes a printer-precedence bug where EImportMetaMain (the AST node the parser folds require.main === module / import.meta.main into) was re-emitted without consulting the surrounding precedence level, causing enclosing operators to re-associate around it — e.g. "x=" + (require.main === module) + "!" printed as "x=" + require.main == module + "!". Changes: src/js_printer/lib.rs adds level-aware wrapping to both printer branches and adds inverted EImportMetaMain to the BinPow left-operand special case; src/ast/e.rs updates a doc comment; RuntimeTranspilerCache.rs bumps EXPECTED_VERSION 25→26; three new itBundled capture tests plus a renamed/modernized run-importmetamain.test.ts with three new runtime tests.
Security risks
None. This is a pure printer-output correctness fix with no auth, crypto, permissions, or untrusted-input parsing surface.
Level of scrutiny
Medium — it changes transpiler output, which affects every CJS module using this idiom, but the change is narrow and mechanical: two let wrap = level.gte(...) guards following the exact pattern used at lib.rs:3346/3377/3521, plus one match arm added to an existing special case. I verified against src/ast/op.rs that Level::Equals and Level::Prefix are the correct thresholds for x === y and !x respectively, and traced the BinPow interaction for all four (branch × inverted) combinations. The ==→=== change is behavior-neutral (both operands are objects or undefined) and matches the fold's source form.
Other factors
- The transpiler-cache version bump is required by the file's own convention and follows the established changelog format (comment-cop's flag was a false positive, correctly explained by the author).
- Test coverage is thorough: bundler
capture:assertions for all three printer branches, runtime assertions for main/non-main CJS, ESM inverted, and the**-left-operand SyntaxError case; existingcapture:arrays and theDeleteFoldedImportMetaMainRefcomment were updated for the===output. - All prior review feedback (CodeRabbit's four items in 4174cf9, my stale-comment note in 9640f46) is addressed; no bugs found by the bug-hunting system on this pass.
9640f46 to
586c7c2
Compare
There was a problem hiding this comment.
LGTM — the stale comment I flagged last run is fixed, and the precedence fix itself checks out.
What was reviewed:
Level::Equals/Level::Prefixwrap thresholds against theop::Levelenum ordering; both branches wrap exactly when the emitted expression's own precedence would be captured by the surrounding operator.- The new
BinPowleft-operand arm: without it,left_level = Exponentiation < Prefixso the ESM!import.meta.mainwouldn't wrap and would emit a SyntaxError; with it,Call ≥ Prefixtriggers the wrap. The arm is redundant-but-harmless in the non-ESM path (already wraps at≥ Equals). ==→===: both operands are object-or-undefined in every reachable case, so no observable change; matches the source form the fold came from.- Cache version bump follows the file's changelog convention; test file rename (was never collected without
.test) plus runtime anditBundledcoverage across all three printer branches.
Extended reasoning...
Overview
Fixes a printer-precedence bug where the EImportMetaMain node (the parser's fold of require.main === module / import.meta.main) was emitted without consulting the surrounding level, letting enclosing operators re-associate around it. Touches src/js_printer/lib.rs (the wrap logic + BinPow special case + ===), a one-line doc comment in src/ast/e.rs, the RuntimeTranspilerCache version bump, and tests in bundler_edgecase.test.ts plus a renamed/rewritten run-importmetamain.test.ts.
Security risks
None. This is code-generation output shape only; no untrusted input parsing, auth, or filesystem paths involved.
Level of scrutiny
The printer is production-critical, but this change applies the printer's standard let wrap = level.gte(...) idiom that every other multi-token expression node already uses — it's a targeted mechanical fix, not a redesign. I traced the Level enum ordering (Equals < ... < Exponentiation < Prefix < ... < Call) against each threshold and against the BinPow right-associative left_level = e_level default to confirm the new arm is load-bearing exactly for the ESM inverted case and a no-op elsewhere.
Other factors
All prior review feedback (CodeRabbit's exit-code/tempDir/concurrent nits, my own stale-comment note on DeleteFoldedImportMetaMainRef, the comment-cop false positive) has been addressed and resolved. Test coverage is thorough: runtime tests exercise the CJS entry, a non-main required module, the ESM inverted form, and the ** SyntaxError case; three itBundled capture tests cover the CJS, bun-ESM, and target=node printer branches; and the two pre-existing capture: arrays were updated for == → ===. The dead run-importmetamain.ts (never collected — no .test suffix) is now a real test file.
|
Independent report of the same bug at main 0e395c2, for the record. With The branch now conflicts with main in one place: |
|
A second independent report of this bug, at main 4b5862f. It shows that the guard idiom // guard.js
if (!import.meta.main) console.log("loaded as a library");
else console.log("run as main");
The branch still conflicts with main in |
…vel of its slot
The parser folds `require.main === module` and `import.meta.main` into
one node. The printer wrote it back as `require.main == module` or
`!import.meta.main` and did not read the precedence level of its slot.
An operator around the node then bound into the text:
'x=' + (require.main === module) + '!'
"x=" + require.main == module + "!" (printed)
The arm is now one cold method. It adds parentheses at
`level >= Equals` for the comparison and at `level >= Prefix` for
`!import.meta.main`. The left operand of `**` counts the node as text
that can start with a unary operator. The printed text stays `==`.
Output that was right keeps its bytes, with one exception:
`delete (0, require.main == module)` gets a second pair of parentheses.
The transpiler cache version goes to 44: an older entry can hold the
wrong text.
test/cli/run/run-importmetamain.ts had no `.test` in its name and never
ran. It is now run-importmetamain.test.ts.
require.main === module per its surrounding precedenceimport.meta.main node and the left operand of ** by level
586c7c2 to
9f8c012
Compare
|
@dylan-conway, this is a corrected answer to your question of 2026-07-07, for the new head.
The question: keep the rule, or keep the list? If you prefer the list, I drop commit 2. Commit 1 is complete without it. |
The left operand of `**` must be an UpdateExpression. The printer had a
list of node kinds that print unary text and need parentheses there. A
node that gets its unary text at print time was not in the list, and
the output was a SyntaxError:
enum E { A = -1 } E.A ** 2 -1 /* A */ ** 2
import.meta.hot ** 2 void 0 ** 2 (--minify-syntax)
lib.missing ** 2 void 0 ** 2 (--minify-syntax)
Each arm that prints unary text adds parentheses at `level >= Prefix`.
The slot now has that level, except for `++x` and `x--`, and the list
is gone. Output for the kinds that were in the list does not change.
9f8c012 to
a8d1f21
Compare
There was a problem hiding this comment.
Beyond the inline findings, I also checked two things and found no problem: every printer arm that can emit a leading unary token at print time (print_number, print_undefined, EBoolean under minify, EAwait, EUnary, EInlinedEnum which forwards level) already wraps at level >= Prefix, so handing the left operand of ** Level::Prefix does not produce an unwrapped -x ** y from any other arm; and the two cases from the deleted test/cli/run/run-importmetamain.ts are carried over verbatim as the first two tests of run-importmetamain.test.ts.
Extended reasoning...
The change moves the EImportMetaMain printer arm into a cold method that wraps by level and replaces the ** left-operand kind list with a Level::Prefix rule in src/js_printer/lib.rs, bumps the transpiler cache version, and adds bundler, transpiler and CLI tests; it touches no security-sensitive surface. Three inline findings already signal that a human must look, so this note only records the additional checks that were ruled out.
Findings marked 🟡 are optional suggestions and need no follow-up push.
| if self.options.target == bun_ast::Target::Node { | ||
| // "__require.module" | ||
| if let Some(require) = self.options.require_ref { | ||
| self.print_symbol(require); | ||
| self.print(b".module"); | ||
| } else { | ||
| self.print(b"module"); | ||
| } |
There was a problem hiding this comment.
🔴 Libraries built with bun build --target=node --format=esm that guard typeof import.meta.main === "boolean" now run their main branch when imported from an ES module under Node; on the base branch they took the fallback. The Node form at src/js_printer/lib.rs:2741-2748 prints __require.main == __require.module, which under a Node ESM entry is undefined == undefined, i.e. true even in a required library; the new parens make typeof return "boolean" so the guard no longer hides that. Fix: emit a Node-ESM expression that is false when the file is not the entry (e.g. compare process.argv[1] to fileURLToPath(import.meta.url)), covering the inverted form too, and add the ESM-loaded-from-ESM variant to the Node matrix test. [also at: src/js_printer/lib.rs:2704 - Libraries bundled with --target=node --format=esm that guard import.meta.main behind a typeof check now run their main-only code when an ES module imports them. src/js_printer/lib.rs:2704 parenthesizes the Node ESM text __require.main == __require.module, so typeof (...) === "boolean" becomes true and the guard stops using its fallback.]
Why this was flagged
Source if (typeof import.meta.main === "boolean" ? import.meta.main : fallback()) runCli(); bundled with bun build --target=node --format=esm, then imported by an ES-module entry under Node. src/js_printer/lib.rs:2741-2748 prints __require.main == __require.module, where __require is createRequire(import.meta.url); under an ESM entry __require.main is undefined (no process.mainModule) and __require.module is never set, so the comparison is true in every file. On base the typeof applied to __require.main only (typeof __require.main == __require.module is "undefined" == undefined, false), so the guard failed and the fallback ran. With the new wrap at src/js_printer/lib.rs:2704 the output is typeof (__require.main == __require.module), which is "boolean", so the guard passes and the library sees true and runs its CLI on import. The new Node matrix test at test/bundler/bundler_edgecase.test.ts:2475-2477 loads the ESM output only from a CommonJS loader (loader.cjs), which sets require.main and so does not exercise this path.
Verification: src/js_printer/lib.rs:4480 prints the typeof operand at Level::Prefix.sub(1), and the new print_import_meta_main (src/js_printer/lib.rs:2700-2706) wraps when level.gte(Level::Equals), so the output is now typeof (__require.main == __require.module). After this change the guard reports "boolean" and the consequent evaluates to true even in an imported library.
There was a problem hiding this comment.
This is right. It is the first item under Downsides in the description. The decision that it needs is the merge order with #43687, so I leave this thread open for a maintainer.
Measured with bun 1.4.3-canary (367d939) and node v26.3.0, on a bundle from bun build --target=node --format=esm. "Guarded" is typeof import.meta.main === "boolean" ? import.meta.main : "fallback". "Plain" is import.meta.main ? "main" : "library". For the third column I added the parentheses of this PR to the base output by hand.
| launch | guarded, base | guarded, with the parentheses | plain, base and this PR |
|---|---|---|---|
| entry point | fallback | true | main |
| imported by an ES module | fallback | true | main |
| loaded by a CommonJS file | fallback | false | library |
- On the base the guard passes in no launch. The text is
typeof __require.main == __require.module === "boolean", which isfalse === "boolean". The fallback runs because of the same missing parentheses. - With the parentheses the guard passes, and the expression gets the value that the plain form already has on the base. That value is wrong in one cell:
__require.main == __require.moduleisundefined == undefinedunder an ES module entry point. - That value is the subject of bundler: use the native import.meta.main in ESM output for Node.js #43687. It builds
import.meta.main ?? __require.main == __require.modulefor this output, so I did not copy an expression for it into this PR. Its tests run the output from an ES module importer and expecttypeofto be"boolean"with the valuefalse. On a Node.js without the property, an imported bundle still getstruethere, which bundler: use the native import.meta.main in ESM output for Node.js #43687 lists as a downside. - An ES module importer in the matrix of this PR would pin the wrong value. The comment on
loader.cjsin that test names bundler: use the native import.meta.main in ESM output for Node.js #43687 for this reason.
The description asks to land #43687 first or in the same release. If that order cannot be kept, the alternative is one condition in print_import_meta_main: no parentheses for the Node.js ESM text until #43687 replaces it. That keeps the guard on its fallback. It also keeps the wrong values of that text on the base. One example: if (!import.meta.main) prints as if (!__require.main == __require.module), and a bundle that a CommonJS file loads takes its main branch.
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-10-25. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Fixes #45776
Problem
bun x.cjsprintsfalsefor"main: " + (require.main === module). Node.js printsmain: true.require.main === moduleandimport.meta.maininto one node. Its printer arm (src/js_printer/lib.rs:3328) writesrequire.main == moduleor!import.meta.mainand ignores thelevelof its slot.!import.meta.main ** 2and-1 /* A */ ** 2(an inlined enum) are aSyntaxError: Unexpected token '**'.Fix
level >= Equalsfor the comparison and atlevel >= Prefixfor!import.meta.main.**prints atLevel::Prefix, except++xandx--. Arms that print unary text wrap at that level, so the list of node kinds is gone.run-importmetamain.test.ts,bundler_edgecase.test.tsandtranspiler.test.jsfail on main.Background
levelis the precedence of the operator around a node. An arm that prints a weaker operator adds parentheses.bun x.cjs.void 0,!0) checkslevelin the printer, as commit 1 does. Its**list has the same gaps.Downsides
typeof import.meta.main === "boolean"guard with a fallback now getstrue, until bundler: use the native import.meta.main in ESM output for Node.js #43687.import.meta.main++in CommonJS output ran on main. It is now a SyntaxError at load.Notes
Question for a maintainer. Commit 2 replaces the list of node kinds for the left operand of
**with a rule by level. The list is a port of esbuild's (case js_ast.BinOpPowinjs_printer.go), and esbuild 0.21.5 prints the same SyntaxError for the inputs below. Keep the rule, or keep the list? To keep the list, drop commit 2: commit 1 alone adds this node to the list, and the other kinds stay as on main.What changed against the old head 586c7c2
==/!=. The old head printed===/!==. That fixed nothing and changed each output that has the idiom.wrap. Commit 2 is new.Repro. bun 1.4.3-canary (367d939) and main 179664e. #45776 reports it on 1.4.4-canary. The fold came with #12867.
bun build --format=cjsprintsif (!import.meta.main)asif (!require.main == module). A file that requires the output takes the main branch.bun --inspect entry.cjs: a required file withif (!(require.main === module))takes its main branch. Without the inspector the runtime makes the!a part of the node, and the text is right.bun test --coverageturns that off too (src/runtime/cli/test_command.rs:2002).function f() { const m = require.main === module; return "x=" + m; }printsreturn "x=" + require.main == module;.(require.main !== module).toString()prints!import.meta.main.toString().The left operand of
**. main prints the text below. esbuild 0.21.5 prints the same text for the first and the third input:enum E { A = -1 },E.A ** 2, in one file or across two-1 /* A */ ** 2import.meta.hot ** 2with--minify-syntaxvoid 0 ** 2ns.missing ** 2with--minify-syntaxvoid 0 ** 2EUnary,EAwait,EUndefined,ENumberandEBoolean. These operands are other kinds, and they get their unary text when they are printed.Level::Prefix, the arms that print unary text add their own parentheses:print_undefined,print_number,EBoolean,EAwait,EUnary, and this node.**lines. 1,445 are byte-identical to main. The 67 that differ are theimport.meta.mainrows.(require.main !== module) ** 2: 5 of 5 outputs failnode --checkon main, 0 of 5 here.The esbuild question (the comment of dylan-conway, 2026-07-07).
require.main === module. It keeps the binary node and prints"x=" + (require.main === module) + "!".bun x.cjs. The printer takes the module format fromexports_kind, after the parse (src/bundler/transpiler.rs:2429).leveland writes the parentheses:(void 0)inprintUndefined,(!0)forEBoolean, and a bundledrequire()inprintRequireOrImportExpr(atLNewand atLComma). Commit 1 does the same for this node:==atEquals,!atPrefix.===. This head keeps the==of main.delete).Measurements. Release
bun-profileof main 179664e and of this head, withllvm-nm,llvm-sizeandllvm-objdump.print_expr, five instantiations: 77,088 B to 74,916 B (-283 to -739 B each).print_import_meta_main, five instantiations: +7,634 B..text: +3,840 B. Strippedbun: +4,096 B.**with an identifier on the left: 9 to 4 instructions, 4 to 1 conditional branches. With a unary expression on the left: 16 to 9 instructions, 5 to 2 conditional branches (read in one instantiation).print_import_meta_main(one instantiation): 20, to three targets. 13 go to the grow path of the output buffer, 3 toRenamer::name_for_symbol, 4 to a helper thatllvm-objdumpshows without a name.falsefrom its entry. This build printsx=true.valgrind,perfandstraceare not installed in my container, and its package mirror is not reachable.Output that was right on main.
test/node_modules,scripts/*.ts, the repo files with the idiom) throughBun.Transpilerfor targets bun, browser and node, with and withoutminify.syntax: 205,911 of 205,914 outputs are byte-identical. The 3 that differ were wrong.--minify-syntax, and with--no-bundle --target=bun --format=cjs: 680 of 688 outputs are byte-identical. The 8 that differ were wrong:typeof import.meta.main !== "boolean"inscripts/agent.tsand a!guard intest/js/bun/resolve/main-test-script.js.delete (null ?? import.meta.main)in CommonJS text printsdelete (0, (require.main == module)): 2 bytes more, same value.Grid. 64 contexts (an operator next to the node) x 8 spellings x 26 settings (
bun x.cjs,bun x.mjs,bun buildfor 3 targets x 2 formats x--minify-syntaxon and off x CommonJS and ES module source) x 2 launches (entry point, loaded by another file) = 16,640 cells. The expected value is the same context with the boolean literal. main: 5,349 wrong, 35 of them a SyntaxError in the output. This head: 0. In this grid a CommonJS file loads the node ESM output.Not fixed here.
Node ESM output under an ES module entry point.
__require.main == __require.moduleisundefined == undefinedthere, so an imported bundle says that it is main. bundler: use the native import.meta.main in ESM output for Node.js #43687 changes that value. Measured fortypeof import.meta.main === "boolean" ? import.meta.main : <fallback>:Bun.Transpiler({ target: "node" })printsrequire.main == require.modulefor a CommonJS file.require.moduleisundefined, so that text does not test for the main module. Its parentheses are right now, and bundler: use the native import.meta.main in ESM output for Node.js #43687 changes the text. Under a CommonJS entry point, an unminified!guard there changes from the main branch in each file to the library branch in each file.bun build --no-bundleprintsimport.meta.mainfor a CommonJS input, for each target but--target=bun --format=cjs: Building with --format cjs and --no-bundle ignores cjs format #29187, build: honor --format=cjs with --no-bundle, reject --format=iife #41988.import.meta.mainas the target of++ordelete: js_parser: keep assignment and delete targets as references #45658. In CommonJS textimport.meta.main++wasrequire.main == module++and is(require.main == module)++.delete import.meta.mainwasdelete require.main == module, which deletedrequire.main, and isdelete (require.main == module).iife output (bundler: define __require in iife output #38077, bundler: keep import.meta.main in iife output for bun #38139) and one value per chunk (bundler: print import.meta.main per chunk when a build has several entry points #41235).
Other open PRs.
typeofcell above on a Node.js withimport.meta.main. As code, each order works. The two conflict in the arm body, which this PR moves intoprint_import_meta_main(the two edits of bundler: use the native import.meta.main in ESM output for Node.js #43687 apply there), and in one test comment. With both applied in a local merge, the tests of both pass (9 inrun-importmetamain.test.ts, 31ImportMetaMain,RequireMain,DeleteFoldedandExponentLeftcases inbundler_edgecase.test.ts, all 262 oftranspiler.test.js) and the grid has 0 wrong cells.**): commit 2 covers it.0 / 0andvoid 0where a local binding orwithobject shadowsNaN/undefined#36124, bundler: print import.meta.main per chunk when a build has several entry points #41235 and bundler: define __require in iife output #38077 each add a row to the**list. Those rows are not necessary after commit 2. bundler: define __require in iife output #38077 also has a copy of the parentheses of commit 1.Self-review. 20 concerns. Not taken:
**list and move the rule to its own PR. The rule is a separate commit, and the question above asks for the decision.Tests.
test/cli/run/run-importmetamain.test.tsreplacesrun-importmetamain.ts, which had no.testin its name and never ran. Its two tests are kept. 7 new tests: the repro of transpiler: parenthesized(require.main === module)loses its parentheses inside a larger expression #45776,bun -e, a const with one use,--inspect, 27 operators in CommonJS and in an ES module (entry point and loaded file), and a second run from the transpiler cache.test/bundler/bundler_edgecase.test.ts: 8 new cases. Two pin the text. Four build for Node.js as CommonJS and ESM, plain and minified, and run the output as the entry point and loaded by another file. Two are for commit 2.test/bundler/transpiler/transpiler.test.js: 2 new tests throughBun.Transpiler.edgecase/DeepImportDiamondDAG, a 20,000-module build with a 60 s limit. It fails the same way with a debug build of main in my container.bundler_minify,bundler_cjs2esm,esbuild/ts,esbuild/default,bundler_compile,transpiler-cache. Five tests there pass the 5 s limit by a small margin or not at all in my container, with this build and with a debug build of main:default/TopLevelAwaitForbiddenRequireSourceMapAPIandCLI,compile/BannerNonAsciiUTF8,compile/FooterNonAsciiUTF8, and--drop invalidates cache.no test proof · iteration 10 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/bundler/bundler_edgecase.test.ts