Repository navigation
Conversation
|
Updated 9:40 PM PT - Aug 20th, 2026
❌ @robobun, your commit 35b91cf has 1 failures in
🧪 To try this PR locally: bunx bun-pr 31244That installs a local version of the PR into your bun-31244 --bun |
|
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:
WalkthroughAdds end-to-end support for TC39 Stage 3 dynamic ChangesDynamic Import Deferred Evaluation
Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/js/bun/resolve/import-defer.test.ts`:
- Around line 668-669: Move the assertion that checks stderr content before the
assertion that checks the exit code in the syntax-error tests: replace the
pattern expect(exitCode).not.toBe(0);
expect(stderr.toLowerCase()).toContain("error"); with
expect(stderr.toLowerCase()).toContain("error"); expect(exitCode).not.toBe(0);
for each occurrence (the three places that currently use those two assertions).
Ensure you only swap the order of the two existing assertions (leave the exact
match/transform on stderr and the not-to-be(0) check unchanged).
🪄 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: cedd6a09-87a3-43a7-afcc-dc584d6c0f45
📒 Files selected for processing (15)
src/ast/e.rssrc/ast/expr.rssrc/ast/import_record.rssrc/js_parser/p.rssrc/js_parser/parse/parse_import_export.rssrc/js_parser/parser.rssrc/js_parser/repl_transforms.rssrc/js_parser/visit/visit_expr.rssrc/js_printer/lib.rssrc/jsc/bindings/NodeVM.cppsrc/jsc/bindings/NodeVM.hsrc/jsc/bindings/ZigGlobalObject.cppsrc/runtime/bake/BakeGlobalObject.cpptest/bundler/bundler_edgecase.test.tstest/js/bun/resolve/import-defer.test.ts
There was a problem hiding this comment.
Thanks for addressing both nits — I don't see any remaining issues, but given this threads a new TC39 phase through the parser, printer, and three C++ moduleLoaderImportModule hooks, it's worth a human pass before merging.
Extended reasoning...
Overview
This PR implements dynamic import.defer() (TC39 Stage 3 deferred module evaluation), completing the static import defer work from #30975. It touches 15 files across four layers: AST (E::Import.phase_defer, ImportRecordFlags::PHASE_DEFER extended to dynamic records), parser (parse_import_expr accepts import.defer(...), threads phase_defer through TransposeState/transpose_import), printer (emits import.defer( for external/non-literal records, degrades to plain import( when WRAP_WITH_TO_ESM would defeat it), and the C++ runtime where ZigGlobalObject, BakeGlobalObject, and NodeVM now forward the previously-dropped bool deferred into JSC::importModule. ~310 lines of new tests cover deferral semantics, TLA, error propagation, CJS interop, attributes, transpiler round-tripping, and bundler degradation.
Security risks
None identified. The change is parsing/threading a boolean phase flag for a standards-track syntax form; no auth, crypto, filesystem, or network surface is touched. The C++ changes replace hardcoded false with a forwarded parameter on an existing JSC hook signature.
Level of scrutiny
High. This is a new language-feature implementation that alters how the JS parser branches on import., adds a field to a core AST node, and changes module-loader host-hook behavior across three global-object variants. Subtle interactions (ESM-marker handling for import.meta vs import.defer, escaped-keyword rejection, bundler inlining vs external paths, code-splitting + __toESM interop) are exactly the kind of thing a maintainer should sanity-check against the spec and JSC's expectations.
Other factors
Both of my earlier inline nits (stale "meta" diagnostic, redundant .defer under WRAP_WITH_TO_ESM) and CodeRabbit's assertion-order nit have been addressed in 117a476, 015d3eb, and 8531a4f respectively. The bug-hunting system found no issues on the current revision. Test coverage is thorough (19 new runtime cases + 3 bundler cases) and the PR description documents verification including no-regression runs. Buildkite #57072 reports failures on an earlier commit; I'd defer to a human to confirm those are unrelated/resolved on the latest push.
|
Status for maintainers — the implementation and review cycle are done; the remaining red CI is unrelated flake.
|
792fcd8 to
4519f76
Compare
|
Status for maintainers — rebased onto current main ( Build #102193: the only hard failure is Rebase resolutions accumulated:
Verification (debug build, current head):
My one allowed retrigger is used. Once the |
4519f76 to
8372138
Compare
c7d8bce to
c2daf08
Compare
c2daf08 to
9b5f824
Compare
9b5f824 to
f3ef340
Compare
There was a problem hiding this comment.
I reviewed this PR and the bug-hunting pass found no issues; all earlier inline findings are resolved. Because it ships new user-facing language syntax and threads a new flag through the parser, printer, and the moduleLoaderImportModule host hook across three global-object types, a maintainer sign-off is still warranted.
What was reviewed
- Parser:
import.deferrecognition,esm_import_keywordmoved so onlyimport.metaimplies ESM, escaped-deferrejection viais_contextual_keyword. - Printer:
.deferemission for external and non-literal paths; confirmed the!wrap_with_to_esmguard prevents the self-defeatingimport.defer(...).then(__toESM)shape. - Runtime:
deferredforwarded throughZigGlobalObject,BakeGlobalObject, and node:vm'sUSE_MAIN_CONTEXT_DEFAULT_LOADERpath; userimportModuleDynamicallycallbacks intentionally drop it (no phase parameter in Node's API). phase_deferthreaded throughTransposeState,deep_clone, REPL lowering, and the react-compilerE::Importconstruction site.
Extended reasoning...
Overview
This PR completes the TC39 Stage 3 Deferred Module Evaluation proposal by adding the dynamic import.defer(...) form (the static import defer * as form landed in #30975). It spans 16 files: a new phase_defer: bool on E::Import and TransposeState, parser recognition of import.defer after the dot, printer emission of import.defer( for external/non-literal targets, and forwarding of JSC's existing bool deferred parameter through moduleLoaderImportModule in ZigGlobalObject.cpp, BakeGlobalObject.cpp, and NodeVM.cpp. Test coverage is thorough: 19 new runtime tests in import-defer.test.ts (deferral timing, TLA transitive deps, throwing modules, CJS callers/targets, computed specifiers, attributes, transpiler round-trip, syntax errors) plus 3 bundler edge-case tests.
Security risks
None identified. The change accepts a new syntactic form and forwards a boolean through an existing host hook whose engine-side semantics are already implemented in the pinned WebKit. No new untrusted-input parsing beyond what import() already handles; the specifier and options arguments go through the existing dynamic-import validation path.
Level of scrutiny
High — this is new user-facing language syntax, and the repo's review guidance calls out API design and Node/Web compat as situational sections requiring maintainer attention. The implementation itself is mechanically clean (a boolean threaded through existing plumbing, with the engine doing the actual work), but shipping a Stage 3 language feature is a product decision. The bundler-degradation behavior (inlined targets lose the defer phase, matching static import defer) and the node:vm limitation (user importModuleDynamically callbacks have no phase parameter) are documented and tested but are the kind of trade-offs a maintainer should confirm.
Other factors
All prior review feedback (mine and CodeRabbit's) has been addressed across the commit history, including the WRAP_WITH_TO_ESM interaction and the "meta" or "defer" diagnostic. The one intentionally-deferred nit (the import() label in check_dynamic_specifier for non-literal deferred specifiers under allowUnresolved) is reasonable to leave — import.defer() is grammatically an ImportCall. The comment-cop lint pass is clean at head. Tests use describe.concurrent, spawn subprocesses with bunEnv/tempDir, assert stderr before exit code, and are verified to fail under USE_SYSTEM_BUN=1.
Parse `import.defer(specifier[, options])` into `E::Import { phase_defer }`,
mark the dynamic import record with `PHASE_DEFER`, and print the call back
out as `import.defer(...)` so JSC sees the phase. The module loader host
hook now forwards the `deferred` flag it receives from JSC into
`JSC::importModule(...)` (Zig, Bake, and node:vm default-loader paths),
letting JSC link the graph, evaluate only async transitive dependencies, and
resolve with the deferred namespace.
When the bundler inlines the target module, the call degrades to a regular
dynamic import — the same documented limitation as static `import defer`.
With code splitting, a deferred dynamic import of a cross-chunk CommonJS target gets wrapped in .then((m)=>__toESM(m.default)), which touches the namespace immediately and would defeat the defer phase on the same line. Emit a regular dynamic import there instead.
4719f96 to
35b91cf
Compare
There was a problem hiding this comment.
I reviewed this PR and found no bugs. Since it adds new user-facing language syntax (import.defer()) and threads a new flag through the module-loader host hooks across four global-object types, a maintainer sign-off on the design choices (bundler degradation, node:vm phase handling) would still be worthwhile.
Checked: phase_defer is threaded through every E::Import construction site (parse, visit/transpose, deep-clone, REPL transform, react-compiler codegen); esm_import_keyword is now set only for import.meta, not import.defer, so CJS callers work; the printer's !wrap_with_to_esm guard prevents emitting a self-defeating .defer on code-split CJS chunks; the deferred flag reaches JSC::importModule on all four moduleLoaderImportModule paths (Zig, Bake, NodeVM, plugin virtual-module).
All prior inline nits from earlier passes have been addressed or explicitly acknowledged.
Extended reasoning...
Overview
This PR completes Bun's implementation of the TC39 Stage 3 Deferred Module Evaluation proposal by adding the dynamic import.defer(...) form (static import defer * as landed in #30975). It touches 16 files across:
- Parser/AST (Rust):
parse_import_export.rsrecognizesimport.defer(,E::Importgainsphase_defer: bool,TransposeStateandtranspose_importthread it through,ImportRecordFlags::PHASE_DEFERis set on dynamic records, deep-clone and react-compiler codegen copy the field, REPL static→dynamic import lowering preserves it. - Printer (Rust): emits
import.defer(for external/non-literal targets; drops the phase when the__toESMinterop wrapper would immediately touch the namespace (code-split CJS). - Runtime (C++):
ZigGlobalObject,BakeGlobalObject, andNodeVMGlobalObjectmoduleLoaderImportModulehooks now forward thedeferredflag intoJSC::importModuleinstead of dropping it;NodeVM::importModulegains abool deferredparameter for theUSE_MAIN_CONTEXT_DEFAULT_LOADERpath. - Tests: 19 new runtime cases in
import-defer.test.tsand 3 new bundler cases inbundler_edgecase.test.ts.
Security risks
None identified. The change adds a new import phase that JSC already supports engine-side; Bun is just passing through a flag it previously discarded and accepting syntax it previously rejected. No new parsing of untrusted input beyond what import() already does; the specifier and options arguments follow the exact same code path as regular dynamic import.
Level of scrutiny
High — this is new user-facing language syntax and touches the module loader across four global-object types. While the individual changes are mechanical (thread a bool, forward a flag), the design decisions warrant maintainer review:
- Bundler degradation: when the target is inlined,
.deferis silently dropped (documented as the same limitation as staticimport defer). A maintainer should confirm this is the desired behavior vs. warning. - node:vm:
importModuleDynamicallycallbacks have no phase parameter (matching Node), sodeferredis intentionally dropped on that path — worth a maintainer confirming this matches intent. - Bake dev-server
hmr.dynamicImportpath is unchanged (no.defersupport) — likely fine but a design call.
Other factors
- Test coverage is thorough: deferred evaluation timing, namespace identity with static
import defer, error-at-access semantics, TLA transitive deps, CJS callers/targets, runtime-computed specifiers, import attributes, transpiler round-trip, syntax-error negative cases, and three bundler scenarios. - All prior review feedback (mine and CodeRabbit's) has been addressed: assertion order in tests,
"meta" or "defer"diagnostic, the__toESM/.deferinteraction, and comment-cop lint. One minor diagnostic-wording nit was acknowledged and intentionally deferred to a follow-up. - The PR has been rebased multiple times over three months with careful conflict resolution documented in status comments.
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-08-21. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Implements the dynamic form of the Stage 3 Deferred Module Evaluation proposal, completing the feature started in #30975 (static
import defer):Bun's pinned WebKit already ships the engine side (upstream WebKit/WebKit#64907): the JSC parser accepts
import.defer(...)underuseImportDefer(which Bun enables), and themoduleLoaderImportModulehost hook carries a trailingbool deferred. Bun previously rejected the syntax in its own transpiler and ignored that flag.What changed
Parser / AST —
src/js_parser/parse/parse_import_export.rs,src/ast/e.rs,src/js_parser/{parser,p,visit/visit_expr,repl_transforms}.rsimport.now accepts the contextual keyworddeferfollowed by the usual( specifier [, options] )arguments. The check compares the raw token, soimport.def\u0065r(...)stays a syntax error; other identifiers afterimport.still error.import.meta,import.defer()does not mark the file as ESM (it is valid in CommonJS, likeimport()).E::Import.phase_defer, threaded through import transposition (TransposeState.phase_defer), andImportRecordFlags::PHASE_DEFERis now also set onImportKind::Dynamicrecords.import defer * as X from 'mod'→await import.defer('mod').Printer —
src/js_printer/lib.rsimport.defer(...), so JSC's own parser sees the phase during bytecode generation.Promise.resolve().then(...)) — the same documented limitation as staticimport defer. The bake dev server'shmr.dynamicImportpath is likewise unchanged.Runtime —
src/jsc/bindings/ZigGlobalObject.cpp,src/runtime/bake/BakeGlobalObject.cpp,src/jsc/bindings/NodeVM.{h,cpp}moduleLoaderImportModuleforwards thedeferredflag intoJSC::importModule(...)instead of dropping it, for the main global, Bake global, plugin virtual modules, and the node:vmUSE_MAIN_CONTEXT_DEFAULT_LOADERpath. JSC then links the graph, eagerly evaluates only the async transitive dependencies, and resolves the promise with the deferred namespace (ensureDeferredNamespaceEvaluationhandles later property access).importModuleDynamicallycallbacks have no phase parameter (same as Node), so deferred imports resolved through a user callback behave like regular dynamic imports.Semantics covered by tests (
test/js/bun/resolve/import-defer.test.ts, 19 new cases)ns[Symbol.toStringTag] === "Deferred Module"import.defer()and staticimport deferof the same module yield the same namespace object.tsfiles, CommonJS callers, CommonJS targets (host-defined eager evaluation)Bun.Transpilerround-tripsimport.defer(...)andscanImportsreports it asdynamic-importimport.deferwithout a call, escapeddef\u0065r,import.source(...)Bundler coverage (
test/bundler/bundler_edgecase.test.ts): inlined targets degrade gracefully and run;--externaltargets keepimport.defer(...)in the output.Verification
bun bd test test/js/bun/resolve/import-defer.test.ts— 39 pass (20 existing static + 19 new)bun bd test test/bundler/bundler_edgecase.test.ts -t DynamicImportDefer— 2 passUSE_SYSTEM_BUN=1(1.4.0 rejects the syntax withExpected "meta" but found "defer")transpiler.test.js,vm.test.ts,repl-transform.test.ts,concurrent-dynamic-import,dynamic-import-tla-cycle,import-meta,import-queryall passno test proof · iteration 17 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/bundler/bundler_edgecase.test.ts