Skip to content

bundler: propagate known_target so a hashbang-bun entry does not split the dedup graph - #33862

Closed
robobun wants to merge 3 commits into
mainfrom
farm/1a373127/bundler-shebang-dup-module
Closed

robobun wants to merge 3 commits into
mainfrom
farm/1a373127/bundler-shebang-dup-module

Conversation

@robobun

@robobun robobun commented Jul 9, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Fixes a bundler bug where a module reachable from both a #!/usr/bin/env bun entry and one of its non-entry imports is parsed and emitted twice, breaking runtime identity and duplicating the source in the generated source map.

Also fixes #25767 as a consequence (see below).

Repro

// entry.ts
#!/usr/bin/env bun
import { Shared } from "./shared.ts";
import { ReExported } from "./reexport.ts";
console.log(Shared === ReExported, new Shared() instanceof ReExported);

// shared.ts
export class Shared { #p = 1; read() { return this.#p; } }

// reexport.ts
import { Shared } from "./shared.ts";
export const ReExported = Shared;
$ bun build entry.ts --target=node --outdir=out --sourcemap=external
$ bun out/entry.js
false false        # expected: true true

The bundle contains class Shared and a renamed class Shared2; ReExported binds to the second copy. The source map lists ../shared.ts at two indices with the file's entire text duplicated in sourcesContent.

Cause

target_from_hashbang overrides the entry file's target to Bun (ParseTask.rs). run_resolution_for_parse_task then uses result.ast.target (= Bun) to key the path-to-source-index map, so shared.ts and reexport.ts are registered in build_graphs[Bun].

When those files are parsed, the target determination at ParseTask.rs falls through to topts.target (the build target, Node here), so their ast.target is Node. reexport.ts then resolves its import of shared.ts against build_graphs[Node], does not find it, and allocates a second source index.

Before 514d37b (the server-components refactor) the fallback was task.known_target, which is the target the importer registered this file under, so the graph stayed unified.

Fix

Restore task.known_target as the fallback. The server-components "use client" path (which deliberately switches a server-graph file to the browser transpiler) is preserved by capturing whether that reassignment happened and keeping topts.target for that branch only.

With the fix, every module transitively reachable from a hashbang-Bun entry inherits ast.target == Bun and dedupes in one graph. This also means the printer escapes non-ASCII identifiers for those modules, which resolves #25767 (the // @bun pragma's Latin-1 promise now holds for the whole chunk, not just the entry). Related: #33859 addresses #25767 by suppressing the pragma instead; the two changes do not conflict.

How did you verify your code works?

Added four itBundled cases in test/bundler/bundler_edgecase.test.ts covering target=node and target=browser, each with a direct import and an export * barrel. Each asserts:

  • the bundle runs and prints true true (class identity preserved) or the expected value;
  • the output contains exactly one class Shared declaration;
  • the source map's sources array has no duplicate entries.

All four fail on the released binary (duplicate class Shared2 emitted) and pass with this change. Also ran bundler_bun, bundler_banner, bundler_browser, bundler_cjs2esm, bundler_barrel, bundler_npm, bake/dev-and-prod, bake/dev/bundle, bake/dev/react-response: all pass.


no test proof · iteration 1 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/bundler/bundler_edgecase.test.ts

…t the dedup graph

When the entrypoint starts with '#!/usr/bin/env bun', ParseTask overrides
that file's target to Bun. Its imports are then registered in
build_graphs[Bun]. But when those imports are parsed, the target
determination fell through to topts.target (the build target, e.g. Node),
so their own imports were looked up in build_graphs[Node] and not found,
causing a second parse and a second copy of any module reachable both
directly from the entry and from another import.

The fallback used to be task.known_target (the target the importer
registered this file under) and was changed to bundler.options.target in
514d37b as part of the server-components refactor. Restoring
known_target as the fallback keeps every module in one dedup graph for the
hashbang case, while the explicit server-components / use-directive branch
still selects the browser transpiler's target.

Fixes the duplicated source entry (and duplicated sourcesContent) in the
generated source map, and fixes the runtime identity break where the two
copies of a class were distinct constructors.

Also fixes #25767: dependencies now inherit the entry's Bun target and are
printed with escaped non-ASCII identifiers, so the '// @Bun' pragma's
Latin-1 promise holds for the whole chunk.
@robobun

robobun commented Jul 9, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 12:59 PM PT - Jul 9th, 2026

❌ @robobun, your commit 7a440ff has 2 failures in Build #71124 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 33862

That installs a local version of the PR into your bun-33862 executable, so you can run:

bun-33862 --bun

@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The PR refactors target resolution in Bun's bundler ParseTask for hashbang entry files, introducing a will_use_browser_transpiler flag that determines whether topts.target or task.known_target is used. New edge-case tests validate hashbang handling for Node and Browser targets, checking deduplicated sourcemap sources and single class definitions.

Changes

Hashbang Target Resolution

Layer / File(s) Summary
Browser transpiler condition and target propagation
src/bundler/ParseTask.rs
Introduces a will_use_browser_transpiler boolean capturing the prior combined switch condition, and uses it to decide whether the non-hashbang target resolves to topts.target or task.known_target.
Hashbang edge-case tests for Node/Browser targets
test/bundler/bundler_edgecase.test.ts
Adds a target-parameterized loop with two itBundled cases (shared import and export star) validating single class definitions and deduplicated sourcemap sources for bun-hashbang entries bundled to Node and Browser targets.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and accurately summarizes the main bundler fix.
Description check ✅ Passed The description includes the required purpose and verification sections and provides sufficient detail about the fix and tests.

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. bundler: gate @bun pragma and @bun-cjs wrapper on build target, not entry hashbang #33859 - Both PRs fix issue Unicode double-encoding when running --target=node bundle under Bun runtime #25767 (hashbang #!/usr/bin/env bun causing incorrect behavior when bundling for non-bun targets). bundler: gate @bun pragma and @bun-cjs wrapper on build target, not entry hashbang #33859 gates the // @bun pragma on the build target instead of the entry hashbang, while bundler: propagate known_target so a hashbang-bun entry does not split the dedup graph #33862 restores known_target propagation so modules stay in one dedup graph. The PR author notes these are alternative approaches that do not conflict, but they address the same root issue.

🤖 Generated with Claude Code

@robobun

robobun commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Not a duplicate of #33859. They touch different files and fix different bugs that happen to share a trigger (hashbang entry with a non-bun build target):

This PR also happens to resolve #25767 because dependencies now inherit the entry's Bun target and are printed with escaped identifiers, so the pragma's Latin-1 promise holds. But the module-duplication fix here is the primary change and is not covered by #33859.

Comment thread src/bundler/ParseTask.rs Resolved
…lving its imports

Follow-up to the known_target propagation change: the hashbang entry itself
is registered only in build_graphs[build_target] by enqueue_entry_item, but
its descendants now resolve against build_graphs[Bun]. A descendant that
circularly imports the entry would miss and allocate a second source index
for it.

Before resolving a file's imports, ensure the file's own path is present in
build_graphs[ast.target] so circular edges dedupe. Server-component
boundaries are excluded because on_parse_task_complete intentionally maps
their path to the generated reference proxy instead.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The circular-entry fix in db87d46 looks right and the new tests cover it — no further issues from me, but given this touches the bundler's per-target dedup-graph registration on every parse (and threads through the server-components boundary logic), it's worth a human sign-off.

Extended reasoning...

Overview

This PR changes how ast.target is determined for parsed files in the bundler (src/bundler/ParseTask.rs) and adds a mirroring step in run_resolution_for_parse_task (src/bundler/bundle_v2.rs) that registers each parsed file's path in build_graphs[ast.target] before resolving its imports. Six new itBundled tests in test/bundler/bundler_edgecase.test.ts cover the diamond-import, export-star barrel, and circular-back-to-entry topologies for both node and browser build targets with a #!/usr/bin/env bun entry.

I previously flagged that the first revision regressed circular imports back to the entry; the author confirmed with a repro and addressed it in db87d46 by mirroring into build_graphs[ast.target] (gated on use_directive == None so server-component boundaries still map to the generated proxy). I re-checked the follow-up: the key (result.source.path.text) matches how every other call site keys path_to_source_index_map, and in the common case (ast.target == registration target) the get().is_none() guard makes it a no-op. The bug hunter found nothing on this revision.

Security risks

None identified. This is bundler graph bookkeeping — no auth, crypto, network, or untrusted-input parsing surface changes.

Level of scrutiny

Medium-high. The change is small in line count but sits in core bundler graph construction that runs for every parsed file, and it interacts with two subtle subsystems: hashbang-driven target flipping and server-components' separate-SSR-graph handling. The first revision introduced a real regression (circular entry re-parse) that was only caught in review, which suggests the invariants here are non-obvious. The author explicitly scoped out a related multi-entry design tension.

Other factors

Good test coverage was added for all three topologies raised in review. The ParseTask.rs change restores pre-514d37b3d2 behavior for the non-server-components branch, and the bundle_v2.rs mirroring is defensive and narrowly gated. Still, per the approval criteria this is not a simple/mechanical change and touches a critical code path, so I'm deferring rather than approving.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the follow-up in db87d46 — the circular-entry case is now covered and I found nothing further, but the build_graphs[ast.target] mirroring in run_resolution_for_parse_task runs on every parse result and touches the core dedup-map invariants, so a maintainer familiar with the bundler graph should sign off.

Extended reasoning...

Overview

This PR changes how per-file ast.target is determined in src/bundler/ParseTask.rs (restoring task.known_target as the fallback so a #!/usr/bin/env bun entry's whole subtree keys into one build_graphs map), and — after my earlier review — adds a mirroring step in src/bundler/bundle_v2.rs::run_resolution_for_parse_task that inserts each parsed file's path into build_graphs[ast.target] before its imports are resolved. Six itBundled tests are added covering diamond, export *, and circular-back-to-entry topologies for both node and browser build targets.

Security risks

None. This is bundler graph bookkeeping — no auth, crypto, network, or untrusted-input parsing surface.

Level of scrutiny

High. The dedup map (path_to_source_index_map keyed by target) is the mechanism that guarantees a source file is parsed and emitted exactly once; getting it wrong produces silent runtime miscompiles (broken class identity, doubled side effects) rather than build errors. The follow-up commit adds an unconditional insertion on this map for every parse result gated only on use_directive == None, which interacts with server-components (where on_parse_task_complete deliberately remaps the same path to a generated proxy), the dev server, and multi-entry --splitting. The author scoped the guard carefully and the reasoning checks out against the code I traced, but this is exactly the kind of cross-cutting invariant a bundler maintainer should confirm.

Other factors

My earlier finding (circular import back to the hashbang entry re-parsing the entry) was addressed with a code fix plus dedicated CircularEntry tests, and the thread is resolved. The bug-hunting pass on the latest revision found nothing. The author also ran the bake/dev-server suites, which exercise the server-components path the guard is meant to preserve. The remaining multi-entry design tension is acknowledged and reasonably left out of scope. Net: I have no outstanding concerns of my own, but the change is not simple/mechanical enough for bot approval.

@robobun

robobun commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI status: the bundler changes are green on every lane. The remaining red is unrelated flake on :darwin: 14 x64 (build 71124):

  • test/js/bun/http/proxy-stress-concurrent.test.ts: 1/1200 requests failed in the https-proxy stress probe
  • test/js/bun/terminal/terminal.test.ts: creates subprocess with terminal attached timed out at 90s

plus already-flaky-tagged retries for bun-install.test.ts (EBADF on Windows 2019 x64) and postgres-invalid-message-length.test.ts (11 aarch64). None of these touch bundler code; the diff here is confined to src/bundler/ParseTask.rs, src/bundler/bundle_v2.rs, and test/bundler/bundler_edgecase.test.ts. The previous run (build 71112) also failed only on an unrelated Postgres connection refusal on Windows baseline.

Ready for review.

@robobun

robobun commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator Author

Re-checked against main at 165dc9f now that #25767 is closed. The HashbangBunEntryTargetNodeSharedImport and HashbangBunEntryTargetBrowserSharedImport tests from this PR still fail on main (the bundle still contains both class Shared and class Shared2, and the source map still lists shared.ts twice), and ParseTask.rs still falls back to topts.target.

#25767 was closed after verifying the issue's literal repro, which has no hashbang. On main, a #!/usr/bin/env bun entry that imports a file containing non-ASCII text and is built with --target=node still prints mojibake under Bun, so this PR is not covered by anything that landed. Keeping it open. It needs a rebase: the src/ hunks merge cleanly, only test/bundler/bundler_edgecase.test.ts conflicts.

@robobun

robobun commented Aug 26, 2026

Copy link
Copy Markdown
Collaborator Author

Verification against current main (731aa92). I applied this PR's six test cases on main without its source change:

  • edgecase/HashbangBunEntryTargetNodeSharedImport and edgecase/HashbangBunEntryTargetBrowserSharedImport: fail. The output has class Shared and class Shared2, and the source map lists ../shared.ts twice.
  • The ExportStar and CircularEntry cases pass on main. CircularEntry only breaks once this PR changes the target fallback, so it guards the bundle_v2.rs part. ExportStar passes on main only because the entry never uses the re-exported binding, so the second copy is tree-shaken away. The split is still there. With import { Shared as S2 } from "./barrel.ts" and console.log(Shared === S2), main prints false and lists ../shared.ts twice. The test would catch more if the entry used the re-exported binding.

With the source change applied on main, all six pass and the Shared === S2 variant prints true. bundler_edgecase, bundler_bun and bundler_barrel pass.

The branch now conflicts with main in test/bundler/bundler_edgecase.test.ts only. Both sides append tests to the end of the same describe block. src/bundler/ParseTask.rs and src/bundler/bundle_v2.rs merge cleanly. It needs a rebase.

#25767 was closed as fixed on main. That verification used the snippet from the issue body, which has no hashbang. That snippet does not reproduce the bug on 1.3.4 or on main. The hashbang case still reproduces on main, so I reopened the issue. This change fixes it as well: the dependency's string prints as "Symbols: \u2713 \u2717 \u26A0" and the output runs correctly under Bun. #33859 fixes the same symptom by not emitting the pragma for non-bun targets. The two changes touch different files and do not conflict.

@robobun

robobun commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as stale: this PR conflicts with main, and its last commit is from 2026-07-09.

The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR.

@robobun robobun closed this Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unicode double-encoding when running --target=node bundle under Bun runtime

1 participant