Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
7 changes: 7 additions & 0 deletions src/ast/import_record.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@ bitflags::bitflags! {
/// calling the "__reExport()" helper function
const CALLS_RUNTIME_RE_EXPORT_FN = 1 << 6;

/// This record came from an HTML resource hint (`<link rel="prefetch">`,
/// `<link rel="modulepreload">`, `<link rel="preload" as="script">`).
/// Hints are fetch-only: the referenced file must be emitted as a raw
/// asset (never bundled/executed) and an unresolved href must not fail
/// the build.
Comment thread
robobun marked this conversation as resolved.
Resolved
const WAS_HTML_RESOURCE_HINT = 1 << 7;

/// If true, this was originally written as a bare "import 'file'" statement
const WAS_ORIGINALLY_BARE_IMPORT = 1 << 8;

Expand Down
77 changes: 49 additions & 28 deletions src/bundler/HTMLScanner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,12 @@ impl<'a> HTMLScanner<'a> {
}

impl<'a> HTMLScanner<'a> {
fn create_import_record(&mut self, input_path: &[u8], kind: ImportKind) -> Result<(), Error> {
fn create_import_record(
&mut self,
input_path: &[u8],
kind: ImportKind,
is_resource_hint: bool,
) -> Result<(), Error> {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// 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'/' {
Expand Down Expand Up @@ -69,6 +74,15 @@ impl<'a> HTMLScanner<'a> {

let owned: &'static [u8] =
Box::leak(AstAlloc::vec_from_slice(path_to_use).into_boxed_slice());
let mut flags = ImportRecordFlags::default();
if is_resource_hint {
// `<link rel="prefetch">` / `rel="modulepreload"` / `rel="preload"
// as="script"` are browser fetch-only hints. An unresolved href
// (e.g. a navigation route) must not fail the build, and the
// bundler must not execute the target.
Comment thread
robobun marked this conversation as resolved.
Resolved
flags.insert(ImportRecordFlags::WAS_HTML_RESOURCE_HINT);
flags.insert(ImportRecordFlags::HANDLES_IMPORT_ERRORS);
}
let record = ImportRecord {
path: FsPath::init(owned),
kind,
Expand All @@ -77,7 +91,7 @@ impl<'a> HTMLScanner<'a> {
loader: None,
source_index: AstIndex::default(),
original_path: b"",
flags: ImportRecordFlags::default(),
flags,
};

self.import_records.push(record);
Expand All @@ -100,11 +114,9 @@ impl<'a> HTMLScanner<'a> {
&mut self,
_element: &mut Element<'_, '_>,
path: &[u8],
url_attribute: &[u8],
kind: ImportKind,
tag: TagHandler,
) {
let _ = url_attribute;
let _ = self.create_import_record(path, kind);
let _ = self.create_import_record(path, tag.kind, tag.is_resource_hint);
}

pub(crate) fn scan(&mut self, input: &[u8]) -> Result<(), Error> {
Expand All @@ -120,13 +132,7 @@ type Processor<'a> = HTMLProcessor<HTMLScanner<'a>, false>;

/// Trait capturing the methods `HTMLProcessor` calls on `T`.
pub(crate) trait HTMLProcessorHandler {
fn on_tag(
&mut self,
element: &mut Element<'_, '_>,
path: &[u8],
url_attribute: &[u8],
kind: ImportKind,
);
fn on_tag(&mut self, element: &mut Element<'_, '_>, path: &[u8], tag: TagHandler);
fn on_write_html(&mut self, bytes: &[u8]);
fn on_html_parse_error(&mut self, message: &[u8]);

Expand All @@ -145,14 +151,8 @@ pub(crate) trait HTMLProcessorHandler {
}

impl<'a> HTMLProcessorHandler for HTMLScanner<'a> {
fn on_tag(
&mut self,
element: &mut Element<'_, '_>,
path: &[u8],
url_attribute: &[u8],
kind: ImportKind,
) {
HTMLScanner::on_tag(self, element, path, url_attribute, kind)
fn on_tag(&mut self, element: &mut Element<'_, '_>, path: &[u8], tag: TagHandler) {
HTMLScanner::on_tag(self, element, path, tag)
}
fn on_write_html(&mut self, bytes: &[u8]) {
HTMLScanner::on_write_html(self, bytes)
Expand All @@ -172,6 +172,10 @@ pub struct TagHandler {
pub url_attribute: &'static str,
/// The kind of import to create
pub kind: ImportKind,
/// The element is a browser fetch-only hint (prefetch / modulepreload /
/// preload as=script). The referenced file is emitted as a raw asset
/// rather than bundled, and an unresolved href is tolerated.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub is_resource_hint: bool,
}

impl TagHandler {
Expand All @@ -180,11 +184,21 @@ impl TagHandler {
selector,
url_attribute,
kind,
is_resource_hint: false,
}
}

const fn hint(selector: &'static str, url_attribute: &'static str, kind: ImportKind) -> Self {
Self {
selector,
url_attribute,
kind,
is_resource_hint: true,
}
}
}

pub(crate) const TAG_HANDLERS: [TagHandler; 16] = [
pub(crate) const TAG_HANDLERS: [TagHandler; 20] = [
// Module scripts with src
TagHandler::new("script[src]", "src", ImportKind::Stmt),
// CSS Stylesheets
Expand All @@ -207,6 +221,12 @@ pub(crate) const TAG_HANDLERS: [TagHandler; 16] = [
),
// Web Workers
TagHandler::new("link[as='worker'][href]", "href", ImportKind::Stmt),
// Generic preload/prefetch targets (fetch/track/document/embed/object)
TagHandler::new(
"link[as='fetch'][href], link[as='track'][href], link[as='document'][href], link[as='embed'][href], link[as='object'][href]",
"href",
ImportKind::Url,
),
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
// Manifest files
TagHandler::new("link[rel='manifest'][href]", "href", ImportKind::Url),
// Icons
Expand All @@ -215,6 +235,12 @@ pub(crate) const TAG_HANDLERS: [TagHandler; 16] = [
"href",
ImportKind::Url,
),
// Preloaded scripts (<link rel="preload" as="script">)
TagHandler::hint("link[as='script'][href]", "href", ImportKind::Url),
// Module preloads (<link rel="modulepreload">)
TagHandler::hint("link[rel='modulepreload'][href]", "href", ImportKind::Url),
// Prefetch hints (<link rel="prefetch">)
TagHandler::hint("link[rel='prefetch'][href]", "href", ImportKind::Url),
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
// Images with src
TagHandler::new("img[src]", "src", ImportKind::Url),
// Images with srcset
Expand Down Expand Up @@ -289,12 +315,7 @@ impl<T: HTMLProcessorHandler, const VISIT_DOCUMENT_TAGS: bool>
// which is not reborrowed while the rewriter — the only
// holder of these closures — is alive.
unsafe {
(*this_ptr).on_tag(
element,
value.as_bytes(),
tag_info.url_attribute.as_bytes(),
tag_info.kind,
);
(*this_ptr).on_tag(element, value.as_bytes(), tag_info);
}
}
}
Expand Down
8 changes: 8 additions & 0 deletions src/bundler/ParseTask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ pub struct ParseTask {
pub stage: ParseTaskStage,

pub tree_shaking: bool,
/// Set while the only import record that has enqueued this path is an
/// HTML resource hint (prefetch/modulepreload/preload-as-script). If a
/// non-hint record for the same path is seen later, it restores the
/// path's native loader and clears this flag.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub is_html_resource_hint: bool,
pub known_target: options::Target,
pub module_type: options::ModuleType,
pub emit_decorator_metadata: bool,
Expand Down Expand Up @@ -281,6 +286,7 @@ impl ParseTask {
},
stage: ParseTaskStage::NeedsSourceCode,
tree_shaking: false,
is_html_resource_hint: false,
is_entry_point: false,
}
}
Expand Down Expand Up @@ -315,6 +321,7 @@ impl Default for ParseTask {
},
stage: ParseTaskStage::NeedsSourceCode,
tree_shaking: false,
is_html_resource_hint: false,
known_target: options::Target::default(),
module_type: options::ModuleType::Unknown,
emit_decorator_metadata: false,
Expand Down Expand Up @@ -553,6 +560,7 @@ pub mod parse_worker {
},
stage: ParseTaskStage::NeedsSourceCode,
tree_shaking: false,
is_html_resource_hint: false,
module_type: options::ModuleType::Unknown,
emit_decorator_metadata: false,
experimental_decorators: false,
Expand Down
26 changes: 24 additions & 2 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6344,11 +6344,24 @@
}
}

let is_html_resource_hint = import_record
.flags
.contains(bun_ast::ImportRecordFlags::WAS_HTML_RESOURCE_HINT);
let import_record_loader = 'brk: {
let resolved_loader = import_record.loader.unwrap_or_else(|| {
path.loader(&transpiler.options.loaders)
.unwrap_or(Loader::File)
});
// HTML resource hints (<link rel="prefetch">, rel="modulepreload",
// rel="preload" as="script") are fetch-only: the referenced file
// must be emitted as a raw asset and never bundled/executed.
// Force the file loader regardless of extension. If a non-hint
// record for the same path is seen later in this batch, the
// `resolve_queue.found_existing` branch below restores the
// native loader.
Comment thread
robobun marked this conversation as resolved.
Resolved
if is_html_resource_hint && !resolved_loader.should_copy_for_bundling() {
break 'brk Loader::File;
Comment thread
robobun marked this conversation as resolved.
Resolved
}
// When an HTML file references a URL asset (e.g. <link rel="manifest" href="./manifest.json" />),
// the file must be copied to the output directory as-is. If the resolved loader would
// parse/transform the file (e.g. .json, .toml) rather than copy it, force the .file loader
Expand Down Expand Up @@ -6385,11 +6398,19 @@
import_record.kind = ImportKind::HtmlManifest;
}

let resolve_entry = resolve_queue.get_or_put(path.text).expect("oom");
if resolve_entry.found_existing {
// SAFETY: arena-allocated `ParseTask` stored in the queue; arena outlives the pass.
import_record.path =
path_as_static(&unsafe { &**resolve_entry.value_ptr }.path);
let existing = unsafe { &mut **resolve_entry.value_ptr };
// If the only earlier record for this path was an HTML
// resource hint (which forced Loader::File above), a
// later non-hint record restores the native loader so the
// file is bundled normally.
Comment thread
robobun marked this conversation as resolved.
Resolved
if existing.is_html_resource_hint && !is_html_resource_hint {
existing.is_html_resource_hint = false;
existing.loader = Some(import_record_loader);
}

Check failure on line 6412 in src/bundler/bundle_v2.rs

View check run for this annotation

Claude / Claude Code Review

Hint→non-hint loader restoration only works within a single resolve_queue batch; path_to_source_index_map hit bypasses it

The hint→non-hint loader restoration at line 6409 only fires when both records appear in the **same** HTML file's import batch — `resolve_queue` is created fresh per parse-result (line 5815), and the cross-batch dedup via `path_to_source_index_map` at line 6387 `continue`s without ever reaching it. With two HTML entry points where `page1.html` has only `<link rel="modulepreload" href="./shared.js">` and `page2.html` has `<script src="./shared.js">`, if page1's parse result completes first `share
Comment thread
robobun marked this conversation as resolved.
Resolved
import_record.path = path_as_static(&existing.path);
continue;
}

Expand Down Expand Up @@ -6420,6 +6441,7 @@
};

resolve_task.loader = Some(import_record_loader);
resolve_task.is_html_resource_hint = is_html_resource_hint;
resolve_task.tree_shaking = transpiler.options.tree_shaking;
*resolve_entry.value_ptr = resolve_task;
if let Some(secondary) = &resolve_result.path_pair.secondary {
Expand Down
20 changes: 11 additions & 9 deletions src/bundler/linker_context/generateCompileResultForHtmlChunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ use crate::mal_prelude::*;
use bstr::BStr;

use bun_ast::Log;
use bun_ast::{ImportKind, ImportRecord, ImportRecordFlags};
use bun_ast::{ImportRecord, ImportRecordFlags};
use bun_core::strings;
use bun_threading::thread_pool::Task as ThreadPoolLibTask;
use lol_html::HandlerResult;
use lol_html::html_content::{ContentType, Element, EndTag};

use crate::HTMLScanner::{HTMLProcessor, HTMLProcessorHandler};
use crate::HTMLScanner::{HTMLProcessor, HTMLProcessorHandler, TagHandler};
use crate::linker_context_mod::{GenerateChunkCtx, LinkerContext, debug};
use crate::options::Loader;
use crate::{Chunk, CompileResult};
Expand Down Expand Up @@ -118,13 +118,8 @@ impl<'a> HTMLProcessorHandler for HTMLLoader<'a> {
));
}

fn on_tag(
&mut self,
element: &mut Element<'_, '_>,
_path: &[u8],
url_attribute: &[u8],
_kind: ImportKind,
) {
fn on_tag(&mut self, element: &mut Element<'_, '_>, _path: &[u8], tag: TagHandler) {
let url_attribute = tag.url_attribute.as_bytes();
if self.current_import_record_index as usize >= self.import_records.len() {
bun_core::Output::panic(format_args!(
"Assertion failure in HTMLLoader.onTag: current_import_record_index ({}) >= import_records.len ({})",
Expand Down Expand Up @@ -162,9 +157,16 @@ impl<'a> HTMLProcessorHandler for HTMLLoader<'a> {
return;
}

let is_resource_hint = import_record
.flags
.contains(ImportRecordFlags::WAS_HTML_RESOURCE_HINT);

if self.linker.dev_server.is_some() {
if !unique_key_for_additional_files.is_empty() {
set_attribute(element, url_attribute, unique_key_for_additional_files);
} else if is_resource_hint && import_record.path.is_disabled {
// An unresolved prefetch/modulepreload href (e.g. a navigation
// route) passes through untouched.
Comment thread
robobun marked this conversation as resolved.
Resolved
} else if import_record.path.is_disabled
|| loader.is_javascript_like()
|| loader.is_css()
Expand Down
Loading
Loading