Repository navigation
Report parser errors on the async module transpile path - #40568
Conversation
The parser logs "Cannot use import statement with CommonJS-only features"
after it has already produced an AST. The sync path (require, the entry
point) checks the log after the parse and throws the BuildMessage. The
async path behind import and import() did not, so the printed output,
an import statement inside the CommonJS wrapper, went to JSC, which
rejected it with "Unexpected token '{'. import call expects one or two
arguments."
Check the log after the parse in RuntimeTranspilerStore as well, so both
paths report the same error with its notes.
|
Warning Review limit reached
On-demand reviews are free for the next 25 days. After that, they cost $0.25 per reviewed file. Or wait 12 minutes for your next included review. View limit detailsLimit details: You’ve used all 5 included reviews currently available. Review configuration: ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (1)
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (3)
Included review availability: Your plan provides up to 5 included reviews per hour; 1 remains after this review. WalkthroughThe runtime transpiler now stops when parsing logs errors, even when an AST exists. Tests cover consistent errors for mixed modules, dynamic imports, ChangesParser error propagation
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Full details: Description checkExplanation The description explains the problem, cause, fix, affected behavior, tests, and verification results. It does not use the template headings exactly, but it provides the required information and is mostly complete. Comment |
|
Status: fix pushed, waiting for CI. Reproduced with the reduced #20718 repro ( The same check also covers Tests: |
There was a problem hiding this comment.
LGTM — the async path now mirrors the sync path's log.errors > 0 check, and the scopeguard already carries the log back to self.log for process_fetch_log.
What was reviewed:
- Confirmed the new check in
TranspilerJob::runsits after watcher registration and matchestranspile_source_code_innerat src/runtime/jsc_hooks.rs:2761; the_log_clone_guardcopies the errored log intoself.logon early return sorun_from_js_threadbuilds theBuildMessagerejection. - Checked that no cleanup is skipped by the new early return — fd close, macro-context free, and log clone are all scopeguard-armed above it.
- Tests follow harness conventions (tempDir, concurrent Promise.all drain, output asserted before exitCode) and assert the exact
[name, message]pair for bothimport()andrequire(), which fails on the unfixed build.
Extended reasoning...
Overview
The PR adds a single 4-line guard (plus comment) to TranspilerJob::run in src/jsc/RuntimeTranspilerStore.rs: after a successful parse, if the transpiler's log has errors, set parse_error = Some(ParseError) and return early instead of printing the AST and handing it to JSC. This mirrors the identical check in the sync path at src/runtime/jsc_hooks.rs:2761. Two new tests in test/js/bun/resolve/build-error.test.ts spawn a fixture that mixes import with module.exports and assert that import() now rejects with the parser's BuildMessage (matching what require() already produced) and that the unhandled case prints the parser's error and help notes to stderr with exit code 1.
Security risks
None. This is an error-reporting path change in the module transpiler — no auth, crypto, network, or untrusted-input parsing is touched. The change makes error handling stricter (rejecting a module that previously slipped through with a confusing JSC SyntaxError), which is fail-closed relative to the prior behavior.
Level of scrutiny
Low-to-moderate. The Rust change is mechanical: it copies an existing, well-established check from the sync transpile path to its async twin, exactly the "fix the whole class — sync/async twins" pattern REVIEW.md calls for. I verified the surrounding resource management: the fd-close guard (should_close_input_file_fd), the _macro_ctx_guard, and the _log_clone_guard are all armed via scopeguard before this new early return, so nothing leaks and the errored log is correctly cloned into self.log for run_from_js_thread → process_fetch_log to build the rejection. The check is placed after watcher registration, matching the sync path's ordering.
Other factors
The tests are well-formed per test/CLAUDE.md: tempDir + bunExe/bunEnv, await using on spawn, test.concurrent for independent subprocesses, Promise.all to drain pipes, and output asserted before exit code. The first test asserts an exact { import, require } object with .toEqual, so it fails on the unfixed build (where import() yields SyntaxError, not BuildMessage). The second test asserts the specific error and both note: lines in stderr and exitCode === 1. No CODEOWNERS cover the touched paths. No prior review objections exist on the timeline. The bug hunt exited on dry_streak with no findings.
"Multiple exports with the same name" is logged from the import scanner after the AST exists, so it is one of the errors the async path now reports. The through export merge tests expected JSC's "Cannot export a duplicate name" when the file was imported and Bun's error when it was run directly. Both paths report Bun's error now.
There was a problem hiding this comment.
LGTM — the follow-up commits addressed the earlier feedback (type-export.test.ts expectation updated, comment trimmed to one line).
What was reviewed:
- The new
log().errors > 0check mirrors the parse-failure branch 30 lines above (sameparse_errorvalue, same early return); placed after watcher registration so the fd is still adopted, and theshould_close_input_file_fdguard covers the new return. - New tests use
tempDir/bunExe/bunEnv/await using, drain both pipes concurrently, assert output before exit code, and cover bothimport()and a subsequentrequire()of the same file. type-export.test.tsnow expects Bun's parser error on both the entry-point and imported-file paths, which is the intended behavior change.
Extended reasoning...
Overview
The PR adds a 4-line guard in TranspilerJob::run (src/jsc/RuntimeTranspilerStore.rs) so the async transpile path bails with parse_error = ParseError when the parser logged errors but still returned an AST — mirroring what the sync path in transpile_source_code_inner already does. Two new concurrent tests in test/js/bun/resolve/build-error.test.ts verify import() of a mixed ESM/CJS file rejects with the parser's BuildMessage (and that a subsequent require() of the same file also gets the parser error, guarding the "failed async load poisons the module registry" case described in the PR). test/js/bun/typescript/type-export.test.ts is updated to expect Bun's duplicate-export error on both the entry-point and imported-file paths.
Security risks
None. This is error-reporting plumbing on the module transpile path; no new input parsing, no privilege boundary, no allocation or resource acquisition added.
Level of scrutiny
Low-to-moderate. The Rust change is a direct copy of the pattern at line 902 in the same function (the None arm of the parse call), placed after the watcher-registration block so behavior for --watch is unchanged. The early return is safe: should_close_input_file_fd is a scope guard that fires on drop, and parse_result owns nothing that needs explicit teardown beyond Drop. AsyncModule::fulfill already handles parse_error = Some(ParseError) by building the rejection from the log, so no new consumer wiring was needed.
Other factors
Since the earlier review, three commits landed: one fixing the type-export.test.ts expectation (a real test that would have failed with the new behavior — good that it was caught and updated rather than skipped), and two trimming the code comment down to the one-line form REVIEW.md asks for. The github-actions inline threads at lines 930/932 correspond to those comment-trimming commits, so the author-resolutions are backed by actual code changes. The new tests follow harness conventions closely (test.concurrent, tempDir, Promise.all on both pipes plus exited, structured .toEqual on parsed JSON, output asserted before exit code). Exit reason was dry_streak.
…er runs The "Cannot use import statement with CommonJS-only features" check ran before to_ast, where the import scanner marks TypeScript imports that are only used as types as unused. A .ts file with such an import next to module.exports was rejected by require() and, since #40568, by import() as well, although the printed output has no import statement at all. Move the check after to_ast so it skips the elided imports. Make the parser return SyntaxError when errors were logged in this last phase, like the parse and visit phases already do, and drop the now redundant log check in RuntimeTranspilerStore.
…er runs (#40594) ### Problem - A `.ts` file with an import that is only used as a type, next to `module.exports`, fails to load with `Cannot use import statement with CommonJS-only features`. TypeScript drops such an import, so the transpiled file is plain CommonJS. `require()` and the entry point have rejected it for a long time. Since #40568, `import` and `import()` reject it too. On 1.4.1 they loaded it. - Cause: the check ran in `P::_parse` before `to_ast` (`src/js_parser/parse/parse_entry.rs:1569`). The import scanner inside `to_ast` is what marks an elided TypeScript import `IS_UNUSED` (`src/js_parser/scan/scan_imports.rs:287`), so the check saw every import as live. ### Fix - Run the check after `to_ast`, over `ast.import_records`. The `IS_INTERNAL | IS_UNUSED` skip now sees the scanner's result. Records with an empty range are skipped too: the parser generates them (the JSX runtime import), and the user cannot replace those with `require()`. The error text and notes are unchanged. - Make the parser fail on every logged error. `_parse` now halts after `to_ast` as it already does after the parse and visit phases (`parse_entry.rs:849`, `:1110`). `Parser::init` takes the error baseline before the priming `lexer.next()`, and `_parse` checks it right after the hashbang, before the `// @bun` pragma and transpiler cache returns, so an error on the first token (`\u0030foo`, an out-of-range `\u{110000}` escape) counts on every path. Before, such a file came back as an `Ok` result with an error in the log. A debug assertion in `cache::JavaScript::parse` pins the invariant. - Correct because the decision is made from the same records the printer emits. A file that prints with no `import` statement runs as CommonJS, as it did before. A file that keeps one is still rejected on all paths. Every caller already treats a parse that fails this way as a build error with the log attached. - Drop the `log().errors > 0` check #40568 added to `RuntimeTranspilerStore`. The parser no longer returns an AST with a logged error, so it was dead. - Verified: `test/js/bun/resolve/build-error.test.ts` (type-only import case fails on main, passes here; JSX and first-token cases, the latter also through a `// @bun` file), `test/cli/run/transpiler-cache.test.ts` (no cache entry for a file whose parse logged an error). Also ran `test/js/bun/typescript/`, `test/bundler/transpiler/`, `test/js/bun/resolve/`, the CJS/ESM tests in `test/cli/run/`, `test/js/node/module/` and eight bundler suites. ### Background - `P::_parse` has three phases: parse statements, visit, and `to_ast` (final assembly). `to_ast` runs the import scanner, which records exports and drops TypeScript imports with no value use by marking their record `IS_UNUSED`. `Parser::init` reads the first token before `_parse` starts. - A file that uses a CommonJS-only feature (`module`, `exports`, top-level `return`) is printed inside a function wrapper. An `import` statement is invalid there, so the parser reports the mix. - `cache::JavaScript::parse` maps a parser `Err` to `Ok(None)` and keeps the log. The runtime turns that into a `BuildMessage` rejection, the bundler into a failed build. <details><summary>Notes</summary> Repro: ```ts // types.ts export interface Foo { x: number } // mixed.ts import { Foo } from "./types"; const f: Foo = { x: 1 }; module.exports = { f }; // main.ts console.log((await import("./mixed.ts")).default); ``` 1.4.1: `import()` prints `{ f: { x: 1 } }`, `require()` and `bun mixed.ts` fail. main (4dd0588): all three fail. This branch: all three load. Cases probed on this branch, via `import()`: `import type { Foo }` plus `module.exports` loads. `import { Foo, x }` with `x` used as a value plus `module.exports` is rejected. A bare `import "./dep"` plus `module.exports` is rejected. A `.js` file with an unused `import` plus `module.exports` is rejected (JavaScript keeps unused imports at runtime). `import { Foo }` plus `exports.f = ...` loads. `commonjs_at_runtime` is only set by the two runtime module loaders (`src/runtime/jsc_hooks.rs:2652`, `src/jsc/RuntimeTranspilerStore.rs:808`), so the relocated check cannot fire in the bundler or the dev server. A `.tsx` file with JSX next to `module.exports` fails on 1.4.1 and on main with JSC's `SyntaxError`, because the generated `import { jsxDEV } from "react/jsx-dev-runtime"` is printed inside the wrapper. Without the empty-range skip this branch reported it as `Cannot use import statement with CommonJS-only features` with `note: Try require("react/jsx-dev-runtime") instead` and no location. With the skip it fails as before. #38012 makes that case work by binding the helpers with `require()`. The first-token hole, found in review: `Parser::init` calls `lexer.next()` once, and `_parse` took its baseline only afterwards. `Lexer::next` logs `Invalid identifier` and `Unicode escape sequence is out of range` and returns `Ok`, so on the first token none of the halt checks saw them. With the `RuntimeTranspilerStore` check gone, `import()` of `\u{110000}abc; console.log("ran"); module.exports = {}` executed the file and `import()` of `\u0030foo = 1;` handed `0foo = 1;` to JSC and wrote it to the transpiler cache, while `require()` rejected both. Taking the baseline in `Parser::init` closes it for every caller. The sync path's own post-parse check at `src/runtime/jsc_hooks.rs:2761` is now redundant as well. It is left alone here to keep this change small. The new transpiler-cache test fails on 1.4.1 (the first run writes a cache entry for the broken output and reports JSC's `SyntaxError`). On main it already passes through the `RuntimeTranspilerStore` check. It pins the invariant now that the parser carries it. In this container the `load the same empty JS file 2000 times` test in `test/js/bun/resolve/` times out at its 5 s limit on the debug ASAN build, with or without this change. </details> <!-- robobun:evidence:begin --> --- **[review]** gate passed · iteration 2 · 6 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 1 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/cli/run/transpiler-cache.test.ts test/js/bun/resolve/build-error.test.ts bun test v1.4.1 (adc354d) test/cli/run/transpiler-cache.test.ts: (pass) transpiler cache > works [714.38ms] (pass) transpiler cache > works with empty files [676.10ms] (pass) transpiler cache > ignores files under the minimum cache size [287.06ms] (pass) transpiler cache > does not cache a file whose parse logged an error [728.86ms] (pass) transpiler cache > it is indeed content addressable [1019.22ms] (pass) transpiler cache > doing 50 buns at once does not crash [1519.04ms] (pass) transpiler cache > disables the cache instead of falling back to the shared temp directory [607.75ms] (pass) transpiler cache > works if the cache is not user-readable [898.43ms] (pass) transpiler cache > works if the cache is not user-writable [313.39ms] (pass) transpiler cache > does not inline process.env [706.01ms] (pass) transpiler cache > --feature flag invalidates cache [1828.32ms] (pass) transpiler cache > a cached entry point does not change how later modules load > re ... (truncated) release without fix: 1 FAILED bun test v1.4.1-canary.1 (eea7b4e) test/cli/run/transpiler-cache.test.ts: (pass) transpiler cache > works [12.85ms] (pass) transpiler cache > works with empty files [12.35ms] (pass) transpiler cache > ignores files under the minimum cache size [5.73ms] (pass) transpiler cache > does not cache a file whose parse logged an error [14.92ms] (pass) transpiler cache > it is indeed content addressable [16.48ms] (pass) transpiler cache > doing 50 buns at once does not crash [30.94ms] (pass) transpiler cache > disables the cache instead of falling back to the shared temp directory [12.67ms] (pass) transpiler cache > works if the cache is not user-readable [15.92ms] (pass) transpiler cache > works if the cache is not user-writable [5.67ms] (pass) transpiler cache > does not inline process.env [10.93ms] (pass) transpiler cache > --feature flag invalidates cache [31.07ms] (pass) transpiler cache > a cached entry point does not change how later modules load > require.extensions is still consulted [13.66ms] (pass) transpiler cache > a cached entry point does not change how later modules load > unknown extensions still use the file loader [15.44ms] (pass) rejects cached module ... (truncated) ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: all passed $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/cli/run/transpiler-cache.test.ts test/js/bun/resolve/build-error.test.ts bun test v1.4.1 (adc354d) test/cli/run/transpiler-cache.test.ts: (pass) transpiler cache > works [639.93ms] (pass) transpiler cache > works with empty files [668.27ms] (pass) transpiler cache > ignores files under the minimum cache size [277.73ms] (pass) transpiler cache > does not cache a file whose parse logged an error [838.80ms] (pass) transpiler cache > it is indeed content addressable [903.84ms] (pass) transpiler cache > doing 50 buns at once does not crash [1531.88ms] (pass) transpiler cache > disables the cache instead of falling back to the shared temp directory [684.08ms] (pass) transpiler cache > works if the cache is not user-readable [990.27ms] (pass) transpiler cache > works if the cache is not user-writable [311.96ms] (pass) transpiler cache > does not inline process.env [617.38ms] (pass) transpiler cache > --feature flag invalidates cache [1829.45ms] (pass) transpiler cache > a cached entry point does not change how later modules load > req ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 588ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/5] gen generated_host_exports.rs generated_host_exports.rs: 122 exports (host=5, lazy=10, generic=107, rust=0); 243 extern-C blocks audited [1/5] cargo bun_runtime → libbun_runtime.a (--target x86_64-unknown-linux-gnu) nightly-2026-07-20-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026-07-19) �[1m�[92m Compiling�[0m bun_js_parser v0.0.0 (/workspace/bun/src/js_parser) �[1m�[92m Compiling�[0m bun_resolver v0.0.0 (/workspace/bun/src/resolver) �[1m�[92m Compiling�[0m bun_ini v0.0.0 (/workspace/bun/src/ini) �[1m�[92m Compiling�[0m bun_bundler v0.0.0 (/workspace/bun/src/bundler) �[1m�[92m Compiling�[0m bun_router v0.0.0 (/workspace/bun/src/router) �[1m�[92m Compiling�[0m bun_standalone_graph v0.0.0 (/workspace/bun/src/standalone_graph) �[1m�[92m Compiling�[0m bun_transpiler v0.0.0 (/workspace/bun/src/transpiler) �[1m�[92m Compiling�[0m bun_bunfig v0.0.0 (/workspace/bun/src/bunfig) �[1m�[92m Compiling�[0m bun_install v0.0.0 (/workspace/bun/src/install) �[1m�[92m ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/bundler/cache.rs | 6 +- src/js_parser/parse/parse_entry.rs | 186 ++++++++++++++++---------------- src/js_parser/parser.rs | 1 + src/jsc/RuntimeTranspilerStore.rs | 6 -- test/cli/run/transpiler-cache.test.ts | 30 ++++++ test/js/bun/resolve/build-error.test.ts | 114 ++++++++++++++++++++ 6 files changed, 246 insertions(+), 97 deletions(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 2 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/bundler/cache.rs 4 3 0 src/js_parser/parse/parse_entry.rs 11 13 0 src/js_parser/parser.rs 1 2 0 src/jsc/RuntimeTranspilerStore.rs 8 7 0 test/cli/run/transpiler-cache.test.ts 3 2 0 test/js/bun/resolve/build-error.test.ts 9 10 0 ``` </details> <!-- robobun:evidence:end -->
Problem
import("./mixed.js")orimport "./mixed.js", wheremixed.jshas animportstatement next tomodule.exports, rejects withSyntaxError: Unexpected token '{'. import call expects one or two arguments.require("./mixed.js")throws the parser'sBuildMessagefor the same file:Cannot use import statement with CommonJS-only features, with theTry require(...)note. This is the message behind theimport()reports in bun throws "Expected CommonJS module to have a function wrapper" importing@discordjs/builders#20718. Older versions failed the same input withTypeError: Expected CommonJS module to have a function wrapper.src/js_parser/parse/parse_entry.rs:1642), so the parse still returns a result. The sync path checkslog.errors > 0after the parse (src/runtime/jsc_hooks.rs:2761). The async path inTranspilerJob::run(src/jsc/RuntimeTranspilerStore.rs) did not. It printed theimportinside the CommonJS wrapper and handed that to JSC. The failedimport()also left that module behind, so a laterrequire()of the same file got the JSC error too.Fix
TranspilerJob::run, return withparse_error = ParseErrorwhen the log has errors.AsyncModule::fulfillthen builds the rejection from the log, the same way it does for a parse that fails outright.parse_entry.rs:849and:1110). Three errors are logged later and reach this point with an AST:Multiple exports with the same name(from the import scanner inP::to_ast), the CommonJS-only import error, and a React Compiler failure.require()and the entry point already reject all three.test/js/bun/typescript/type-export.test.ts("through export merge") expected JSC'sCannot export a duplicate name 'value'.when the file was imported and Bun'sMultiple exports with the same name "value"when it was run directly. It now expects Bun's error on both paths.test/js/bun/resolve/build-error.test.ts(two new tests, both fail on the unfixed build) andtype-export.test.ts. Also rantest/js/bun/resolve/, the CJS/ESM tests intest/cli/run/,test/js/node/module/andtest/bundler/transpiler/react-compiler.test.ts.Background
require()and the entry point usetranspile_source_code_inneron the JS thread.importandimport()useRuntimeTranspilerStore: aTranspilerJobparses and prints on a worker thread and posts the result back to the JS thread.module,exports, top-levelreturn) is printed inside the wrapper(function(exports, require, module, __filename, __dirname) { ... }). Animportstatement is not valid inside a function, so the parser reports the mix as an error with a note that names the feature.bun_ast::Logcollects the diagnostics of one transpile. ABuildMessageis the JS error built from one log entry (message, location, notes).process_fetch_logturns a log with errors into the rejection value.Notes
Repro from #20718, reduced to local files:
Before:
SyntaxError: Unexpected token '{'. import call expects one or two arguments.After:error: Cannot use import statement with CommonJS-only featuresplusnote: Try require("./x.ts") insteadandnote: This file is CommonJS because 'module' was used, exit code 1.bun b.tsalready printed that output before this change.Order matters on the unfixed build:
requirefirst gives theBuildMessage, thenimport()gives the JSC error.import()first gives the JSC error for both, because the failed async load registers the CommonJS module. The new test runsimport()first and expects theBuildMessagefrom both.Node rejects the same file. With
.cjsor"type": "commonjs"it isSyntaxError: Cannot use import statement outside a module. With module detection it runs as ESM andmodule.exportsthrowsReferenceError: module is not defined in ES module scope.The duplicate export case:
export const value = 1; export {value};imported from another file. Before, JSC reportedSyntaxError: Cannot export a duplicate name 'value'.Now the parser's error with its"value" was originally exported herenote is reported, asbun a.jsalready did. The first CI run caught this through the old expectation intype-export.test.ts.In this container (debug ASAN build, 12 cores)
load-same-js-file-a-lot.test.tsand the leak tests inrequire-cache.test.tstime out. Therequire()variants, which do not touch this code, time out the same way, so the timeouts are machine speed. Thevia import()AST leak test passes.