Skip to content
Closed
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/bundler/HTMLScanner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,8 @@ pub(crate) const TAG_HANDLERS: [TagHandler; 16] = [
TagHandler::new("script[src]", "src", ImportKind::Stmt),
// CSS Stylesheets
TagHandler::new("link[rel='stylesheet'][href]", "href", ImportKind::At),
// CSS Assets
TagHandler::new("link[as='style'][href]", "href", ImportKind::At),
// CSS preloads (fetch hint only; not merged into the page stylesheet)
TagHandler::new("link[as='style'][href]", "href", ImportKind::Url),
Comment thread
robobun marked this conversation as resolved.
Resolved
// Font files
TagHandler::new(
"link[as='font'][href], link[type^='font/'][href]",
Expand Down
5 changes: 5 additions & 0 deletions src/bundler/LinkerContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,9 @@ impl<'a> LinkerContext<'a> {
// SAFETY: field-disjoint scalar read; `transpiler` is itself a `*mut`.
let dyn_entry_points =
unsafe { &mut *core::ptr::addr_of_mut!((*bundle).dynamic_import_entry_points) };
// SAFETY: field-disjoint with `self` and with `dyn_entry_points`.
let html_preload_css_entry_points =
unsafe { &mut *core::ptr::addr_of_mut!((*bundle).html_preload_css_entry_points) };

// SAFETY: `bundle.transpiler` is a `*mut Transpiler` backref valid for
// the bundle's lifetime; `resolver`/`log`/`options` are stable fields.
Expand Down Expand Up @@ -527,10 +530,12 @@ impl<'a> LinkerContext<'a> {
sources,
server_component_boundaries,
dyn_entry_points.keys(),
html_preload_css_entry_points.keys(),
// SAFETY: parse_graph backref
unsafe { &(*self.parse_graph).entry_point_original_names },
)?;
dyn_entry_points.clear_retaining_capacity();
html_preload_css_entry_points.clear_retaining_capacity();

let runtime_named_exports =
&self.graph.ast.items_named_exports()[Index::RUNTIME.get() as usize];
Expand Down
20 changes: 19 additions & 1 deletion src/bundler/LinkerGraph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ pub mod entry_point {
UserSpecified,
DynamicImport,
Html,
/// A CSS file referenced from HTML via `<link rel="preload" as="style">`.
HtmlPreload,
}
impl Kind {
#[inline]
Expand Down Expand Up @@ -634,6 +636,7 @@ impl<'a> LinkerGraph<'a> {
sources: &[bun_ast::Source],
server_component_boundaries: &server_component_boundary::List,
dynamic_import_entry_points: &[index::Int],
html_preload_css_entry_points: &[index::Int],
entry_point_original_names: &IndexStringMap,
) -> Result<(), crate::Error> {
let scb = server_component_boundaries.slice();
Expand All @@ -657,7 +660,8 @@ impl<'a> LinkerGraph<'a> {
self.entry_points.set_capacity(
entry_points.len()
+ server_component_boundaries.list.len()
+ dynamic_import_entry_points.len(),
+ dynamic_import_entry_points.len()
+ html_preload_css_entry_points.len(),
)?;
// SAFETY: capacity reserved; columns initialized below.
unsafe { self.entry_points.set_len(entry_points.len()) };
Expand Down Expand Up @@ -711,6 +715,20 @@ impl<'a> LinkerGraph<'a> {
});
}

for &id in html_preload_css_entry_points {
if entry_point_kinds[id as usize] != entry_point::Kind::None {
continue;
}

let source = &sources[id as usize];
entry_point_kinds[id as usize] = entry_point::Kind::HtmlPreload;

self.entry_points.append_assume_capacity(EntryPoint {
source_index: id,
output_path: RawSlice::new(source.path.text),
});
}

let import_records_len = self.ast.items_import_records().len();
self.meta.set_capacity(import_records_len)?;
// Fill each slot with `Default`.
Expand Down
17 changes: 17 additions & 0 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ pub struct BundleV2<'a> {
/// See the comment in `Chunk.OutputPiece`.
pub unique_key: u64,
pub dynamic_import_entry_points: ArrayHashMap<IndexInt, ()>,
/// `<link rel="preload" as="style">` targets; each gets its own CSS chunk.
pub html_preload_css_entry_points: ArrayHashMap<IndexInt, ()>,

pub finalizers: Vec<ExternalFreeFunction>,

Expand Down Expand Up @@ -1639,6 +1641,7 @@ pub mod bv2_impl {
pub all_urls_for_css: &'a [&'a [u8]],
pub redirects: &'a [u32],
pub dynamic_import_entry_points: &'a mut ArrayHashMap<IndexInt, ()>,
pub html_preload_css_entry_points: &'a mut ArrayHashMap<IndexInt, ()>,
/// Files which are Server Component Boundaries
pub scb_bitset: Option<DynamicBitSetUnmanaged>,
pub scb_list: server_component_boundary::Slice<'a>,
Expand Down Expand Up @@ -1746,6 +1749,7 @@ pub mod bv2_impl {

let is_js = self.all_loaders[source_index.get() as usize].is_javascript_like();
let is_css = self.all_loaders[source_index.get() as usize].is_css();
let is_html = self.all_loaders[source_index.get() as usize] == Loader::Html;

let import_record_list_id = source_index;
let mut has_redirect = false;
Expand Down Expand Up @@ -1810,6 +1814,15 @@ pub mod bv2_impl {

let next_source = import_record.source_index;
let kind_is_dynamic = import_record.kind == ImportKind::Dynamic;
if is_html
&& import_record.kind == ImportKind::Url
&& next_source.is_valid()
&& self.all_loaders[next_source.get() as usize].is_css()
{
self.html_preload_css_entry_points
.put(next_source.get(), ())
.expect("unreachable");
}
self.stack.push(ReachFrame::Enter {
source_index: next_source,
was_dynamic_import: CHECK_DYNAMIC_IMPORTS && kind_is_dynamic,
Expand Down Expand Up @@ -1888,6 +1901,7 @@ pub mod bv2_impl {
DynamicBitSetUnmanaged::init_empty(self.graph.input_files.len())?;

self.dynamic_import_entry_points = ArrayHashMap::new();
self.html_preload_css_entry_points = ArrayHashMap::new();

// reshaped for borrowck — hoist the values that would
// otherwise re-borrow `self`/`self.graph` while the visitor holds
Expand Down Expand Up @@ -1915,6 +1929,7 @@ pub mod bv2_impl {
all_loaders: self.graph.input_files.items_loader(),
all_urls_for_css,
dynamic_import_entry_points: &mut self.dynamic_import_entry_points,
html_preload_css_entry_points: &mut self.html_preload_css_entry_points,
scb_bitset,
scb_list,
additional_files_imported_by_js_and_inlined_in_css:
Expand Down Expand Up @@ -2727,6 +2742,7 @@ pub mod bv2_impl {
free_list: Vec::new(),
unique_key: 0,
dynamic_import_entry_points: ArrayHashMap::new(),
html_preload_css_entry_points: ArrayHashMap::new(),
finalizers: Vec::new(),
drain_defer_task: DeferredBatchTask::default(),
asynchronous: false,
Expand Down Expand Up @@ -5109,6 +5125,7 @@ pub mod bv2_impl {
/* arena: help_catch_memory_issues — no-op (mimalloc TLH check) */

self.dynamic_import_entry_points = ArrayHashMap::new();
self.html_preload_css_entry_points = ArrayHashMap::new();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let mut html_files: ArrayHashMap<Index, ()> = ArrayHashMap::new();

// Separate non-failing files into two lists: JS and CSS
Expand Down
18 changes: 17 additions & 1 deletion src/bundler/linker_context/computeChunks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@
let mut html_chunks: ArrayHashMap<&[u8], Chunk> = ArrayHashMap::new();
let loaders = parse_graph.input_files.items_loader();
let ast_targets = this.graph.ast.items_target();
// (source_index, pre-sort css_chunks index) per HtmlPreload entry; remapped below.
let mut html_preload_css_chunk_indices: Vec<(IndexInt, u32)> = Vec::new();

let code_splitting = this.graph.code_splitting;
let could_be_browser_target_from_server_build = this.options.target.is_server_side()
Expand Down Expand Up @@ -146,9 +148,11 @@
temp,
&[Index::init(source_index)],
);
let is_html_preload = this.graph.files.items_entry_point_kind()[source_index as usize]
== crate::EntryPoint::Kind::HtmlPreload;
// Create a chunk for the entry point here to ensure that the chunk is
// always generated even if the resulting file is empty
let hash_to_use = if !this.options.css_chunking {
let hash_to_use = if !this.options.css_chunking && !is_html_preload {
bun_wyhash::hash(
temp.alloc_slice_copy(entry_bits.bytes(this.graph.entry_points.len())),
)
Expand All @@ -161,6 +165,12 @@
hasher.final_()
};
let css_chunk_entry = css_chunks.get_or_put(hash_to_use)?;
if is_html_preload {
html_preload_css_chunk_indices.push((
source_index,
u32::try_from(css_chunk_entry.index).expect("int cast"),
));
}

Check warning on line 173 in src/bundler/linker_context/computeChunks.rs

View check run for this annotation

Claude / Claude Code Review

HtmlPreload/page-CSS dedup only works when the preloaded file is the page's only stylesheet

The content-hash dedup only makes the preload and the injected `rel="stylesheet"` point at the same output when the preloaded file is the page's **only** applied stylesheet. With `<link rel="preload" as="style" href="./app.css">` + `<link rel="stylesheet" href="./app.css">` + `<link rel="stylesheet" href="./other.css">`, the HtmlPreload chunk hashes `[app]` while the page chunk hashes `[app, other]`, so two chunks are emitted and the preload href points at a file the page never applies (Chrome l
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
if !css_chunk_entry.found_existing {
// const css_chunk_entry = try js_chunks.getOrPut();
let order_len = order.len() as usize;
Expand Down Expand Up @@ -483,6 +493,9 @@
}
}
}
for (_, idx) in html_preload_css_chunk_indices.iter_mut() {
*idx = remapped_css_indexes[*idx as usize];
}
}

// We don't care about the order of the HTML chunks that have no JS chunks.
Expand Down Expand Up @@ -513,6 +526,9 @@
u32::try_from(chunk_id).expect("int cast");
}
}
for &(source, chunk_id) in html_preload_css_chunk_indices.iter() {
entry_point_chunk_indices[source as usize] = chunk_id;
}

// Determine the order of JS files (and parts) within the chunk ahead of time
find_all_imported_parts_in_js_order(this, chunks)?;
Expand Down
8 changes: 7 additions & 1 deletion src/bundler/linker_context/findImportedCSSFilesInJSOrder.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::mal_prelude::*;
use bun_alloc::Arena;
use bun_ast::ImportRecord;
use bun_ast::{ImportKind, ImportRecord};
use bun_collections::VecExt;

use crate::{Index, LinkerContext};
Expand Down Expand Up @@ -76,6 +76,12 @@ pub fn find_imported_css_files_in_js_order(
if record.source_index.is_valid()
&& !visited.is_set(record.source_index.get() as usize)
{
// Preloaded CSS is chunked via `html_preload_css_entry_points`.
if record.kind == ImportKind::Url
&& all_loaders[record.source_index.get() as usize].is_css()
{
continue;
}
stack.push(Frame::Enter(record.source_index));
}
}
Expand Down
27 changes: 26 additions & 1 deletion src/bundler/linker_context/generateCompileResultForHtmlChunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ impl<'a> HTMLProcessorHandler for HTMLLoader<'a> {
element: &mut Element<'_, '_>,
_path: &[u8],
url_attribute: &[u8],
_kind: ImportKind,
kind: ImportKind,
) {
if self.current_import_record_index as usize >= self.import_records.len() {
bun_core::Output::panic(format_args!(
Expand Down Expand Up @@ -184,6 +184,31 @@ impl<'a> HTMLProcessorHandler for HTMLLoader<'a> {
return;
}

if loader.is_css() && kind == ImportKind::Url {
// `<link rel="preload" as="style">`: rewrite href to the file's own CSS chunk.
let chunk_index = self.linker.graph.files.items_entry_point_chunk_index()
[import_record.source_index.get() as usize];
// SAFETY: `self.chunks` raw `*mut [Chunk]` valid for the link step.
let chunks = unsafe { &*self.chunks };
debug_assert!(
(chunk_index as usize) < chunks.len()
&& chunks[chunk_index as usize].content.is_css(),
"html_preload_css_chunk_indices did not assign a CSS chunk",
);
if (chunk_index as usize) < chunks.len()
&& chunks[chunk_index as usize].content.is_css()
{
set_attribute(
element,
url_attribute,
chunks[chunk_index as usize].unique_key,
);
} else {
element.remove();
}
return;
}
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved

if loader.is_javascript_like() || loader.is_css() {
// Remove the original non-external tags
element.remove();
Expand Down
Loading
Loading