Repository navigation
Conversation
|
Updated 12:05 AM PT - Oct 17th, 2026
❌ @robobun, your commit 255a208 has 1 failures in
The baseline build contains instructions not available on Static scan violations
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughRewrites top-level ChangesTop-level this undefined substitution tests and compiler updates
Possibly related PRs
Suggested reviewers
Pre-merge checks:
|
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/js_parser/p.rs (1)
5616-5623:⚠️ Potential issue | 🟠 Major | ⚡ Quick winHandle
module_type == Esmin this branch too.Line 5616 still keys only on
has_es_module_syntax.prepare_for_visit_pass()separately marks files as ESM whenself.options.module_type == options::ModuleType::Esm, so a.mjs/type: "module"file with no explicitimport/exporttokens will still fall through to the CommonJSexportsrewrite instead of gettingundefined.💡 Suggested fix
- if self.has_es_module_syntax && self.commonjs_named_exports.count() == 0 { + if (self.has_es_module_syntax + || self.options.module_type == options::ModuleType::Esm) + && self.commonjs_named_exports.count() == 0 + { // In an ES6 module, "this" is supposed to be undefined. Instead of // doing this at runtime using "fn.call(undefined)", we do it at // compile time using expression substitution here. return Some(Expr { loc, data: js_ast::ExprData::EUndefined(E::Undefined), }); } else {As per coding guidelines, "Fix the whole bug class in the same PR - grep for every sibling site sharing the pattern."
🤖 Prompt for 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. In `@src/js_parser/p.rs` around lines 5616 - 5623, The branch that substitutes "this" for undefined only checks self.has_es_module_syntax and misses files marked ESM via options; update the condition to also consider self.options.module_type == options::ModuleType::Esm (or an equivalent module_type == Esm flag) so that when has_es_module_syntax OR the module_type is Esm and commonjs_named_exports.count() == 0 you return the EUndefined Expr; search for other sibling sites that check has_es_module_syntax (e.g., other CommonJS rewrites called after prepare_for_visit_pass()) and apply the same module_type check to fix the whole bug class.Source: Coding guidelines
🤖 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/transpiler/runtime-transpiler.test.ts`:
- Around line 236-239: The test captures stderr but never asserts it; update the
subprocess tests that read Promise.all([proc.stdout.text(), proc.stderr.text(),
proc.exited]) to assert stderr before checking exitCode—either add
expect(stderr).toBe("") (or the expected stderr string) immediately after the
stdout assertion or include stderr in the same object assertion (e.g., expect({
file, stdout, stderr }).toEqual({ file, stdout: "undefined true\n", stderr: ""
})), then keep expect(exitCode).toBe(0); apply the same change for the other
occurrence around the variables stdout, stderr, exitCode.
---
Outside diff comments:
In `@src/js_parser/p.rs`:
- Around line 5616-5623: The branch that substitutes "this" for undefined only
checks self.has_es_module_syntax and misses files marked ESM via options; update
the condition to also consider self.options.module_type ==
options::ModuleType::Esm (or an equivalent module_type == Esm flag) so that when
has_es_module_syntax OR the module_type is Esm and
commonjs_named_exports.count() == 0 you return the EUndefined Expr; search for
other sibling sites that check has_es_module_syntax (e.g., other CommonJS
rewrites called after prepare_for_visit_pass()) and apply the same module_type
check to fix the whole bug class.
🪄 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: 2aa73306-b322-4419-9f80-9e0f1ad174c4
📒 Files selected for processing (4)
src/js_parser/p.rstest/bundler/esbuild/default.test.tstest/bundler/transpiler/runtime-transpiler.test.tstest/bundler/transpiler/transpiler.test.js
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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 `@src/js_parser/p.rs`:
- Around line 5616-5621: The strict-mode check in P::prepare_for_visit_pass
should use the same forced-ESM predicate as P::value_for_this: replace the
current branch that only checks
esm_import_keyword/esm_export_keyword/top_level_await_keyword with a predicate
that uses self.has_es_module_syntax || self.options.module_type ==
options::ModuleType::Esm (and still ensure commonjs_named_exports.count() == 0
if that was part of the original module detection), so files forced to ESM (e.g.
.mjs or package.json "type":"module") enable implicit strict mode and match the
behavior of value_for_this; update the branch in prepare_for_visit_pass
accordingly, referencing prepare_for_visit_pass, value_for_this,
has_es_module_syntax, and options::ModuleType::Esm.
In `@src/jsc/RuntimeTranspilerCache.rs`:
- Line 46: Update the runtime-transpiler cache version constant so both modules
agree: change the RUNTIME_TRANSPILER_CACHE_VERSION constant in the bundler cache
to match EXPECTED_VERSION (23) defined in RuntimeTranspilerCache.rs; locate the
RUNTIME_TRANSPILER_CACHE_VERSION symbol in src/bundler/cache.rs and set its
value to 23 to prevent existing cache entries from being treated as stale.
🪄 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: d0e6225c-9432-42eb-b1d3-c5f940a4c837
📒 Files selected for processing (5)
src/js_parser/p.rssrc/js_printer/lib.rssrc/jsc/RuntimeTranspilerCache.rstest/bundler/transpiler/runtime-transpiler.test.tstest/bundler/transpiler/transpiler.test.js
There was a problem hiding this comment.
♻️ Duplicate comments (1)
src/js_parser/p.rs (1)
5616-5620:⚠️ Potential issue | 🟠 Major | ⚡ Quick winKeep forced-ESM detection in sync with implicit strict-mode setup.
Lines 5619-5620 now classify syntax-less
.mjs/"type":"module"files as ESM for top-levelthis, butprepare_for_visit_pass()still only enables implicit strict mode from import/export/top-level-await. That leaves the same file with modulethissemantics and sloppy-mode parsing rules, which is an observable correctness break for forced-ESM files. Please drive both sites from the same forced-ESM predicate/helper.As per coding guidelines, "Rust code: fix the whole bug class in the same PR - grep for every sibling site sharing the pattern."
🤖 Prompt for 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. In `@src/js_parser/p.rs` around lines 5616 - 5620, The code currently treats files as forced-ESM in the TLA/`this` check using the condition (self.has_es_module_syntax || self.options.module_type == options::ModuleType::Esm) && self.commonjs_named_exports.count() == 0 but `prepare_for_visit_pass()` still enables implicit strict mode only when import/export/top-level-await are present, causing mismatched semantics; extract that forced-ESM logic into a single helper (e.g., is_forced_esm(&self) or ModuleType::is_forced_esm) and replace both the top-level `this`/TLA check and the implicit strict-mode decision in `prepare_for_visit_pass()` to call this helper so forced `.mjs`/package-"type":"module" files get both module `this` semantics and implicit strict parsing consistently (ensure to reference and remove the duplicated conditionals: has_es_module_syntax, options.module_type == options::ModuleType::Esm, and commonjs_named_exports.count()).Source: Coding guidelines
🤖 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.
Duplicate comments:
In `@src/js_parser/p.rs`:
- Around line 5616-5620: The code currently treats files as forced-ESM in the
TLA/`this` check using the condition (self.has_es_module_syntax ||
self.options.module_type == options::ModuleType::Esm) &&
self.commonjs_named_exports.count() == 0 but `prepare_for_visit_pass()` still
enables implicit strict mode only when import/export/top-level-await are
present, causing mismatched semantics; extract that forced-ESM logic into a
single helper (e.g., is_forced_esm(&self) or ModuleType::is_forced_esm) and
replace both the top-level `this`/TLA check and the implicit strict-mode
decision in `prepare_for_visit_pass()` to call this helper so forced
`.mjs`/package-"type":"module" files get both module `this` semantics and
implicit strict parsing consistently (ensure to reference and remove the
duplicated conditionals: has_es_module_syntax, options.module_type ==
options::ModuleType::Esm, and commonjs_named_exports.count()).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 49a8f0a4-b2af-4de9-85fc-49152ae63652
📒 Files selected for processing (3)
src/js_parser/p.rssrc/js_printer/lib.rssrc/jsc/RuntimeTranspilerCache.rs
There was a problem hiding this comment.
All my earlier feedback has been addressed and I didn't find anything new, but since this changes transpiler semantics (the module_type == Esm expansion of value_for_this, the printer's delete-operand wrap, and the runtime cache key derivation) it's worth a human maintainer's sign-off.
Extended reasoning...
Overview
This PR fixes #32167 by changing top-level this substitution in ES modules from null to undefined, matching ECMA-262 and Node. It touches five source files in the parser/printer/cache layer plus four test files:
src/js_parser/p.rs—value_for_thisreturnsEUndefinedinstead ofENull, and now also treatsoptions.module_type == Esmas ESM (so.mjs/"type": "module"files with no import/export syntax getundefinedinstead of falling through toexports). The now-unusednull_value_exprhelper is removed (verified no remaining references).src/js_printer/lib.rs—EUndefinedadded to the delete-operand wrap predicate so substituteddelete thisprints asdelete (0, undefined)instead of the strict-mode-invaliddelete undefined.src/jsc/RuntimeTranspilerCache.rs—EXPECTED_VERSIONbumped 22→23 with a changelog line.src/bundler/cache.rs—RUNTIME_TRANSPILER_CACHE_VERSIONmirror synced 20→23.src/js_parser/parse/parse_entry.rs—module_type(which is#[repr(u8)]with stable discriminants) folded into the runtime-transpiler features hash, closing a pre-existing cache-aliasing gap where byte-identical files in ESM vs CJS packages shared a cache entry.
All three of my earlier inline comments (cache version bump, delete undefined printer wrap, module_type in features hash) and CodeRabbit's comments have been addressed and resolved across commits 84e22c4, 9f8b044, 63de048, and 1a6c6fa. The bug-hunting pass on the current revision found no new issues.
Security risks
None identified. No auth, crypto, permissions, or untrusted-input parsing surface is touched. The cache-key change strictly narrows which entries are considered hits, and the version bump invalidates all prior on-disk entries.
Level of scrutiny
This is core transpiler/parser infrastructure — value_for_this runs on every top-level this in every transpiled file, and the features-hash change affects cache keying for every cached module. The primary fix (ENull→EUndefined) is a one-liner that restores the upstream esbuild behavior, but the PR also includes a deliberate behavioral expansion: the || module_type == Esm clause changes what bare .mjs / "type": "module" files (with no import/export syntax) see for top-level this from {} (via the exports substitution) to undefined. That is the spec-correct outcome and is well-tested here, but it is a user-visible semantic change beyond the original bug report.
Other factors
- None of the changed files are CODEOWNER-protected.
- Test coverage is thorough: transform-output unit tests, runtime subprocess tests across import-only/export-only/bare-
.mjs/type:module/CJS, an updated bundler expectation, and a transpiler-cache integration test that exercises the ESM/CJS cache-poisoning scenario in both orders. - The author appropriately scoped out the related implicit-strict-mode question to a separate issue (#32175).
Given the transpiler-semantics scope and the multi-commit evolution across review rounds, I'm deferring to a human maintainer rather than auto-approving.
There was a problem hiding this comment.
All my earlier feedback is addressed and I found nothing new on this revision — deferring only because this is a transpiler-semantics change (widened ESM predicate, printer delete-operand wrap, cache-key shape) that's worth a maintainer glance before merge.
Extended reasoning...
Overview
This PR fixes #32167 by changing the compile-time substitution of top-level this in ES modules from null to undefined (matching ECMA-262 and Node). What started as a one-line ENull → EUndefined swap in value_for_this (src/js_parser/p.rs) grew through review into five source-file changes:
src/js_parser/p.rs— returnEUndefinedinstead ofENull; widen the ESM predicate to includemodule_type == Esm(so syntax-less.mjs/"type": "module"files also getundefined); remove the now-unusednull_value_exprhelper (verified no remaining references).src/js_printer/lib.rs— addEUndefinedtois_identifier_or_numeric_constant_or_property_accesssodelete thisin a module printsdelete (0, undefined)instead of the strict-mode-invaliddelete undefined.src/jsc/RuntimeTranspilerCache.rs— bumpEXPECTED_VERSION22 → 23.src/bundler/cache.rs— sync the mirror constant 20 → 23.src/js_parser/parse/parse_entry.rs— foldmodule_typeinto the runtime-transpiler features hash so byte-identical files in ESM vs CJS package contexts no longer alias one cache entry.
Plus four test files: bundler expectation update, new runtime subprocess tests, new transform-output tests, and a new transpiler-cache integration test.
Security risks
None. No auth, crypto, network, or filesystem-permission surface is touched. The cache-key change only adds a discriminator; it cannot cause stale entries to be accepted that weren't before.
Level of scrutiny
Moderate-to-high. The parser, printer, and runtime transpiler cache are on the hot path for every JS/TS file Bun executes. Each individual change is small and well-reasoned, but together they alter (a) ESM classification for this-substitution purposes, (b) printer output for an edge-case delete operand, and (c) the shape of the on-disk cache key. None of these are mechanical; they're semantic decisions about transpiler behavior. The widened ESM predicate in particular (treating module_type == Esm as ESM even with no import/export syntax) is a deliberate behavior change beyond the original bug report — it's correct per spec, but a maintainer should confirm it doesn't conflict with any intentional Bun-specific interop heuristic.
Other factors
- All three of my earlier inline comments (cache version bump,
delete undefinedwrap,module_typein features hash) were addressed in commits 84e22c4 and 1a6c6fa, with tests covering each. - The bug-hunting system found nothing on the latest revision.
- No CODEOWNERS paths are touched.
- The author appropriately scoped out the related implicit-strict-mode question to a follow-up issue (#32175) rather than expanding this PR further.
- Test coverage is thorough: transform-output assertions, runtime subprocess checks across four ESM-forcing variants plus a CJS negative control, and a cache-aliasing integration test that fails on the pre-fix build.
This is good work and I'd expect it to merge cleanly — I'm deferring purely because parser/cache semantics changes of this scope benefit from a maintainer sign-off rather than bot-only approval.
This comment has been minimized.
This comment has been minimized.
24c6b77 to
4b66440
Compare
There was a problem hiding this comment.
All prior review feedback has been addressed and the change looks correct to me, but since this alters transpiler output semantics for every ES module (and broadens the ESM classification for this-substitution via module_type), it's worth a human sign-off.
Extended reasoning...
Overview
This PR fixes #32167 by changing the compile-time substitution of top-level this in ES modules from null to undefined (per ECMA-262 §16.2.1.6 and matching Node/esbuild). It touches:
src/js_parser/p.rs—value_for_thisreturnsEUndefinedinstead ofENull; the ESM predicate is broadened to includeoptions.module_type == Esm(so.mjs/"type": "module"files without import/export syntax also getundefinedinstead of falling through to the CJSexportssubstitution). The now-unusednull_value_exprhelper is removed.src/js_printer/lib.rs— addsEUndefinedto the delete-operand wrap helper sodelete this→delete (0, undefined)instead of strict-mode-invaliddelete undefined.src/jsc/RuntimeTranspilerCache.rs— bumpsEXPECTED_VERSION22→23.src/bundler/cache.rs— syncs the mirror constant 20→23.src/js_parser/parse/parse_entry.rs— foldsmodule_typeinto the features hash so byte-identical files in ESM vs CJS contexts no longer alias one cache entry.- Tests: transform-output assertions, runtime subprocess tests across import-only/export-only/bare-
.mjs/type:modulefixtures, a CJS negative control, and a transpiler-cache test for the module_type aliasing.
All three issues I raised on earlier revisions (cache version bump, delete undefined strict-mode SyntaxError, module_type missing from the features hash) have been addressed and resolved, as has CodeRabbit's feedback. The bug-hunting pass on the current revision found nothing.
Security risks
None. No auth, crypto, filesystem permissions, or untrusted-input parsing surface is changed. The transpiler-cache changes only add a discriminant byte to an existing hash and bump a version constant.
Level of scrutiny
Moderate-to-high. The diff is small and each piece is well-reasoned, but the JS parser/printer is on the hot path for every module Bun executes, and this is a runtime-observable semantics change. Two aspects in particular warrant a maintainer's eye:
- Broadening the ESM predicate (
|| module_type == Esm) changes what.mjs/"type":"module"files with no import/export syntax see for top-levelthis— fromexports({}) toundefined. That's spec-correct and matches Node, but it's a behavior change for a class of files beyond the original bug report, and it interacts with Bun's intentional CJS-interop leniency for forced-ESM files (the author explicitly scoped out the related strict-mode question into #32175). - Cache-key change — adding
module_typetofeatures_hashis correct, but it's a structural change to how cache entries are keyed.
Other factors
- Test coverage is thorough (transform output, runtime behavior across all four ESM-detection paths, CJS control, delete-operand edge case, cache-aliasing regression test).
- CI is green on the PR's own tests across all lanes; remaining failures are documented as unrelated flakes.
- The
default/ThisUndefinedWarningESMexpectation update aligns with esbuild's original fixture. - No outstanding unresolved review threads.
I'm not approving solely because transpiler-semantics changes are the kind of thing a Bun maintainer should sign off on, not because I see anything wrong.
This comment has been minimized.
This comment has been minimized.
4b66440 to
e13bbdf
Compare
This comment has been minimized.
This comment has been minimized.
e13bbdf to
0e61e64
Compare
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
LGTM — all three earlier concerns are addressed in the current diff: EXPECTED_VERSION is bumped to 30, module_type is folded into the features hash (with a test proving byte-identical ESM/CJS files no longer alias), and the delete this → delete (0, undefined) case is covered by the printer and locked in by a transpiler test.
Checked that null_value_expr has no remaining call sites, that options::ModuleType is #[repr(u8)] so the as u8 hash write is well-defined, and that the runtime test matrix covers both the sync entry-point and async imported-dep transpiler paths plus .cjs-under-"type":"module" staying exports.
Extended reasoning...
Overview
The PR fixes #32167: top-level this in an ES module was being substituted with null instead of undefined, contrary to the ECMAScript spec, Node, and the esbuild code this was ported from. The core change is one line in src/js_parser/p.rs (ENull → EUndefined), plus removal of the now-dead null_value_expr() helper. Supporting changes: EXPECTED_VERSION bumped 29→30 in RuntimeTranspilerCache.rs to invalidate stale on-disk entries, and module_type added to the features hash in parse_entry.rs so byte-identical .js files under "type": "module" vs "type": "commonjs" no longer share a cache entry. Four test files are extended: bundler snapshot updated to match esbuild, transpiler printed-output tests (including constant folding, arrow capture, delete this, and nested-function this left alone), a describe.concurrent runtime matrix over ESM/CJS entry and dep paths, and a transpiler-cache test proving the ESM/CJS cache separation via strict-vs-sloppy observable behavior.
Security risks
None. This is a spec-correctness fix to a compile-time literal substitution in the transpiler. No user input parsing, no auth, no crypto, no filesystem or network surface. The module_type as u8 hash write is safe — options::ModuleType is #[repr(u8)] with three variants.
Level of scrutiny
Moderate. The parser is a critical path, but the semantic change is a one-token substitution that aligns with the spec and the reference implementation (the comment above the changed line already said "undefined"). The remaining changes are the cache-invalidation infrastructure I asked for in earlier review rounds. I verified null_value_expr has no remaining callers repo-wide, the ModuleType enum has a stable #[repr(u8)], and the new test file already imports tempDir/bunExe/bunEnv from harness.
Other factors
All three of my prior inline concerns (cache version bump, delete undefined strict-mode SyntaxError, module_type missing from the cache key) are demonstrably fixed in the current diff — verified from code, not from the author's self-resolution. All coderabbitai threads were resolved by non-authors. Test coverage is thorough and follows the CLAUDE.md/REVIEW.md conventions: describe.concurrent for independent subprocess tests, Promise.all draining stdout/stderr/exited, combined-object assertion before exit code, tempDir from harness, real issue number cited, and the transpiler-cache test reuses that file's existing temp_dir/dummyFile fixture pattern. The PR description transparently documents scope that was tried and backed out (widening module_type == Esm into the branch condition) with a clear reason and a locking test for the current .cjs behavior.
There was a problem hiding this comment.
LGTM — all three concerns from earlier rounds are addressed: EXPECTED_VERSION is bumped to 30, module_type is now folded into the features hash, and the printer already wraps EUndefined for delete (verified at src/js_printer/lib.rs:1544, covered by the new delete (0, undefined) assertion).
Also checked: null_value_expr has no remaining callers, the module_type as u8 cast is sound (options_types::bundle_enums::ModuleType is #[repr(u8)]), and the earlier module_type == Esm widening is indeed dropped from value_for_this — the imports-cjs.js test locks in .cjs-under-"type":"module" keeping this === module.exports.
Extended reasoning...
Overview
The PR swaps a single literal in value_for_this (ENull → EUndefined) so top-level this in ES modules matches Node and the spec, deletes the now-orphaned null_value_expr() helper, bumps the runtime transpiler cache EXPECTED_VERSION from 29 to 30, and adds module_type to the features hash so byte-identical .js files under different package.json "type" settings no longer alias one cache entry. Test coverage spans the Bun.Transpiler printed output (including typeof/equality folding, arrow capture, delete this, and function-body this left alone), runtime spawns for entry-point and imported ESM plus CJS-under-ESM, an updated esbuild bundler snapshot, and a transpiler-cache test proving the ESM/CJS split.
Security risks
None. This is a compile-time expression substitution in the parser and a hash-input addition; no untrusted-input parsing, no auth/crypto/permissions, no I/O surface.
Level of scrutiny
Low-to-moderate. The core change is a one-token literal fix that brings Bun in line with the esbuild reference (js_parser.go emits EUndefined here) and Node. The two knock-on cache concerns — stale on-disk entries and the module_type key gap — were the substantive review risk, and both are handled with the version bump plus the hash addition (backed by a targeted test). Tests are added alongside existing cases in the right files, use tempDir/bunExe/bunEnv, drain pipes concurrently, assert output before exit code, and run under describe.concurrent.
Other factors
This is a follow-up push after my earlier inline comments; every point raised is now visible in the diff. I confirmed null_value_expr has zero remaining references, is_identifier_or_numeric_constant_or_property_access already includes EUndefined on main (so delete this prints delete (0, undefined)), and bundle_enums::ModuleType is #[repr(u8)] so the as u8 hash write is well-defined. The value_for_this condition is unchanged from base (has_es_module_syntax && commonjs_named_exports.count() == 0), so the dropped module_type == Esm widening described in the PR notes is not present — and the imports-cjs.js runtime test guards against a future regression there. No outstanding third-party CHANGES_REQUESTED reviews; the coderabbit threads are non-author-resolved. Exit reason is dry_streak.
This comment has been minimized.
This comment has been minimized.
d798cdd to
95d120b
Compare
this in an ES module
|
Rebased onto main (6c1eb06) as one commit, 95d120b, and reduced to the constant fix. Reproduced on 1.4.3 and on a release build of main: Changes in this revision:
The PR body has the measurements. The change adds 0 instructions and 0 bytes of binary size. Each cached transpiler entry is rewritten once after the upgrade. |
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 findings: the two points I raised on earlier revisions are now in place on this one — EXPECTED_VERSION is bumped (34 -> 35) and the printer's delete operand wrap already covers EUndefined on main, so delete this prints delete (0, undefined). I also checked print_undefined for the extends / computed-key positions under minify (it parenthesizes void 0 at prefix level and above) and the REPL early return (it sits above the ESM gate, so REPL this is unchanged).
Extended reasoning...
The source change is a one-token substitution in value_for_this in src/js_parser/p.rs (ENull to EUndefined for top-level this in a file with ES module syntax), deletion of the now-unused null_value_expr helper, and a transpiler cache version bump in src/jsc/RuntimeTranspilerCache.rs; the rest is tests. It touches no security-sensitive surface. The inline findings (the PR description claims a module_type features-hash change that is not in the diff, and the TS type-only-import gate) are what keep this from an approve; the printer and REPL paths named in the body were read and ruled out.
Additional findings (outside the current diff — GitHub can't attach inline comments there):
-
🟣
src/js_parser/p.rs— Pre-existing: a TypeScript CommonJS file whose only ES syntax is a type-only or type-elided import still runs under the CJS wrapper, but its top-levelthisis printed asundefined(base:null) where Node givesmodule.exports. The gate at src/js_parser/p.rs:6184 useshas_es_module_syntax, which is set fromesm_import_keywordthatimport type {...}never restores (parse_stmt.rs:2323/2338/2348), while exports_kind for the same file is decided as Cjs at parse_entry.rs:2037. Fix: substitute top-levelthisconsistently with the exports_kind the file is finally given (undefined only when it will run as ESM,exportswhen it gets the CJS wrapper), while keeping import-only .js files, which the runtime loads as ESM, at undefined.Why this was flagged
Input: a .ts file such as
import type { Foo } from "./types"; module.exports = { self: this };(or a value import used only in type positions), run withbun file.tsor required from CJS. parse_stmt.rs:2102 recordsesm_import_keywordand the type-only branches at parse_stmt.rs:2323, 2338 and 2348 return S::TypeScript without restoring it. p.rs:3413-3416 then setshas_es_module_syntaxfrom that keyword, so value_for_this at p.rs:6184 takes the ESM branch and the visit pass replacesthiswith EUndefined (p.rs:6190). Yet parse_entry.rs:2037-2043 classifies the same file as ExportsKind::Cjs with WrapMode::BunCommonjs becausemoduleis used, and the import-rejection at parse_entry.rs:2630-2639 skips IS_UNUSED records, so the file loads without error inside the CJS wrapper. The user getsthis === undefined(base branch:this === null), whereas Node/tsc givethis === module.exports; the CJS substitution toexportsat p.rs:6196 never runs.Verification: Pre-existing (base prints
null; this PR printsundefined, neither is Node'smodule.exports). Trigger: a TypeScript file whose only ES syntax is a type-only import and that uses CommonJS, run or required. parse_stmt.rs:2323, 2338 and 2348 never restoreprevious_import_keyword, sovalue_for_this(p.rs:6184-6191) makesthisEUndefined, while parse_entry.rs:2037-2043 decidesexports_kind = Cjs.
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 rest of the diff: the value_for_this ESM arm now matches esbuild's valueForThis, null_value_expr has no remaining callers in src/, and the EXPECTED_VERSION bump covers the changed printed output. One note: the PR description's Scope section says the module_type cache-key hunk and its test were removed, but commit cf2f971 at HEAD adds them (src/js_parser/parse/parse_entry.rs:324-326 and the two "byte-identical files" cases in test/cli/run/transpiler-cache.test.ts) — the description and the code should agree before merge.
Extended reasoning...
The change substitutes EUndefined for top-level this in ES modules in src/js_parser/p.rs, deletes the now-unused null_value_expr helper, hashes module_type into the runtime transpiler cache key in parse_entry.rs, and bumps EXPECTED_VERSION to 35, with tests across transpiler, runtime-transpiler, cache, and esbuild-ported suites. No security-sensitive surface is touched. A confirmed inline finding on the module_type hash (sync and async load paths pass different module_type for .mjs/.cjs files, so one file gets two cache entries) plus the description contradicting the code on that very hunk mean a human should still look.
cf2f971 to
95d120b
Compare
…S module The parser replaces a module-scope `this` at compile time. In a file with ES module syntax it put `null` there. The language says `undefined`. - value_for_this returns E::Undefined for the ES module case and the now unused null_value_expr helper is removed. - The runtime transpiler cache version goes from 34 to 35, because cached entries hold the old printed text.
95d120b to
255a208
Compare
There was a problem hiding this comment.
LGTM — the trimmed-down revision is a one-literal change that matches esbuild's valueForThis, with the cache version bumped and the output change covered end to end.
What was reviewed:
value_for_thisinsrc/js_parser/p.rs: only the ES-module arm changes (ENull->EUndefined); the CJSexportsarm and REPL early-return are untouched, andnull_value_exprhad no remaining callers.delete this->delete (0, undefined): the printer'sis_identifier_or_numeric_constant_or_property_accessinsrc/js_printer/lib.rsalready listsEUndefined, so strict-mode output stays valid (and the transpiler test pins it).EXPECTED_VERSION35 -> 36 insrc/jsc/RuntimeTranspilerCache.rswith the cache-hit replay test on an 8 KiB.mjs; the PR description's "34 to 35" wording is stale relative to the code.- Tests: printed-form matrix (js/ts, minified or not), runtime paths (entry, static/dynamic import,
require, Worker,-e) plus CJS controls, and the two esbuild-port expectations updated rather than new inputs substituted.
Extended reasoning...
The diff is +3/-6 lines in src/ (one ExprData literal in the parser's top-level this substitution and a transpiler-cache format version bump) plus about 170 lines of tests across five test files. It touches no security-sensitive surface: no auth, crypto, input parsing of untrusted data, or memory management. The change is a direct port of esbuild's behavior, the printer already handles the delete undefined edge case, no CODEOWNERS entry covers the changed paths, all third-party review threads were resolved by non-authors, and the scope has shrunk since the last review by dropping the module_type hashing hunk that earlier findings concerned. The bug hunt exited on dry_streak with no findings.
|
CI on the rebased head 255a208 (build 127076): the PR's own tests pass on all lanes. Two red items, neither from this diff:
Mergeable, no open review threads, ready for a maintainer. |
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-10-17. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Fixes #32167
Problem
thisin an ES module isnull. Node and ECMA-262 giveundefined.export {}; console.log(typeof this, this === undefined)printsobject false.value_for_this(src/js_parser/p.rs:6190) replaces a module-scopethisat compile time. Its ES module arm builtE::Null.Fix
E::Undefined. The unusednull_value_expris removed.EXPECTED_VERSION(src/jsc/RuntimeTranspilerCache.rs) goes from 35 to 36. Cached entries hold the old text.valueForThis, the source of this port, returnsundefined.this === eval("this")now holds.transpiler.test.js,runtime-transpiler.test.ts,transpiler-cache.test.ts,esbuild/default.test.ts,esbuild/extra.test.ts. 11 of 11 new or corrected cases fail on main.Background
thisoutside a function or class body:exportsin CommonJS, a literal in an ES module.typeof thisfolds from it.thisto JavaScriptCore at runtime: no extra case fixed, and the bundler still needs the literal.Downsides
nullbreaks:class X extends this {}now throws, as in Node. Output grows 5 bytes per module-scopethis. 0 of 46,398test/node_modulesfiles change.thisisexportsin a.mjsfile with no import/export (Decide a file's module type with one rule on every runtime load path #40940). A binding namedundefinedcaptures the value on 4 of 6 paths (js_printer: print0 / 0andvoid 0where a local binding orwithobject shadowsNaN/undefined#36124).Notes
Scope. This PR now holds only the constant fix, the cache version bump and tests. It is +3/-6 lines in
src/.module_typeinto the transpiler cache features hash. That hunk and its test are removed.thisdoes not readmodule_type, and the two runtime load paths do not pass the samemodule_typefor one file yet. Decide a file's module type with one rule on every runtime load path #40940 makes them agree and carries the hash.E.Undefined(0a18da2, 2021-04-23). ca4120a (2021-05-13, "bug fixes galore") changed it to the sharednullValueExpr. The comment above the line still saysundefined.What changes for users.
import(),require()of an ES module, Worker entry,bun -e,bun testfiles.bun build,Bun.buildandBun.Transpiler:nullbecomesundefined(void 0withminify.syntax),typeof thisfolds to"undefined",this === undefinedfolds totrue,typeof this !== "undefined" ? this : globalThisfolds toglobalThis,delete thisprintsdelete (0, undefined).import,export,import.meta, a top-levelawait, or a TypeScript type-only import or export.Measurements. A is main 6c1eb06, B is this PR. Release builds, linux x64.
thispath: +0 instructions, +0 branches, +0 calls.visit_expr_in_outis 0x451e -> 0x451e bytes (JavaScript copy) and 0x4753 -> 0x4753 bytes (TypeScript copy). Differing instructions: 1 per copy, the tag immediate (mov $0x25,%al->mov $0x26,%al). Tool:nm -Sandobjdump -donbun-profile. valgrind and perf are not installed in the build container.size -A.Bun.Transpileroutput overtest/node_modules(.js, .mjs, .cjs, .ts): 0 of 46,398 files differ, 202,569,024 bytes on both sides. A module with 1,000 module-scopethisnodes grows 5 bytes per node unminified and 2 bytes withminify.syntax.thisprinted as a bareundefinedthat a local binding can capture (export {}; const f = (undefined) => [this]): 4 of 6 paths on this PR (Bun.Transpilerdefault,bun build --no-bundle,bun --inspect,bun test --coverage). Not onbun file.mjsand not onbun build. A user-writtenvoid 0on main: 3 of 6 paths (the same without coverage). On main the samethisisnullon 6 of 6.default/ThisUndefinedWarningESM).bundler_bytecode_portable.test.tspinned hashes changed: 0 of 27. New or corrected cases that fail withUSE_SYSTEM_BUN=1on a release build of main: 11 of 11. The 4 control cases pass on both.Tests.
test/bundler/transpiler/transpiler.test.js: printed forms with the js and ts loaders, with and withoutminify.syntax.test/bundler/transpiler/runtime-transpiler.test.ts: the repro from the issue, and one module reached as entry file, static import,import(),require(), Worker entry and-e. Two controls keepthis === module.exportsfor CommonJS.test/cli/run/transpiler-cache.test.ts: a cached ES module prints the same value on the miss and on the hit. No test can cover the version bump itself. The cache measurement above does.extra/CommonJSSymbol8now runs its bundle. It assertedns.b !== void 0but was never run.default/ThisWithES6Syntaxstays todo. For an import-only file esbuild's expected bundle output is{}and Node givesundefined.Other suites run with the debug build, all pass:
esbuild/ts.test.ts,esbuild/dce.test.ts,esbuild/importstar.test.ts,esbuild/packagejson.test.ts,bundler_cjs.test.ts,bundler_edgecase.test.ts,es-decorators.test.ts,es-decorators-esbuild.test.ts,decorators.test.ts,macro-test.test.ts. A macro call with a module-scopethisargument still transpiles.Failures of the debug build that are the same on main's debug build (5 s timeouts):
default/TopLevelAwaitForbiddenRequireSourceMapCLI,default/TopLevelAwaitForbiddenRequireSourceMapAPI, transpiler-cache--define invalidates cacheand--drop invalidates cache.Not fixed here.
.mjs,.mts, or"type": "module"files with no import/export:thisisexportsand the file runs as CommonJS. The parser needs onemodule_typeon every load path first (Decide a file's module type with one rule on every runtime load path #40940).module_typeis not in the transpiler cache features hash (Decide a file's module type with one rule on every runtime load path #40940).undefinedwhenminify_syntaxis off (src/js_printer/lib.rs,print_undefined). js_printer: print0 / 0andvoid 0where a local binding orwithobject shadowsNaN/undefined#36124 fixes that in the printer.this, notmodule.exports(src/jsc/bindings/JSCommonJSModule.cpp).eval("this")in a CommonJS file differs from Node.exports.x = ...can getundefinedfor onethisandexportsfor a later one in the bundler (js_parser: make the ESM/CJS classification and the module/exports bindings agree #40840 works on that classification).