Repository navigation
Conversation
Five fixes to how HTML entrypoints classify and emit asset URLs: - HTMLScanner: leave protocol-relative URLs (//host/...) for the resolver's external rule instead of rewriting them as rooted project paths. - HTMLScanner/HTMLLoader: parse img[srcset]/source[srcset] with the WHATWG image-candidate grammar, one import record per candidate URL, and rewrite the attribute with descriptors preserved. - HTMLLoader: re-append the ?query/#fragment suffix from the source URL to the hashed asset reference (mirroring the CSS printer). - find_reachable_files: treat any non-CSS importer (HTML included) as a copy-forcing context so a CSS-inlined asset also referenced from HTML is still emitted on disk. HTMLLoader falls back to the data: URI when no unique key is available instead of leaving the raw source path. - process_files_to_copy: hard-error on distinct-content asset output path collisions with the same 'Multiple files share the same output path' message the chunk pass emits; identical-content collisions are left alone.
WalkthroughChangesHTML bundling now preserves protocol-relative URLs, parses and rewrites HTML bundling and asset output
Possibly related PRs
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 12:12 AM PT - Jul 27th, 2026
✅ @robobun, your commit 0e4276e1511485ee798ce9a901ddb3ce5bccbbf3 passed in 🧪 To try this PR locally: bunx bun-pr 36015That installs a local version of the PR into your bun-36015 --bun |
|
This PR may be a duplicate of:
🤖 Generated with Claude Code |
|
CI build #82946 (latest, at c0ae417): bundler test lanes green. Remaining marks are unrelated to this diff:
All review feedback addressed. Ready for review. |
…tighten emit test
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 `@test/bundler/bundler_html.test.ts`:
- Around line 1043-1077: Expand the “html/srcset-candidates” test to cover
descriptor-less srcset candidates, trailing-comma termination, and candidates
separated by multiple spaces or newlines. Add fixture markup and assertions for
both img and source where applicable, verifying rewritten local assets,
preserved descriptors or absence of descriptors, ignored trailing entries, and
unchanged external URLs while confirming emitted asset contents.
In `@test/bundler/bundler_naming.test.ts`:
- Line 215: Update the bundler naming test assertion for the “Multiple files
share the same output path” error to also verify the conflicting output path and
each contributing input listed in the detail block, rather than matching only
the header. Preserve the existing header assertion while asserting the complete
collision details emitted by the bundling error.
🪄 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: bf3a6e6a-740b-40d9-83b6-ae50df2ceb36
📒 Files selected for processing (5)
src/bundler/HTMLScanner.rssrc/bundler/bundle_v2.rssrc/bundler/linker_context/generateCompileResultForHtmlChunk.rstest/bundler/bundler_html.test.tstest/bundler/bundler_naming.test.ts
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🟡
src/bundler/linker_context/generateCompileResultForHtmlChunk.rs:264— The dev-server fallback branch returnsRewrittenUrl::Value(import_record.path.pretty.to_vec())without re-appendingsuffix, while the sibling unique-key branch just above gotwith_suffix(unique_key_for_additional_files, suffix).path.prettyis derived from the post-strip resolved path (e.g./_bun/asset/{hash}.svg), so'<img src="./sprites.svg#icon">'in dev-server mode still loses#icon— same bug class this PR fixes for the production path. One-line fix:return with_suffix(import_record.path.pretty, suffix);.Extended reasoning...
What
In
rewrite_one_url, the PR adds?query/#fragmentre-appending via thewith_suffixclosure to the production unique-key branch, thedata:-URI branches, and the dev-server unique-key branch — but not to the dev-server fallback:if self.linker.dev_server.is_some() { if !unique_key_for_additional_files.is_empty() { return with_suffix(unique_key_for_additional_files, suffix); // ← got the fix } else if import_record.path.is_disabled || loader.is_javascript_like() || loader.is_css() { return RewrittenUrl::Remove; } return RewrittenUrl::Value(import_record.path.pretty.to_vec()); // ← didn't }
Why the suffix is genuinely lost here
import_record.path.prettyis derived frompath.text— the resolver's post-strip path. HTML<img src>usesImportKind::Url, for whichis_from_css()is true (src/ast/lib.rs), so the resolver retries with?#stripped andpath.textcarries no fragment. In dev-server mode with a cached asset,bundle_v2.rssetsimport_record.source_index = Index::INVALIDandpath.pretty = "{ASSET_PREFIX}/{hash:016x}{ext}"computed frompath.text— no fragment. Withsource_indexinvalid,unique_key_for_additional_filesisb""andloaderdefaults toLoader::File, so control falls through to thepath.pretty.to_vec()return.Step-by-step
- Source:
'<img src="./sprites.svg#icon">', dev server running,sprites.svgalready in the dev-server asset cache. - Scan pass creates an
ImportKind::Urlrecord; resolver strips#iconto locatesprites.svg; dev-server asset path setssource_index = INVALIDandpretty = "/_bun/asset/abcd….svg". - Rewrite pass:
original = b"./sprites.svg#icon", sosuffix = b"#icon". self.linker.dev_server.is_some()→ true.unique_key_for_additional_filesis empty (source_index invalid).is_disabled/is_javascript_like()/is_css()all false for a.svgfile loader.- Falls through to
return RewrittenUrl::Value(import_record.path.pretty.to_vec())→"/_bun/asset/abcd….svg", no#icon. - Browser fetches the sprite sheet but renders nothing — SVG fragment addressing (
<use href>-style) needs the client-side#iconto select the symbol.
Why existing code doesn't prevent it
suffixis computed unconditionally at the top of the function andwith_suffixis a local closure available to every branch, but this return simply doesn't call it. The production-mode sibling at the bottom of the function (return with_suffix(unique_key_for_additional_files, suffix)) and the dev-server unique-key branch two lines above both do. Nothing else in the pipeline re-attaches the fragment after this point —RewrittenUrl::Valueis written to the attribute verbatim.Impact
Dev-server-only, and the pre-PR line was
set_attribute(element, url_attribute, import_record.path.pretty)— identical behavior, so this is not a regression. But it is exactly the bug class the PR sets out to fix ("?query/#fragmentstripped on rewrite"), and REVIEW.md is explicit: "Fix the whole class in the same PR — same-class sites are ONE concern, not scope creep. Grep for every sibling site sharing the pattern." This is a same-function sibling two lines below a site that received the fix.Fix
return with_suffix(import_record.path.pretty, suffix);
If
prettycan somehow already carry a suffix in dev-server mode (I couldn't find a path where it does), a comment stating why this branch is intentionally excluded would satisfy the same rule. - Source:
…path.pretty in asset-collision error
There was a problem hiding this comment.
All prior inline feedback has been addressed (including the stale-comment nit at bundle_v2.rs:1646/1981 — now updated). I didn't find further issues, but this bundles five independent behavioural fixes (new SrcSetIter parser, rewrite_one_url refactor, the is_js→!is_css reachability-gate change, new asset output-path collision check) across ~430 lines of bundler emit/reachability code, so it's worth a human pass.
What was reviewed:
SrcSetIteragainst the WHATWG image-candidate grammar — trailing-comma, descriptor-less, whitespace-run cases all covered; scan and rewrite drive the same iterator so record indices stay 1:1.rewrite_one_url: every value-producing arm (dev-server unique-key, dev-server pretty-path fallback, data:-URI, non-dev unique-key) now goes throughwith_suffix; data:-URI arm keeps fragment-only.find_reachable_filesgate widening: checked that theadditional_files_imported_by_css_and_inlinedbranch is unaffected and the clear-site guard at ~1981 still reads the same bitset.- Asset-collision check: identical-content collisions correctly bypass the error;
from inputlines now usepath.prettymatching the chunk-side message.
Extended reasoning...
Overview
Five HTML-bundler fixes in one PR: (1) //host/... no longer misclassified as project-rooted; (2) srcset walked per-candidate via a new SrcSetIter shared between scan and rewrite; (3) ?# suffix re-appended on rewritten asset URLs (mirroring the CSS printer); (4) HTML importers now force on-disk emission of CSS-inlined assets (is_js && is_inlined → is_inlined && !is_css); (5) asset output-path collisions now raise DuplicateOutputPath instead of silent last-writer-wins. on_tag was refactored into rewrite_one_url returning a RewrittenUrl enum so the srcset loop and the single-URL path share one code path. Four new bundler_html tests plus naming/AssetNoOverwrite un-todo'd and a same-content variant added.
Security risks
None identified. Inputs are build-time HTML/asset paths under the user's own control; no auth/crypto/network surface. The new SrcSetIter operates on borrowed byte slices with index-bounded loops — no allocation driven by untrusted lengths.
Level of scrutiny
Medium-high. This is production bundler output correctness: the reachability-gate change (!is_css) affects whether assets are emitted at all, the collision check turns a previously-silent build into a hard error, and SrcSetIter is a hand-rolled tokenizer for a WHATWG micro-grammar. None of it is hot-path perf-sensitive, but wrong output here ships to users' dist/.
Other factors
Three earlier review rounds from me flagged: sticky-remove nuking the whole <img> on one Remove candidate, dev-server path.pretty fallback dropping the suffix, absolute vs pretty path in the collision error, and stale doc-comments on the reachability bitset — all four are fixed in the current diff. CodeRabbit's srcset edge-case coverage ask was also taken (descriptor-less / newline / trailing-comma fixture). The PR consolidates three prior PRs plus two new fixes, which is a lot of surface for one change; the individual pieces look correct and are each covered by a test that fails on main, but the aggregate scope is why I'm deferring rather than approving.
Jarred-Sumner
left a comment
There was a problem hiding this comment.
Too much code for something that should be simple.
…tIter src/ is now net +86 (was +217): collision check is a single-pass first-error, rewrite helper drops the intermediate enum ceremony and debug logs, SrcSetIter uses iterator combinators over hand-rolled index loops.
|
Trimmed in 0e4276e:
All 6 tests still pass. Happy to split into per-fix PRs instead if that's easier to review. |
There was a problem hiding this comment.
No new issues found, but this bundles five behavioral fixes plus a post-review simplification pass (0e4276e) that reshaped next_record_url, compacted SrcSetIter, and replaced the aggregated collision error with a first-hit-only message — worth a human pass on the final shape.
What was reviewed:
SrcSetItertokenization vs. WHATWG step 8 (paren-depth, trailing-comma, descriptor-less, url-with-comma) — scan and rewrite drive the same iterator so record indices stay 1:1.next_record_urlrefactor is behavior-preserving vs. the old inlineon_tag(external/invalid-source/JS-CSS/standalone/unique-key ordering); all value-producing arms now go through the?#re-append, including the dev-serverpath.prettyfallback.find_reachable_filesis_js→!is_cssgate widens copy-forcing to HTML importers only; CSS-only-referenced inlined assets still get theiradditional_filescleared.- Asset collision check keys on
dest_pathand compareshash, so identical-content collisions pass (covered byAssetNoOverwriteSameContent).
Extended reasoning...
Overview
Five HTML-bundler fixes across three Rust files (HTMLScanner.rs, bundle_v2.rs, generateCompileResultForHtmlChunk.rs, net +86 in src/) plus ~150 lines of new itBundled tests: protocol-relative URL detection, a new SrcSetIter tokenizer used by both scan and rewrite passes, ?# suffix preservation on rewritten asset URLs, widening the CSS-inline copy-forcing gate from JS-only to any non-CSS importer, and a new asset output-path collision guard in process_files_to_copy.
Security risks
None identified. The inputs are project-local build inputs (HTML attribute values, on-disk asset paths); no network, auth, or privilege surfaces. SrcSetIter is bounds-safe (all indexing via .get()/.first()/computed positions on &[u8]).
Level of scrutiny
Medium-high. The bundler is production-critical, bundle_v2.rs is core, and this PR both changes a shared reachability gate (affects which assets are emitted for all builds, not just HTML) and introduces new error-producing behavior (the collision check). SrcSetIter is a hand-written mini-parser. Most importantly, the tip commit 0e4276e is a broad simplification pass that landed after every prior review round — the Rewrite enum + next_record_url shape, the compacted iterator, and the single-pass collision message are all newer than the resolved threads.
Other factors
- All five fixes have failing-on-main tests; the mechgate evidence shows debug+ASAN and release both green.
- Prior review rounds surfaced and resolved: srcset edge-case coverage, dev-server suffix arm, per-candidate
Removesemantics, sibling-comment drift, WHATWG paren-depth. One pre-existing-behavior nit (non-srcsetRemoveonimg[src]) was explicitly deferred with rationale. - The 0e4276e collision message dropped the per-input
from input …lines that the chunk-side sibling (generateChunksInParallel.rs) prints — an intentional simplification per the author, but a wording divergence a maintainer may want to weigh. - The author explicitly offered to split into per-fix PRs; a human can decide whether to take that or land as-is.
Not a rubber-stamp candidate: five coupled fixes + a late refactor of the reviewed code is exactly the shape REVIEW.md asks a human to look at.
|
Status note on fix 4 (asset inlined in CSS and also referenced from HTML is never emitted, HTML keeps the raw head -c 3000 /dev/urandom > logo.png
printf '.foo { background: url(./logo.png) }\n' > style.css
printf '<link rel="stylesheet" href="./style.css"><img src="./logo.png">' > index.html
bun build index.html --outdir out && ls out && grep -o 'src="[^"]*"' out/index.html
# out/ has no logo-*.png, index.html still says src="./logo.png"
The branch now conflicts with main in two places: |
|
Overlap update: the |
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-07-27. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Five fixes to how HTML entrypoints classify asset URLs and emit them, so the HTML build's asset-URL contract matches the CSS printer's.
Repro
Cause
HTMLScanner::create_import_recordrewrites any leading/as a rooted project path, so//cdn/x.jsnever reaches the resolver's ownstarts_with("//")external rule.TAG_HANDLERSimg[srcset]/source[srcset]push the whole attribute through the single-URL path.HTMLLoader::on_tagreplaces the whole attribute value with the unique key after the resolver already stripped?#to find the file. The CSS printer re-appends the suffix fromrecord.original_path; HTML didn't.find_reachable_filescounts only JS importers as copy-forcing, so an asset inlined in CSS and referenced only from HTML has its unique key cleared and the HTML rewrite is a silent no-op.process_files_to_copypushes each assetOutputFilewith no output-path uniqueness check; the chunk-side "Multiple files share the same output path" guard only sees chunks.Fix
HTMLScanner: skip the rooted-path branch when the second byte is also/.HTMLScanner+HTMLLoader: sharedSrcSetIterwalks the WHATWG image-candidate grammar; scan creates one import record per candidate, rewrite rebuilds the attribute with descriptors preserved. Both passes drive the same iterator so record counts stay 1:1.HTMLLoader::rewrite_one_url: re-append the source URL's?#suffix to the emitted reference (fragment only fordata:URIs), same ascss/printer.rs.find_reachable_files: any non-CSS importer forces the asset to be emitted.HTMLLoaderfalls back to thedata:URI when no unique key exists instead of leaving the raw source path.process_files_to_copy: map over asset output paths and raiseDuplicateOutputPathwith the existing error/note wording when two distinct content hashes collide; identical-content collisions are benign.Verification
All five fail on
main(4 inbundler_html.test.ts,naming/AssetNoOverwritewas previouslytodo: true) and pass with this change. The fullbundler_html,bundler_naming,bundler_loader,bundler_edgecase,bundler_html_serverandhtml-import-manifestsuites pass.Consolidates #36007, #36008, #36012 (the first three fixes) and adds the two emit-contract fixes that had no open PR.
[review] gate passed · iteration 3 · 5 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 4 passed · 0 rejected · iteration 3
evidence per changed file