Repository navigation
Conversation
…sset A <link rel="preload" as="style"> is a fetch-only hint; the stylesheet is not applied until the page does so itself (the common async-CSS pattern is onload="this.rel='stylesheet'"). The HTML bundler was treating this the same as rel="stylesheet": the CSS was merged into the page's applied CSS chunk, the preload tag was deleted, and a rel="stylesheet" link was injected, so styles the source page never applied were now render-applied in the built output. Map link[as="style"][href] to ImportKind::Url (matching as="font" / as="image" preloads) and drop the CSS exclusion from the HTML url-asset loader override so the file is emitted standalone with its href rewritten, leaving the preload tag in place.
WalkthroughChangesHTML HTML preload CSS flow
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 8:06 PM PT - Jul 26th, 2026
❌ @autofix-ci[bot], your commit 9b2d4e1 has 1 failures in
🧪 To try this PR locally: bunx bun-pr 36011That installs a local version of the PR into your bun-36011 --bun |
The first iteration forced the preloaded file through Loader::File, which
emitted it byte-for-byte and left @import/url() references unresolved.
Instead, keep the CSS loader so the file's own dependency graph is
walked, but give it its own CSS chunk rather than folding it into the
page's applied stylesheet:
- ReachableFileVisitor records CSS files reached from HTML via a
url-kind import in html_preload_css_entry_points.
- LinkerGraph::load appends those as entry points (new
entry_point::Kind::HtmlPreload), mirroring the dynamic-import path,
so computeChunks emits each as a standalone Content::Css chunk with
@import/url() resolved.
- findImportedCSSFilesInJSOrder skips url-kind records whose target is
CSS so the preloaded file is not also merged into the page bundle.
- generateCompileResultForHtmlChunk rewrites the preload href to that
chunk's unique key instead of removing the tag.
This is order-independent when the same file is referenced by both a
preload and a rel="stylesheet" link, and the applied stylesheet keeps
going through the CSS graph in that case.
When the same file is referenced by both rel="preload" as="style" and rel="stylesheet", the preload entry point and the page's CSS chunk have identical import order. Key the HtmlPreload chunk by content hash so it dedupes into the page chunk, and record the (source_index, chunk_index) mapping explicitly so entry_point_chunk_indices is set even when the deduped chunk's own entry_point.source_index is the HTML file. The HTML rewrite now writes the same href to the preload and the injected stylesheet link, and debug_asserts the looked-up chunk is CSS instead of silently leaving a stale or wrong href. Tests: strengthen the shared-file tests to assert preload and stylesheet hrefs match, add --production variants, and make the css-deps test assert the resolved url() data URI contents.
… HTML mode In --compile --target=browser builds a chunk unique_key is replaced by the chunk's raw bytes, so writing it into an href would inline the CSS text into the attribute value. A single-file bundle has no separate file to preload, so remove the tag instead. Covered by a new test in standalone.test.ts.
When the page applies other stylesheets besides the preloaded one, the preload gets its own output containing exactly what the source declared so an onload swap applies only that file, and the page bundle separately contains every applied stylesheet. The bytes are duplicated across the two outputs; that is the tradeoff for preserving the source declaration.
A fresh HtmlPreload CSS chunk previously had entry_bits containing only its own appended entry bit, which is beyond the parse-graph entry_points count that HTMLImportManifest::write sizes its intersection bitset to. In server-target builds with >=2 HTML imports the preload output was emitted but omitted from the owning page's manifest. Use the CSS file's full file entry_bits (which mark every entry point that reaches it, including the HTML page) so the manifest's has_intersection check associates the chunk with the right page. Covered by html-import/preload-as-style-in-manifest.
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 `@src/bundler/bundle_v2.rs`:
- Around line 5127-5128: Update the CSS-target handling in
finish_from_bake_dev_server so preload-style CSS imports are excluded from
start.css_entry_points, matching the existing ImportKind::Url filtering used by
the other CSS traversal path. Preserve registration of non-preload CSS targets
and the surrounding entry-point reset behavior.
🪄 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: dab90309-28bc-4895-8f1d-84efaa2ce936
📒 Files selected for processing (10)
src/bundler/HTMLScanner.rssrc/bundler/LinkerContext.rssrc/bundler/LinkerGraph.rssrc/bundler/bundle_v2.rssrc/bundler/linker_context/computeChunks.rssrc/bundler/linker_context/findImportedCSSFilesInJSOrder.rssrc/bundler/linker_context/generateCompileResultForHtmlChunk.rstest/bundler/bundler_html.test.tstest/bundler/html-import-manifest.test.tstest/bundler/standalone.test.ts
640f1b5 set entry_bits = file bits only when creating a fresh chunk. When the HtmlPreload entry content-hash-dedupes into a page CSS chunk another entry already created, the existing chunk kept only that page's bits, so a page that only preloads the file was omitted from its own HTML-import manifest while its emitted preload href still pointed at the chunk. OR the file's entry_bits into the existing chunk so every referencing page's manifest lists it. Covered by html-import/preload-as-style-in-manifest-deduped.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/bundler/linker_context/computeChunks.rs (1)
168-178: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winPreserve manifest ownership when a preload creates the deduplicated chunk first.
If a preload of
preload.cssis processed before a normal stylesheetstyle.csswith identical content, the stylesheet hitsfound_existingwhileis_html_preloadis false. Its entry bits are never merged, so its HTML import manifest omits the shared CSS chunk.
src/bundler/linker_context/computeChunks.rs#L168-L178: mergeentry_bitswhen either the incoming entry or the existing chunk’s entry point isHtmlPreload.test/bundler/html-import-manifest.test.ts#L406-L445: add the reverse-order case using distinct CSS files with identical content; assert both manifests contain the same CSS chunk.🤖 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/bundler/linker_context/computeChunks.rs` around lines 168 - 178, The deduplication path only merges entry bits when the incoming chunk is an HTML preload, so reverse-order deduplication loses manifest ownership. In src/bundler/linker_context/computeChunks.rs:168-178, update the found_existing handling around css_chunk_entry so it merges entry_bits when either the incoming entry or the existing chunk’s entry point is HtmlPreload. In test/bundler/html-import-manifest.test.ts:406-445, add the reverse-order case with distinct identical-content CSS files and assert both HTML manifests reference the same CSS chunk.
🤖 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.
Outside diff comments:
In `@src/bundler/linker_context/computeChunks.rs`:
- Around line 168-178: The deduplication path only merges entry bits when the
incoming chunk is an HTML preload, so reverse-order deduplication loses manifest
ownership. In src/bundler/linker_context/computeChunks.rs:168-178, update the
found_existing handling around css_chunk_entry so it merges entry_bits when
either the incoming entry or the existing chunk’s entry point is HtmlPreload. In
test/bundler/html-import-manifest.test.ts:406-445, add the reverse-order case
with distinct identical-content CSS files and assert both HTML manifests
reference the same CSS chunk.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 31b97712-3a48-4f83-9ac9-14969d7fdc21
📒 Files selected for processing (2)
src/bundler/linker_context/computeChunks.rstest/bundler/html-import-manifest.test.ts
|
Re the outside-diff finding on |
There was a problem hiding this comment.
No new issues found after four review iterations — the earlier findings (standalone-HTML href inlining, --production chunk-index mapping, HTMLImportManifest entry_bits on fresh and deduped chunks) are all addressed with tests. Deferring because this threads a new HtmlPreload entry-point kind through the linker's chunk computation, and the shared-with-extra-stylesheet semantics (preload gets its own output, bytes duplicated) is a user-facing bundler design call worth a maintainer sign-off.
What was reviewed:
computeChunks: content-hash keying, post-sort index remap, and thefound_existingentry_bits OR — checked that HtmlPreload entries always run after page entries so the dedup ordering assumption holds.generateCompileResultForHtmlChunk: the new branch guardscompile_to_standalone_htmland falls back toremove()in release when the chunk lookup is not CSS.findImportedCSSFilesInJSOrderguard is scoped toUrl+CSS so JS-imported CSS andrel=stylesheet(At) are unaffected.- Dev-server path is intentionally unchanged (pre-existing gap, noted in PR description).
Extended reasoning...
Overview
The PR changes how bun build handles <link rel="preload" as="style"> in HTML entry points: instead of folding the referenced CSS into the page's applied stylesheet bundle, it emits a standalone CSS chunk and rewrites the preload's href to point at it. This touches the HTML scanner tag table, BundleV2's reachable-file visitor, LinkerGraph::load (new entry_point::Kind::HtmlPreload), computeChunks (content-hash dedup + explicit chunk-index recording + entry_bits merge), findImportedCSSFilesInJSOrder (skip url-kind CSS), and generateCompileResultForHtmlChunk (rewrite href / drop under --compile). ~115 lines of Rust across 7 bundler files plus ~320 lines of new tests across three test files.
Security risks
None identified. The change is bundler output-shape logic; no new parsing of untrusted input, no path handling changes, no network/auth surface.
Level of scrutiny
High. computeChunks is core linker logic where chunk-index bookkeeping errors surface as wrong hrefs or missing manifest entries rather than crashes — exactly what the four prior review iterations caught (standalone-HTML raw-CSS-in-href, --production chunk-0 misroute, manifest omission on fresh chunks, manifest omission on deduped chunks). Each was fixed and covered by a targeted test. The remaining design decision — that a file referenced by both preload and stylesheet alongside other stylesheets ships its bytes twice — is pinned as intentional by html/preload-as-style-shared-with-extra-stylesheet, and the rationale (preserve source-declared preload target for the onload swap pattern) is defensible, but it's a user-visible bundler semantics choice.
Other factors
- All prior inline findings (mine and CodeRabbit's) are resolved; the dev-server gap is explicitly scoped out with a stated reason.
- Test coverage is thorough for the build path: both tag orders × both
--productionstates,@import/url()resolution, standalone--compile, and two HTML-import-manifest scenarios (fresh chunk and deduped chunk across pages). - I re-checked the post-sort remap:
html_preload_css_chunk_indicesis only remapped insideif css_chunks.count() > 0, which is guaranteed whenever an HtmlPreload entry exists. The explicitentry_point_chunk_indiceswrite after the main loop correctly covers the deduped case where the chunk's ownentry_point.source_index()is the HTML page rather than the CSS file. - Not approving because this introduces a new entry-point kind and chunk-dedup path in the linker — the kind of change REVIEW.md flags for maintainer agreement ("new cross-cutting abstractions need maintainer agreement"), and the four-iteration history shows the interaction surface is subtle.
|
CI build 82951: 193/197 jobs passed. The only hard failure is |
|
Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-26, it conflicts with main, and its last CI run failed. This is not a judgment on the fix itself. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main. |
Problem
<link rel="preload" as="style" href="./x.css">is a fetch-only hint: the stylesheet is not applied until the page does so itself (the common async-CSS pattern isonload="this.rel='stylesheet'").bun build ./index.htmlwas treating this the same asrel="stylesheet": the referenced CSS was merged into the page's applied CSS chunk, the preload tag was deleted, and arel="stylesheet"link was injected. Styles the source page never applied were now render-applied in the built output, and there was nothing left to swap to.Before:
Cause
TAG_HANDLERSinsrc/bundler/HTMLScanner.rsmappedlink[as='style'][href]toImportKind::At, the same kind aslink[rel='stylesheet'], so the file was folded into the page's CSS chunk byfindImportedCSSFilesInJSOrderand the original tag was removed bygenerateCompileResultForHtmlChunk.Fix
Map
link[as='style']toImportKind::Urlso it is distinguishable from an applied stylesheet, and give the referenced file its own CSS chunk instead of merging it:ReachableFileVisitorrecords CSS files reached from HTML via a url-kind record inhtml_preload_css_entry_points.LinkerGraph::loadappends those as entry points (newentry_point::Kind::HtmlPreload), mirroring the dynamic-import path, socomputeChunksemits each as a standaloneContent::Csschunk with@import/url()resolved.computeChunkscontent-hashes theHtmlPreloadchunk key and recordsentry_point_chunk_indicesfor the preload source explicitly. When the same file is also referenced viarel="stylesheet", the two chunks dedupe and both the preload href and the injected stylesheet href point at the same output.findImportedCSSFilesInJSOrderskips url-kind records whose target is CSS so the preload is not also folded into the page bundle.generateCompileResultForHtmlChunkrewrites the preloadhrefto that chunk's unique key instead of removing the tag, anddebug_asserts the looked-up chunk is CSS. Under--compile --target=browser(standalone single-file output) the tag is dropped: there is no separate file to preload and writing a chunk key into an href would inline raw CSS into the attribute.The preloaded CSS keeps going through the CSS loader, so its own
@importandurl()dependencies are resolved and emitted. This is order-independent when the same file is referenced by bothrel="preload" as="style"andrel="stylesheet", in both default and--productionbuilds.Dev server is unchanged: it already removed the preload tag before this change and still does;
computeChunksdoes not run on that path so the chunk lookup is not available. That is the same semantic gap as the original bug and can be fixed separately.After:
Verification
New tests in
test/bundler/bundler_html.test.ts:html/preload-as-style: page with both an applied stylesheet and a preload; the preload tag survives with a hashed href, the preloaded file is emitted standalone, and the applied bundle does not contain the preloaded rules.html/preload-as-style-only: page with only a preload gets no injectedrel="stylesheet".html/preload-as-style-css-deps:@importis inlined andurl()is resolved (data-URI content asserted) in the standalone output.html/preload-as-style-shared-{preload,stylesheet}-first{,-production}: the same file referenced by both a preload and a stylesheet resolves to one output file, with both hrefs equal, in both tag orders and in both default and--productionbuilds.And in
test/bundler/standalone.test.ts:drops <link rel=preload as=style>:--compile --target=browserremoves the preload tag rather than inlining CSS into its href.All eight fail on current canary and pass with this change.
bundler_html.test.ts,bundler_html_server.test.ts,html-import-manifest.test.ts,standalone.test.ts,esbuild/css.test.ts, andesbuild/splitting.test.tscontinue to pass.[review] gate passed · iteration 4 · 10 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 7 passed · 0 rejected · iteration 4
evidence per changed file