Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
128 changes: 94 additions & 34 deletions src/bundler/HTMLScanner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,40 +32,40 @@ impl<'a> HTMLScanner<'a> {

impl<'a> HTMLScanner<'a> {
fn create_import_record(&mut self, input_path: &[u8], kind: ImportKind) -> Result<(), Error> {
// In HTML, sometimes people do /src/index.js
// In that case, we don't want to use the absolute filesystem path, we want to use the path relative to the project root
let path_to_use: &[u8] = if input_path.len() > 1 && input_path[0] == b'/' {
resolve_path::join_abs_string::<platform::Auto>(
fs::FileSystem::instance().top_level_dir,
&[&input_path[1..]],
)
}
// Check if imports to (e.g) "App.tsx" are actually relative imoprts w/o the "./"
else if input_path.len() > 2 && input_path[0] != b'.' && input_path[1] != b'/' {
'blk: {
let Some(index_of_dot) = input_path.iter().rposition(|&b| b == b'.') else {
break 'blk input_path;
};
let ext = &input_path[index_of_dot..];
if ext.len() > 4 {
break 'blk input_path;
}
// /foo/bar/index.html -> /foo/bar
let dirname = resolve_path::dirname::<platform::Auto>(self.source.path.text());
if dirname.is_empty() {
break 'blk input_path;
}
let resolved =
resolve_path::join_abs_string_z::<platform::Auto>(dirname, &[input_path]);
if sys::exists_z(resolved) {
resolved.as_bytes()
} else {
input_path
}
// `/src/x.js` is project-root-relative; `//host/x.js` is protocol-relative (external).
let path_to_use: &[u8] =
if input_path.len() > 1 && input_path[0] == b'/' && input_path[1] != b'/' {
resolve_path::join_abs_string::<platform::Auto>(
fs::FileSystem::instance().top_level_dir,
&[&input_path[1..]],
)
}
} else {
input_path
};
// Check if imports to (e.g) "App.tsx" are actually relative imoprts w/o the "./"
else if input_path.len() > 2 && input_path[0] != b'.' && input_path[1] != b'/' {
'blk: {
let Some(index_of_dot) = input_path.iter().rposition(|&b| b == b'.') else {
break 'blk input_path;
};
let ext = &input_path[index_of_dot..];
if ext.len() > 4 {
break 'blk input_path;
}
// /foo/bar/index.html -> /foo/bar
let dirname = resolve_path::dirname::<platform::Auto>(self.source.path.text());
if dirname.is_empty() {
break 'blk input_path;
}
let resolved =
resolve_path::join_abs_string_z::<platform::Auto>(dirname, &[input_path]);
if sys::exists_z(resolved) {
resolved.as_bytes()
} else {
input_path
}
}
} else {
input_path
};

let owned: &'static [u8] =
Box::leak(AstAlloc::vec_from_slice(path_to_use).into_boxed_slice());
Expand Down Expand Up @@ -103,7 +103,12 @@ impl<'a> HTMLScanner<'a> {
url_attribute: &[u8],
kind: ImportKind,
) {
let _ = url_attribute;
if url_attribute == b"srcset" {
for (url, _) in SrcSetIter::new(path) {
let _ = self.create_import_record(url, kind);
}
return;
}
let _ = self.create_import_record(path, kind);
}

Expand Down Expand Up @@ -164,6 +169,61 @@ impl<'a> HTMLProcessorHandler for HTMLScanner<'a> {

pub(crate) struct HTMLProcessor<T, const VISIT_DOCUMENT_TAGS: bool>(PhantomData<T>);

/// `(url, descriptor)` per `srcset` candidate; scan and rewrite both use this so their record counts stay 1:1.
pub(crate) struct SrcSetIter<'a>(&'a [u8]);

impl<'a> SrcSetIter<'a> {
pub(crate) fn new(value: &'a [u8]) -> Self {
Self(value)
}
}

impl<'a> Iterator for SrcSetIter<'a> {
type Item = (&'a [u8], &'a [u8]);
fn next(&mut self) -> Option<Self::Item> {
let ws = u8::is_ascii_whitespace;
let s = &mut self.0;
while s.first().is_some_and(|b| ws(b) || *b == b',') {
*s = &s[1..];
}
if s.is_empty() {
return None;
}
let url_end = s.iter().position(ws).unwrap_or(s.len());
let url_trim = s[..url_end]
.iter()
.rposition(|&b| b != b',')
.map_or(0, |i| i + 1);
let url = &s[..url_trim];
if url_trim < url_end {
*s = &s[url_end..];
return Some((url, b""));
}
let mut i = url_end;
while s.get(i).is_some_and(ws) {
i += 1;
}
let desc_start = i;
let mut depth: u32 = 0;
while let Some(&b) = s.get(i) {
match b {
b',' if depth == 0 => break,
b'(' => depth += 1,
b')' => depth = depth.saturating_sub(1),
_ => {}
}
i += 1;
}
let desc = &s[desc_start
..s[desc_start..i]
.iter()
.rposition(|b| !ws(b))
.map_or(desc_start, |j| desc_start + j + 1)];
*s = s.get(i + 1..).unwrap_or(b"");
Some((url, desc))
}
}

#[derive(Clone, Copy)]
pub struct TagHandler {
/// CSS selector to match elements
Expand Down
40 changes: 29 additions & 11 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1643,7 +1643,7 @@ pub mod bv2_impl {
pub scb_bitset: Option<DynamicBitSetUnmanaged>,
pub scb_list: server_component_boundary::Slice<'a>,

/// Files which are imported by JS and inlined in CSS
/// Files inlined in CSS and also imported by a non-CSS source (JS, HTML)
pub additional_files_imported_by_js_and_inlined_in_css: &'a mut DynamicBitSetUnmanaged,
/// Files which are imported by CSS and inlined in CSS
pub additional_files_imported_by_css_and_inlined: &'a mut DynamicBitSetUnmanaged,
Expand Down Expand Up @@ -1744,7 +1744,6 @@ 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 import_record_list_id = source_index;
Expand Down Expand Up @@ -1795,17 +1794,19 @@ pub mod bv2_impl {
let import_record = &self.all_import_records
[import_record_list_id.get() as usize]
.as_slice()[ir_idx];
// Mark if the file is imported by JS and its URL is inlined for CSS
// CSS inlines as data:; any non-CSS importer (JS, HTML) forces on-disk emission.
let is_inlined = import_record.source_index.is_valid()
&& !self.all_urls_for_css
[import_record.source_index.get() as usize]
.is_empty();
if is_js && is_inlined {
self.additional_files_imported_by_js_and_inlined_in_css
.set(import_record.source_index.get() as usize);
} else if is_css && is_inlined {
self.additional_files_imported_by_css_and_inlined
.set(import_record.source_index.get() as usize);
if is_inlined {
if is_css {
self.additional_files_imported_by_css_and_inlined
.set(import_record.source_index.get() as usize);
} else {
self.additional_files_imported_by_js_and_inlined_in_css
.set(import_record.source_index.get() as usize);
}
Comment thread
robobun marked this conversation as resolved.
Resolved
}

let next_source = import_record.source_index;
Expand Down Expand Up @@ -1976,8 +1977,7 @@ pub mod bv2_impl {
let content_hashes: &mut [u64] = input_files_cols.content_hash_for_additional_file;
for (index, url_for_css) in all_urls_for_css.iter().enumerate() {
if !url_for_css.is_empty() {
// We like to inline additional files in CSS if they fit a size threshold
// If we do inline a file in CSS, and it is not imported by JS, then we don't need to copy the additional file into the output directory
// A file inlined in CSS and not imported by any non-CSS source needn't be copied to the output directory.
if additional_files_imported_by_css_and_inlined.is_set(index)
&& !additional_files_imported_by_js_and_inlined_in_css.is_set(index)
{
Expand Down Expand Up @@ -4169,6 +4169,24 @@ pub mod bv2_impl {
}
}

// Distinct-content asset collisions on one output path are a hard error; identical content is benign.
let mut seen: bun_collections::StringHashMap<u64> = Default::default();
for out in &additional_output_files {
let gop = seen.get_or_put(&out.dest_path)?;
if gop.found_existing && *gop.value_ptr != out.hash {
self.transpiler.log_mut().add_error_fmt(
None,
bun_ast::Loc::EMPTY,
format_args!(
"Multiple files share the same output path: {}\nConsider adding \"[hash]\" to --asset-naming",
bstr::BStr::new(&out.dest_path),
),
);
return Err(Error::DuplicateOutputPath);
}
*gop.value_ptr = out.hash;
}

self.graph.additional_output_files = additional_output_files;
}
Ok(())
Expand Down
Loading
Loading