Repository navigation
Conversation
The HTML bundler's selector list for <link> tags only matched a fixed set of rel/as values (stylesheet, icon, manifest, as=image|font|video|audio| style|worker). Any other <link href> pointing at a local file, such as rel=prefetch, rel=modulepreload, or rel=preload with as=script|fetch| track|document|embed|object, was passed through untouched. The built page shipped the original source path, which is a guaranteed 404 at runtime (the referenced asset was either emitted under a hashed name or bundled into the entry chunk). Add the missing selectors: - link[as='script'] and link[rel='modulepreload'] are treated as JS imports: the module is bundled into the entry chunk and the hint tag is dropped (there is no separate file left to preload). - link[as='fetch'|'track'|'document'|'embed'|'object'] and link[rel='prefetch'] are treated as URL assets: the file is emitted, hashed, and the href is rewritten to the output path.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughChangesHTML resource hints are classified during scanning, handled during bundling, and preserved or rewritten during HTML output generation. Tests cover preload, prefetch, modulepreload, local HTML, unresolved URLs, and dev-server behavior. HTML resource hint handling
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 8:13 PM PT - Jul 26th, 2026
✅ @robobun, your commit 378ad584b60b63603728cb3d21e77221e4e4530d passed in 🧪 To try this PR locally: bunx bun-pr 36013That installs a local version of the PR into your bun-36013 --bun |
|
CI status: the diff is green on every
Review feedback addressed through edc3f02:
|
…h-only hints Address review: the first pass mapped link[as=script] / rel=modulepreload to ImportKind::Stmt, which bundled the target into the entry chunk and executed it on page load, and rel=prefetch hard-failed the build on navigation-route hrefs. Both diverge from browser semantics where these tags are fetch-only. Introduce ImportRecordFlags::WAS_HTML_RESOURCE_HINT and mark the three resource-hint selectors with it. A hint record: - forces Loader::File so the target is emitted as a raw hashed asset and the href is rewritten, regardless of extension (JS/CSS are not bundled or executed); - sets HANDLES_IMPORT_ERRORS so an href that does not resolve to a local file (e.g. a navigation route) passes through untouched instead of failing the build; - yields to the native loader if a later non-hint record in the same batch references the same path (tracked via ParseTask.is_html_resource_hint), so <link rel=modulepreload href=./a.js> followed by <script src=./a.js> still bundles a.js and drops the hint. link[as=fetch|track|document|embed|object] stay as plain Url imports.
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🔴
src/bundler/HTMLScanner.rs:225-229— Thelink[as='fetch'|'track'|'document'|'embed'|'object']selector usesTagHandler::new()instead ofTagHandler::hint(), so its records get neitherHANDLES_IMPORT_ERRORSnorWAS_HTML_RESOURCE_HINT— the same failure class d0bf2cd fixed foras=script/modulepreload/prefetch.<link rel="preload" as="fetch" href="/api/user" crossorigin>(MDN's canonical preload-for-fetch pattern) now fails the build where it previously passed through, and<link rel="preload" as="document" href="./iframe.html">is parsed withLoader::Htmlrather than emitted as a raw asset. This entry should useTagHandler::hint()like its siblings.Extended reasoning...
What the bug is
Commit d0bf2cd introduced
TagHandler::hint()to give recordsWAS_HTML_RESOURCE_HINT+HANDLES_IMPORT_ERRORS, and applied it tolink[as='script'],link[rel='modulepreload'], andlink[rel='prefetch']— three of the four new selectors this PR adds. The fourth new selector, atHTMLScanner.rs:225-229: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, ),
still uses
TagHandler::new(), sois_resource_hint = falseandcreate_import_record(HTMLScanner.rs:78-85) never sets either flag on these records.But per the HTML spec the
asattribute is only meaningful onrel=preload/rel=modulepreload— every element this selector matches is a fetch-only resource hint, exactly the classhint()was introduced to handle.Code path — unresolved href → build failure (regression)
For
<link rel="preload" as="fetch" href="/api/user" crossorigin>(MDN's documented pattern for preloading afetch()response):HTMLScanner.rs:225—link[as='fetch'][href]matches;create_import_recordis called withis_resource_hint = false, soHANDLES_IMPORT_ERRORSis not set.HTMLScanner.rs:42-46— leading/→ the path is joined ontofs.top_level_dir.bundle_v2.rs:6083— resolver returnsModuleNotFound(no./api/userfile in the project).bundle_v2.rs:6120-6128—!import_record.flags.contains(HANDLES_IMPORT_ERRORS)is true →last_error = Some(err.into())andadd_resolve_error_with_text_dupelogs "Could not resolve". The build fails.
Before this PR no selector matched
as=fetch, so the tag passed through untouched and the build succeeded — this is a concrete regression on realistic input. The same applies to<link rel="preload" as="document" href="/settings">(iframe navigation targets), which are commonly server routes.Code path — JS/CSS/HTML target → bundled/executed
For
<link rel="preload" as="document" href="./iframe.html">(spec-defined use ofas=documentfor<iframe>/<frame>navigation targets):- Record is created with
WAS_HTML_RESOURCE_HINTnot set. bundle_v2.rs:6347-6349—is_html_resource_hint = false, so theLoader::Fileforce at line 6362 does not fire.bundle_v2.rs:6370-6378— the fallbackUrloverride explicitly excludesresolved_loader != Loader::Html, so.htmlkeepsLoader::Htmland is parsed/bundled as an HTML entry rather than emitted as a raw hashed asset.
Similarly,
<link rel="preload" as="fetch" href="./data.js">keepsLoader::Js(excluded by!resolved_loader.is_javascript_like()), so the file is bundled into the entry chunk and, in the rewrite pass,generateCompileResultForHtmlChunk.rshitsloader.is_javascript_like()→element.remove()— the hint tag is silently deleted and the JS runs on page load. This is the exact fetch-only-semantics violation the earlier review flagged forrel=prefetch.Why existing code doesn't prevent it
The two guards d0bf2cd added are keyed entirely on the flags this selector doesn't set:
bundle_v2.rs:6123-6125gates the resolve error on!HANDLES_IMPORT_ERRORS.bundle_v2.rs:6362gates theLoader::Fileforce onis_html_resource_hint.generateCompileResultForHtmlChunk.rs:160-169gates the pass-through-untouched branch onWAS_HTML_RESOURCE_HINT.
None of these fire for
TagHandler::new()entries. The fallback override atbundle_v2.rs:6370-6378deliberately excludes JS/CSS/HTML so<script src>/<link rel=stylesheet>continue to bundle — which is correct forrel=manifestbut wrong forrel=preload as=fetch|document.Step-by-step proof
Input:
<link rel="preload" as="fetch" href="/api/user" crossorigin>
Step as=script(fixed)as=fetch(this bug)Selector TagHandler::hint(...)TagHandler::new(...)is_resource_hinttruefalseHANDLES_IMPORT_ERRORSset not set Resolver: /api/userModuleNotFoundModuleNotFoundbundle_v2.rs:6123skipped (flag set) → path.is_disabled = true, build continueslast_error = Some(...)→ build failsRewrite pass is_resource_hint && path.is_disabled→ tag passes throughnever reached The new
html/link-hint-unresolvedtest coversrel=prefetchandrel=modulepreloadbut notas=fetch/as=document, so this gap has no test coverage.Impact
- Build regression on any project preloading an API endpoint (
as=fetch href=/api/...) or iframe route (as=document href=/route). - Semantic corruption when
as=fetch|documentpoints at a local.js/.css/.htmlfile: the target is bundled/executed instead of emitted as a raw asset.
Per REVIEW.md "Fix the whole class in the same PR": these are sibling entries in the same
TAG_HANDLERStable added by the same PR, sharing the same failure mode; the fix commit appliedhint()to three of them and missed this one. The pre-existingas=font|image|video|audioentries have the same construction, but those rarely point at routes or JS/HTML —as=fetchandas=documentare specifically for API endpoints and iframe navigation targets, so the impact is materially different, and unlike them this selector is newly introduced by this PR.Fix
Change the
link[as='fetch'|'track'|'document'|'embed'|'object'][href]entry fromTagHandler::new(...)toTagHandler::hint(...), and extendhtml/link-hint-unresolvedwith<link rel="preload" as="fetch" href="/api/user" crossorigin>to cover it.
…hints; trim comments as= is only valid on rel=preload|modulepreload, so these are always fetch-only hints and need the same soft-resolve and force-File behaviour as the other hint selectors. Without this, <link rel=preload as=fetch href=/api/user> failed the build and <link rel=preload as=document href=./iframe.html> was parsed as an HTML entry instead of emitted as a raw asset. Extend html/link-hint-unresolved to cover as=fetch and as=document route hrefs. Also trim doc comments per comment-cop review.
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🔴
src/bundler/bundle_v2.rs:6405-6412— Escalating the cross-batch case above: it doesn't need two entry points or scheduling luck — the canonical single-entry modulepreload pattern hits it deterministically.<link rel="modulepreload" href="./dep.js">+<script src="./main.js">wheremain.jsdoesimport "./dep.js": the HTML batch pinsdep.jstoLoader::Fileand schedules its ParseTask beforemain.js's imports are ever resolved; whenimport "./dep.js"arrives, line 6387 hits andcontinues, sodep.jsis parsed as a URL-string module (NoSideEffectsPureData) — a bare import is tree-shaken and a named import fails with "No matching export". That's the MDN-documented use case for modulepreload (preloading a dependency of the entry), and the new test only covers the degenerate case where hint and<script src>point at the same file. Note also that the fix suggested above (upgradeitems_loader_mut()[id]at the 6387 hit) is insufficient here:dep.js's ParseTask has already been scheduled withLoader::Fileat line 6579 by the timemain.js's parse result is drained.Extended reasoning...
What the bug is
The hint→non-hint loader restoration at lines 6409-6412 only runs inside the
resolve_queue.get_or_put(...).found_existingbranch, andresolve_queueis a per-parse-result local. The existing comment on this block already flags the cross-batch gap for a two-HTML-entry race; this escalates it: the same gap deterministically breaks the primary modulepreload use case with a single HTML entry point.<link rel="modulepreload">exists to preload a dependency of the entry script, not the entry script itself — MDN's canonical example is:<link rel="modulepreload" href="./dep.js"> <script type="module" src="./main.js"></script>
// main.js import { x } from "./dep.js"; // or a bare: import "./dep.js";
With this PR,
dep.jsis silently pinned toLoader::Fileand never bundled as JS.Code path
index.html's parse result is handled on the bundle thread:
run_resolution_for_parse_task→resolve_import_records→process_resolve_queue, all synchronous withinon_parse_task_complete.resolve_import_records: the modulepreload record hasWAS_HTML_RESOURCE_HINT→ line 6362 forcesimport_record_loader = Loader::File. The<script src="./main.js">record is non-hint →Loader::Js. Different paths, so the same-batch restoration at line 6409 never fires. Two freshParseTasks go intoresolve_queue:dep.jswithloader = Some(File),is_html_resource_hint = true;main.jswithloader = Some(Js).process_resolve_queue: fordep.js,path_to_source_index_map.get_or_putat line 6509 inserts it; line 6537 writesinput_files[dep].loader = File;File.should_copy_for_bundling()is true, so lines 6573-6575 setside_effects = NoSideEffectsPureDataand push it toadditional_files; line 6579 schedulesdep.js's ParseTask withLoader::File.main.jsis likewise inserted and scheduled withLoader::Js.
main.js's parse result arrives (necessarily after step 2 — the HTML batch scheduled it):
resolve_import_recordsseesimport "./dep.js".WAS_HTML_RESOURCE_HINTis not set →is_html_resource_hint = false,import_record_loader = Js. Line 6387 hits —path_to_source_index_mapalready holdsdep.jsfrom step 2 — setsimport_record.source_indexandcontinues at line 6394. Lines 6401-6412 are unreachable. Nothing touchesinput_files[dep].loader, anddep.js's ParseTask is already running (or queued) withLoader::File.
Link/emit:
dep.jswas parsed with the File loader — its AST is a synthetic default-export-of-URL-string with no user code. It's markedNoSideEffectsPureData, so a bareimport "./dep.js"inmain.jsis tree-shaken. A named import (import { x } from "./dep.js") fails linking with "No matching export in 'dep.js' for import 'x'". The rewrite pass readsinput_files[dep].loader = File, so the modulepreloadhrefis rewritten to the raw emitteddep-<hash>.js.dep.js's top-level code never runs.Why the ordering is deterministic
Unlike the two-entry-point scenario in the earlier comment (which depends on which HTML parse result the pool completes first), here
main.js's ParseTask is created and scheduled by index.html'sprocess_resolve_queue.on_parse_task_completeprocesses one result synchronously — resolve, then process queue — before draining the next, sodep.jsis always inpath_to_source_index_mapbeforemain.js's imports are resolved. No thread-pool luck required.Why existing code doesn't prevent it
- The restoration at line 6409 is scoped to
resolve_queue, which is fresh per parse result.main.js's batch never sees theParseTaskthat carriedis_html_resource_hint = true. - The
path_to_source_index_maphit at line 6387 setssource_indexandcontinues without inspecting or updatinginput_files[id].loader. process_resolve_queue'sfound_existingbranch (lines 6580-6596) is also unreached —main.js's batch never enqueuesdep.jsbecause line 6394 short-circuits first.- The PR's own test (
html/link-preload-prefetch) only exercises the degenerate case where the modulepreload target and<script src>are the same file (./mod.js), which stays inside oneresolve_queueand hits line 6409. Pointing the hint at a transitive dependency — the actual purpose of modulepreload — is not covered.
Impact
The primary real-world modulepreload pattern silently produces broken output: dependency code is dropped from the bundle (bare import), or the build fails with a misleading "No matching export" (named import). This is a regression for any project that adds a modulepreload hint for a module that is only reached transitively from the entry script.
How to fix
The suggestion in the earlier comment — upgrade
items_loader_mut()[id]at the line-6387 hit when a non-hint record arrives for a hint-pinned slot — is not sufficient here on its own: by the timemain.js's import is resolved,dep.js's ParseTask has already been scheduled (line 6579) withLoader::Fileand may already have been parsed. A working fix needs to either (a) defer scheduling hint-only ParseTasks until the graph settles (so a later non-hint reference can restore the loader before parse), or (b) on the line-6387 upgrade, also re-parse the file with its native loader (re-schedule / mark stale) and clearNoSideEffectsPureData+ theadditional_filesentry. Whichever approach is taken, please add a test with<link rel="modulepreload" href="./dep.js">+<script src="./main.js">wheremain.jsimportsdep.jsand assertsdep.js's code lands in the entry chunk.
Forcing Loader::File for resource-hint records broke the canonical
modulepreload pattern: <link rel=modulepreload href=./dep.js> +
<script src=./main.js> where main.js imports dep.js. The hint record is
processed before main.js's imports are resolved, so dep.js was scheduled
with Loader::File and import {x} from './dep.js' failed with 'No matching
export'. The intra-batch loader restoration could not help because main.js's
import arrives in a later batch after dep.js's ParseTask is already
scheduled.
Revert to the simpler rule: hint records resolve and enqueue with their
native loader (so JS is bundled as JS) and set HANDLES_IMPORT_ERRORS so
unresolvable hrefs pass through. In the rewrite pass a JS/CSS target means
the file is in the entry chunk and the hint tag is dropped; a file-loader
target has its href rewritten to the hashed asset path.
This removes the ParseTask.is_html_resource_hint field and the bundle_v2.rs
loader machinery added in d0bf2cd, leaving only the flag, the soft-resolve,
and the selectors. The test now covers the transitive-dep case directly.
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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/HTMLScanner.rs`:
- Around line 229-232: Update the modulepreload and prefetch selectors in the
TagHandler::hint entries to use the rel token-match operator, allowing each
token to match within space-separated rel values. Add or update coverage for
standalone and combined rel values, including both accepted option spellings.
- Around line 34-39: Update HTMLScanner::create_import_record to detect
resource-hint URLs beginning with // and bypass local-path normalization and
resolution, preserving the protocol-relative URL unchanged; explicitly retain
this behavior for accepted network-path forms, including IPv6 hosts. In
test/bundler/bundler_html.test.ts at lines 1097-1111, add a protocol-relative
external hint and assert the emitted value remains unchanged.
In `@test/bundler/bundler_html.test.ts`:
- Around line 1015-1043: Add preload fixtures for as="embed" and as="object" in
the html/link-preload-prefetch test, provide corresponding source assets, and
assert both links are rewritten to their emitted hashed asset paths. Keep the
existing coverage unchanged so all advertised non-code variants are validated.
🪄 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: b83b92bf-c371-45eb-a98c-9be366c5002a
📒 Files selected for processing (4)
src/ast/import_record.rssrc/bundler/HTMLScanner.rssrc/bundler/linker_context/generateCompileResultForHtmlChunk.rstest/bundler/bundler_html.test.ts
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🔴
src/bundler/bundle_v2.rs:6397-6405— The intra-batch restoration doesn't cover the non-hint reference arriving via a transitive import — and unlike the multi-entry case already deferred on this thread, that hits deterministically on a single HTML entry.<link rel="modulepreload" href="./util.js">+<script src="./main.js">wheremain.jsdoesimport { helper } from "./util.js": the HTML batch pinsutil.jstoLoader::Fileinpath_to_source_index_mapbeforemain.jsis scheduled, somain.js's import record hits the map andcontinues past the restoration, and the build fails with "No matching export in util.js for import 'helper'". Before this PR no selector matchedmodulepreloadand this build succeeded; "modulepreload a module the entry script imports" is the primary MDN-documented use ofrel=modulepreload(Vite emits exactly this for entry-chunk deps), so the "known limitation" wording (multi-entry, nondeterministic) does not cover it.Extended reasoning...
What the bug is
The hint→non-hint loader restoration at lines 6398-6404 fires only when both records land in the same
resolve_queue— i.e. both appear directly in the same HTML file. The earlier comment on this thread showed that a non-hint record arriving from a different HTML entry bypasses it via thepath_to_source_index_maphit; the author deferred that as narrow and thread-pool-nondeterministic. But the same bypass triggers deterministically on a single HTML entry whenever the hinted module is reached via a transitive JS import from the entry script rather than a direct<script src>— which is the canonical thingrel=modulepreloadis for.Step-by-step proof (single entry)
<!-- index.html --> <link rel="modulepreload" href="./util.js"> <script type="module" src="./main.js"></script>
// main.js import { helper } from "./util.js"; helper();
- HTML batch —
resolve_import_records:util.js's record hasWAS_HTML_RESOURCE_HINT→ line 6358 forcesLoader::File;resolve_queueinserts a freshParseTask{loader=File, is_html_resource_hint=true}.main.js's record insertsParseTask{loader=Js}. The two paths differ, sofound_existingat line 6398 never fires in this batch. - HTML batch —
process_resolve_queue: runs synchronously on the bundle thread, insertsutil.jsintopath_to_source_index_map, writesLoader::Fileintograph.input_files, and only then schedulesmain.js's ParseTask. Soutil.jsis guaranteed to be in the map beforemain.js's own resolve pass runs. main.jsbatch —resolve_import_records: for itsimport "./util.js"record (noWAS_HTML_RESOURCE_HINT— the JS parser doesn't set it),import_record_loader = Js. But thepath_to_source_index_map.get(path.text)check that runs before line 6397 hits, setssource_index, andcontinues. Lines 6398-6404 are never reached;input_files[util.js].loaderstaysFile.- Parse:
util.jswas scheduled withLoader::File→ its AST isexport default "<unique-key>"; the real module body (and thehelperexport) is discarded. - Link:
main.js'simport { helper } from "./util.js"binds against a File-loader AST with nohelperexport → build fails with "No matching export in util.js for import 'helper'". For a bare side-effect import, the build succeeds bututil.js's top-level statements silently disappear from the bundle.
Why the existing restoration doesn't prevent it
The restoration at lines 6398-6404 lives inside the
resolve_queue.get_or_put(...).found_existingbranch, andresolve_queueis created fresh per parse-result. The cross-batch dedup point —path_to_source_index_map— sits before it in the loop andcontinues directly, so any non-hint record arriving in a later batch never reaches the restoration. The PR's own test (html/link-preload-prefetch) only exercises hint + direct<script src>on the same path (both in the HTML batch, sofound_existingfires); it doesn't cover hint + transitive import.Why this is a regression, not the documented limitation
- Regression: before this PR no selector matched
rel=modulepreload, soutil.jswas reached only viamain.js's import →Loader::Js→ bundled correctly. After this PR the build fails. - Deterministic: step 2 is structural —
process_resolve_queuefor the HTML batch populates the map before it createsmain.js's ParseTask. No thread-pool ordering is involved. - Not covered by the PR's Known-limitation wording: that wording is explicitly "multiple HTML entry points where one only hints a JS file that another
<script src>s, and the hint-only entry happens to complete first". This is single-entry and always-first. - Primary use case: MDN on
rel=modulepreload: "provides a declarative way to preemptively fetch a module script and its dependencies" — i.e. preload modules the entry script will import. Vite's production output emits<link rel="modulepreload">for exactly the entry chunk's transitive dependencies. - Also CSS:
<link rel="prefetch" href="./theme.css">+<link rel="stylesheet" href="./main.css">wheremain.css@importstheme.csshits the same path —theme.cssis pinned toLoader::Fileand the@importno longer bundles it.
How to fix
The suggestion from the earlier thread — track
is_html_resource_hinton the input-file slot and upgrade at thepath_to_source_index_maphit — has the same "ParseTask already scheduled" problem here. The structural fix is the deferral the author mentioned: don't schedule hint-only ParseTasks (or don't forceLoader::Fileon them) until every non-hint reference that could reach the same path has been resolved. A narrower stopgap that unblocks this PR: don't addrel=modulepreload/as=scripttargets toresolve_queueat all when they resolve to a JS-like loader — leave the hint href as-is (pre-PR behavior for that tag) and let the real import pull the module in; the rewrite pass then drops the hint tag becauseloader.is_javascript_like(). That trades "build fails" back for "hint href is a 404", which is what shipped before. - HTML batch —
-
🔴
src/bundler/bundle_v2.rs:6347-6359— The dev-server HTML guard at lines 6270-6288 runs before the newis_html_resource_hintcomputation at line 6347, so in dev-server/bake mode a hint targeting a local.htmlfile — e.g.<link rel="prefetch" href="./page2.html">(canonical next-page navigation prefetch) or<link rel="preload" as="document" href="./iframe.html">— now hard-fails the build with "Browser builds cannot import HTML files." where before this PR the tag passed through untouched.HANDLES_IMPORT_ERRORSdoes not help here: it is only consulted on theModuleNotFoundpath, not this one. Hoist theWAS_HTML_RESOURCE_HINTread above line 6270 and skip (orLoader::File-override) the guard for hint records — same "sibling arm before hint check" class as the FileMap comment above, but a distinct code path with a hard-error failure mode.Extended reasoning...
What the bug is
The new
TagHandler::hintselectors (link[rel='prefetch'],link[as='document'], etc.) create import records for hrefs that were previously ignored by the scanner. When such a hint targets a local.htmlfile that exists on disk, the resolver succeeds and — in dev-server/bake mode — execution reaches the dev-server guard atbundle_v2.rs:6270-6288before the newis_html_resource_hintcomputation at line 6347. That guard testspath.loader(&self.transpiler.options.loaders) == Some(Loader::Html) && (import_record.loader.is_none() || == Html); both conjuncts hold for a hint record (HTMLScanner setsloader: NoneatHTMLScanner.rs:87), so it unconditionally emits"Browser builds cannot import HTML files."viaadd_range_error_fmtandcontinue 'outer. TheLoader::Fileoverride that would have made this a raw-asset copy is never reached.Code path
- Scan —
<link rel="prefetch" href="./page2.html">matches the newlink[rel='prefetch'][href]TagHandler::hintentry.create_import_recordproduces a record withflags = WAS_HTML_RESOURCE_HINT | HANDLES_IMPORT_ERRORS,loader: None. - Resolve —
bundle_v2.rs:6064runs the disk resolver;./page2.htmlexists, so resolution succeeds andpathis set fromresolve_result.path(). - Dev-server guard —
bundle_v2.rs:6270:self.dev_server_handle()isSomein dev-server/bake mode. Line 6272-6274:path.loader(...)for a.htmltarget isSome(Loader::Html);import_record.loader.is_none()istrue. Both conjuncts satisfied. - Line 6282-6287:
log.add_range_error_fmt(..., "Browser builds cannot import HTML files."), thencontinue 'outer. Build fails. - Line 6347 —
is_html_resource_hintcomputation and theLoader::Fileoverride — is never reached.
Why existing code doesn't prevent it
HANDLES_IMPORT_ERRORSis only consulted at lines 6123-6125 inside theModuleNotFoundbranch of the resolve-failure path. On the resolve-success path there is no check for it before the dev-server guard fires; the guard emits the error unconditionally.- The new dev-server pass-through added in
generateCompileResultForHtmlChunk.rs:167-168("Unresolved hint href: pass through untouched") only handlesimport_record.path.is_disabled— i.e. resolve-failure — and never runs anyway becauseresolve_import_recordserrored out before the rewrite pass. - The
Loader::Fileoverride at line 6358 is placed after line 6288, so it cannot influence the guard's conditions.
Step-by-step proof
Dev-server / bake project with:
<!-- index.html --> <link rel="prefetch" href="./page2.html">
and
page2.htmlpresent on disk (a second route the user is likely to navigate to — the MDN-documented use ofrel=prefetch).- Before this PR: no
TAG_HANDLERSentry matchedlink[rel='prefetch'], so no import record was created. The tag passed through untouched; the dev-server build succeeded. - After this PR: the new selector matches, a record is created with
loader: None, resolution succeeds, and at line 6272 the dev-server guard sees.html+loader.is_none()→ hard error"Browser builds cannot import HTML files."; the build fails.
The same happens for
<link rel="preload" as="document" href="./iframe.html">(matches the newlink[as='document'][href]hint selector).Impact
Build-breaking regression in dev-server/bake mode on the canonical next-page navigation prefetch pattern (
<link rel="prefetch" href="./other-page.html">) whenever the target exists on disk. This is the same "sibling arm runs before the hint handling" class as the already-flagged FileMap-arm comment on line 6363, but on a distinct code path (the dev-server HTML guard) and with a hard-error failure mode rather than wrong bundling — per REVIEW.md ("Fix the whole class in the same PR"), it belongs in the same change.How to fix
Hoist the
is_html_resource_hintread (and, ideally, theLoader::Fileoverride onimport_record.loader) above theif let Some(dev_server) = self.dev_server_handle()block at line 6270, so the guard'simport_record.loader.is_none()conjunct is false for hint records. Alternatively, add&& !import_record.flags.contains(ImportRecordFlags::WAS_HTML_RESOURCE_HINT)to the guard's condition at line 6272-6274. Either way, a hint targeting a local.htmlshould reach the raw-asset emission path, not the dev-server error. - Scan —
In dev-server/bake mode, an HTML import record targeting a local .html file hits the 'Browser builds cannot import HTML files' guard before loader selection runs. A <link rel=prefetch href=./page2.html> or <link rel=preload as=document href=./frame.html> hint would now reach that guard (before this PR no selector matched it) and fail the build. Treat hint records the same as unresolved hrefs here: mark is_disabled and continue so the rewrite pass leaves the href untouched.
|
Addressing the two additional findings:
|
…ale doc comment A hint targeting a local .html file (<link rel=prefetch href=./page2.html>, <link rel=preload as=document href=./frame.html>) kept Loader::Html after 2bd81d6 dropped the File-loader force, so page2.html was parsed as a nested HTML entry and its scripts leaked into the current page's entry chunk. Extend the existing HTML Url->File override to also fire for Loader::Html when the record carries WAS_HTML_RESOURCE_HINT, so the target is copied as a raw asset and the href is rewritten. Also reword the WAS_HTML_RESOURCE_HINT doc comment: 'emit as a raw asset' described the File-loader force removed in 2bd81d6.
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 `@test/bundler/bundler_html.test.ts`:
- Around line 1115-1116: Update the assertion near the html script extraction so
the test always verifies that PAGE2_SCRIPT is absent, even when no index-*.js
tag is matched. Remove the conditional skip and directly assert the expected
emitted chunk or no-chunk result, while preserving the fixture’s intended
parent-output leak check.
🪄 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: 730114e0-ead2-416d-b547-7d186054562f
📒 Files selected for processing (3)
src/ast/import_record.rssrc/bundler/bundle_v2.rstest/bundler/bundler_html.test.ts
4ef8f2f to
6e0a405
Compare
Covers the WAS_HTML_RESOURCE_HINT carve-out in the dev-server HTML-import guard (bundle_v2.rs) and the is_resource_hint && path.is_disabled pass-through in the rewrite pass (generateCompileResultForHtmlChunk.rs), neither of which is reachable from itBundled.
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 `@test/bake/dev/html.test.ts`:
- Around line 374-397: Update the “resource-hint links pass through in dev
server” test to assert that the local ./page2.html prefetch link is present with
the expected href, alongside the existing unresolved-href assertions. Keep the
current fixture and other checks unchanged.
🪄 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: 9a011c21-1fc5-4166-a34c-929f7d0266d4
📒 Files selected for processing (2)
test/bake/dev/html.test.tstest/bundler/bundler_html.test.ts
| && !resolved_loader.should_copy_for_bundling() | ||
| && !resolved_loader.is_javascript_like() | ||
| && !resolved_loader.is_css() | ||
| && resolved_loader != Loader::Html | ||
| && (resolved_loader != Loader::Html | ||
| || import_record | ||
| .flags | ||
| .contains(bun_ast::ImportRecordFlags::WAS_HTML_RESOURCE_HINT)) |
There was a problem hiding this comment.
🔴 The new as='fetch' / rel='prefetch' selectors feed .json/.toml/.txt targets into the pre-existing ImportKind::Url → Loader::File override, and because the HTML entry's records are resolved first, the target is registered in path_to_source_index_map with loader=File before any JS module's imports are seen. A later import data from './data.json' in bundled JS then reuses that slot and gets the emitted path string instead of the parsed object — a silent runtime regression vs main, where these tags weren't matched at all. The PR already handled this exact class for .js (2bd81d6, covered by the "not pinned to a file loader" assertion in html/link-preload-prefetch) and for .html (5d17bb2); JSON/TOML/text is the remaining sibling.
Extended reasoning...
What the bug is
The four new TagHandler::hint selectors (link[as='fetch'|'track'|'document'|'embed'|'object'], link[as='script'], link[rel='modulepreload'], link[rel='prefetch']) all use ImportKind::Url. When such a hint targets a file whose extension maps to a non-JS/CSS/HTML/should-copy loader — .json→Json, .toml→Toml, .txt→Text, etc. — the pre-existing override at bundle_v2.rs:6366-6377 fires (loader == Html && kind == Url && !should_copy && !is_js && !is_css) and forces import_record_loader = Loader::File. That forced loader flows into resolve_task.loader at line 6434, and process_resolve_queue then registers the path in path_to_source_index_map (line 6499) with new_input_file.loader = File (line 6527) — first-wins.
If a bundled JS module later does import data from './data.json', its import-record resolution hits the already-populated map entry at line 6386, sets source_index to the File-loaded slot at line 6391, and continues. The File loader's default export is the emitted path string, so data is "./data-<hash>.json" instead of the parsed {k:1} object.
Why it's a regression introduced by this PR
The override at 6366-6377 itself is unchanged from main (only the Html clause at 6371-6374 changed). What's new is that this PR adds selectors that feed it: on main, no TAG_HANDLERS entry matches as='fetch' or rel='prefetch', so a ./data.json referenced by such a hint is never scanned, and the file is reached only via main.js's import → Loader::Json → parsed object. After this PR the hint record is created during index.html's scan, resolved and enqueued in the same synchronous process_resolve_queue pass that schedules main.js's ParseTask, so it always wins the map slot.
The pre-existing rel='manifest' selector could technically hit the same override, but overlapping a manifest with a JS static import is implausible. as='fetch' and rel='prefetch' are specifically intended for data files, which developers do sometimes also statically import (e.g. <link rel="prefetch" href="./config.json"> for a future page + a lazy chunk that does import cfg from './config.json').
Step-by-step proof
<!-- index.html -->
<head>
<link rel="preload" as="fetch" href="./data.json" crossorigin>
</head>
<body><script type="module" src="./main.js"></script></body>// main.js
import data from "./data.json";
console.log(data.k);// data.json
{"k":1}- Scan —
HTMLScannermatcheslink[as='fetch'][href]→ import record withkind=Url,loader=None,WAS_HTML_RESOURCE_HINT|HANDLES_IMPORT_ERRORS. Separately matchesscript[src]→ record for./main.js. - Resolve index.html's records (
bundle_v2.rs:6356): for./data.json,resolved_loader = Loader::Json(from extension).Json.should_copy_for_bundling()is false (loader.rs:114-123),Json.is_javascript_like()is false,Json.is_css()is false,Json != Html→ override fires →import_record_loader = Loader::File. Line 6434:resolve_task.loader = Some(File). - process_resolve_queue (same synchronous drain): line 6483 reads
value.loader = Some(File); line 6499map.get_or_put("…/data.json")inserts; line 6527new_input_file.loader = File; line 6534 writessource_indexinto the map; line 6569 schedules the File ParseTask. In the same loop iteration,./main.jsis scheduled withLoader::Js— its own import records won't be resolved until its ParseTask completes on a later drain. - Resolve main.js's records (later): for
./data.json, line 6386path_to_source_index_map.get(path)returns the existing id → line 6391import_record.source_index = existing→continue. The record'sloaderis set toJsonat line 6380, but that's on the record; the input-file slot's loader staysFileand the already-scheduled File ParseTask has emitted the path-string default export. - Runtime:
console.log(data.k)logsundefined(datais the string"./data-<hash>.json"). Onmainit logs1.
Why existing code doesn't prevent it
- The
is_javascript_like()exclusion at line 6369 (which lets 2bd81d6's fix work for modulepreloaded.js) doesn't coverLoader::Json/Toml/Text. - The
WAS_HTML_RESOURCE_HINTclause added at line 6374 only affectsresolved_loader == Html. path_to_source_index_mapis first-wins by design; there's no reconciliation when a later import wants a different loader.- None of the three new tests cover a hint target that is also statically imported from JS with a data loader —
html/link-preload-prefetch'sdata.jsonis reached only via the hint, and itsdep.jsoverlap case exercises the.jssibling that 2bd81d6 already fixed.
Impact
Silent behavioral change: a JSON/TOML/text import that returned a parsed value on main now returns a path string, with no build error or warning. Per REVIEW.md's whole-class rule, the PR already fixed two siblings of this exact first-wins interaction (.js targets in 2bd81d6 — the test even comments "It must be bundled as JS (not pinned to a file loader), so `import { x } from './dep.js'` resolves" — and .html targets in 5d17bb2); JSON/TOML/text is the remaining member of the class the new selectors expose.
How to fix
Either exclude data loaders from the override the same way JS/CSS are excluded (but then a hint-only .json wouldn't be emitted as a raw asset, so that's wrong on its own), or — more targeted — when WAS_HTML_RESOURCE_HINT is set and the target already exists in path_to_source_index_map with a non-File loader, reuse that slot instead of forcing File; conversely, if the JS import arrives second, the fix needs the hint record to not pin the input-file loader. The simplest correct shape is probably: for hint records whose resolved_loader is a data loader (Json/Toml/Text/etc.), keep the native loader on the input_file slot (so a JS import gets the parsed object) and separately emit the raw bytes as an additional file for the href rewrite — mirroring what should_copy_for_bundling loaders already do. A regression test in html/link-preload-prefetch adding import data from './data.json' to main.js and asserting jsContent contains the JSON's value would pin it.
There was a problem hiding this comment.
Verified. This is the JSON/TOML/text sibling of the first-wins loader-pinning interaction the PR already documents under Trade-off for JS targets, and it is triggered by the pre-existing Url->File override (unchanged from main except for the Html clause). Fixing it correctly (so a hint-only .json is emitted as a raw asset AND a hint-plus-JS-import .json gives a parsed object) requires deferring hint-only ParseTasks until the graph is complete, same as the JS case. I have added it to the Trade-off section in the PR description rather than expanding the loader-pinning workarounds further. The trigger (both <link rel=preload as=fetch href=./data.json> and import data from './data.json' for the same file) is unusual: preload-as-fetch is for fetch() calls, and a static import is bundled so there is nothing to preload.
With entryPoints:[index.html, page2.html] and <link rel=prefetch href=./page2.html> in index.html, page2.html is already in path_to_source_index_map as an Html-loaded entry. Setting the hint record's source_index to that slot made the reachability walk follow the edge and pull page2's scripts into index's entry chunk. When a hint record hits an existing Html-loaded map slot, mark is_disabled and continue without setting source_index so the href passes through (page2.html is emitted under its own entry-point name, so the original href is already a valid output path).
patch_import_record_source_indices re-derives source_index from record.path.text for every record, which re-populated the source_index that the sibling-entry hint guard had just left invalid when the hint href was root-relative (/page2.html writes the absolute path into path.text via HTMLScanner's leading-slash join, whereas ./page2.html leaves the literal relative string). Skip records whose path.is_disabled is set, matching the invariant the resolve loop already establishes (is_disabled records have invalid source_index). Extend html/link-hint-sibling-entry to cover both href shapes.
There was a problem hiding this comment.
The three prior findings (dev-server test coverage, sibling-entry leak, root-relative patch_import_record_source_indices bypass) are now addressed and covered by tests. Deferring to a human for the remaining design call in the unresolved thread at bundle_v2.rs:6374 — whether the acknowledged JSON/TOML/text loader-pinning regression is acceptable as a documented trade-off — and because the fix accreted several special-case guards across the resolve loop that warrant a maintainer's read.
What was reviewed:
- 378ad58's
is_disabledskip inpatch_import_record_source_indicesagainst every otheris_disabled = truesite insrc/bundler/— the pre-existing sites either also invalidatesource_indexor hold unresolved paths that miss the map, so no behaviour change there. - The
on_tagsignature refactor against bothHTMLProcessorHandlerimpls (scanner +HTMLLoader) — both updated;url_attributerecovered fromtagin the loader. WAS_HTML_RESOURCE_HINTuses bit 7, previously unused inImportRecordFlags.
Extended reasoning...
Overview
Adds four resource-hint <link> selectors (rel=prefetch, rel=modulepreload, as=script, as=fetch|track|document|embed|object) to TAG_HANDLERS, tags their import records with a new WAS_HTML_RESOURCE_HINT flag, and threads that flag through four sites in bundle_v2.rs (dev-server HTML-import guard bypass, Url→File loader override for .html targets, sibling-HTML-entry disabling at the map hit, and an is_disabled skip in patch_import_record_source_indices) plus a dev-server pass-through arm in generateCompileResultForHtmlChunk.rs. Refactors HTMLProcessorHandler::on_tag to take the whole TagHandler. Four new itBundled cases and one devTest.
Security risks
None — bundler output-path rewriting; no auth, crypto, or untrusted-input parsing beyond what lol-html already handles.
Level of scrutiny
Medium-high. The change is behavioural in the bundler resolve loop, touches a shared helper (patch_import_record_source_indices) used by every import record, and went through three rounds of found-and-fixed bugs during review (dev-server coverage gap, sibling-entry cross-chunk leak, root-relative-href bypass of the sibling guard). Each fix added another special-case branch keyed on the new flag, which is the shape REVIEW.md warns about ("when a heuristic keeps sprouting counterexamples in review, redesign structurally").
Other factors
- One inline thread from a prior run remains unresolved: the
as=fetch/rel=prefetchselectors now feed.json/.toml/.txtinto the pre-existingUrl→Fileoverride, so a file that is both hint-referenced and staticallyimported from JS gets the path string instead of the parsed object — a strict regression vs main. The author verified it, declined to fix (would require deferring hint-only ParseTasks), and documented it in the PR description's Trade-offs. Whether that's acceptable to ship is a maintainer call. - The
is_disabledskip inpatch_import_record_source_indicesis broader than the hint-record fix strictly requires; verifiers checked every otheris_disabled = truewriter insrc/bundler/and found no case where a disabled record'ssource_indexneeds re-populating, so this reads as a correct invariant tightening rather than an over-broad guard — but it is a change to a general codepath. - Test coverage is good: each of the four production behaviours and the dev-server pass-through has a dedicated case, and the sibling-entry test now covers both
./and/href shapes per the last fix.
|
Overlap note: #41938 (now the single PR for the HTML URL-attribute work) touches the same code. It changes |
|
Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-27 and it conflicts with main. 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
bun build ./index.htmlonly rewrites<link href>for a fixed allowlist ofrel/asvalues. Any<link>outside that list keeps its original source path in the output, which is a guaranteed 404 because the target was either emitted under a hashed name or bundled into the entry chunk.This contradicts
docs/bundler/html-static: "Any<link>tag with anhrefattribute pointing to a local file is rewritten to the new path, and hashed".Fix
Add four resource-hint entries to
TAG_HANDLERSinsrc/bundler/HTMLScanner.rscoveringrel=prefetch,rel=modulepreload,as=script, andas=fetch|track|document|embed|object. These use a newTagHandler::hintconstructor that setsImportRecordFlags::WAS_HTML_RESOURCE_HINTandHANDLES_IMPORT_ERRORSon the record.Behaviour per target type:
ImportKind::Urlpath emits the file with a content hash and thehrefis rewritten to the output path.<link rel=modulepreload href=./dep.js>+<script src=./main.js>wheremain.jsimportsdep.jsbundlesdep.jsas JS (covered byhtml/link-preload-prefetch)..htmltargets: emitted as raw hashed assets (the existingUrl->Fileoverride now also fires forLoader::HtmlwhenWAS_HTML_RESOURCE_HINTis set), so<link rel=prefetch href=./page2.html>is copied verbatim with a rewritten href instead of being parsed as a nested HTML entry (html/link-hint-local-html). In dev-server mode these records skip the "Browser builds cannot import HTML files" guard and pass through untouched (test/bake/dev/html.test.ts).path_to_source_index_maplookup hits anHtml-loaded slot is marked disabled so the reachability walk does not follow it, and the href passes through (the sibling is emitted under its own entry-point name, so the original href is already a valid output path;html/link-hint-sibling-entry)./dashboard, API endpoints like/api/user, external URLs, protocol-relative URLs):HANDLES_IMPORT_ERRORSlets these pass through untouched instead of failing the build (html/link-hint-unresolved).Output for the repro above:
(
modulepreloadandas=scripttags are dropped because their targets are in the entry chunk.)Trade-offs
Both stem from the resolve pipeline's first-wins loader pinning; fixing them requires deferring hint-only
ParseTasks until the module graph is complete, which is a larger change than this 404 fix warrants.<link rel="preload" as="script" href="./unused.js">with no<script src>and no transitive import) is bundled into the entry chunk, matching the existinglink[as=worker]handler..json/.toml/text target is also statically imported from JS (<link rel=preload as=fetch href=./data.json>+import data from './data.json') pins the file toLoader::Filevia the pre-existingUrl->Fileoverride, so the JS import sees the emitted path string instead of the parsed object. Theas=fetchhint is forfetch()calls; a static import is bundled and needs no preload hint.Verification
New
html/link-preload-prefetch,html/link-hint-local-html,html/link-hint-sibling-entry, andhtml/link-hint-unresolvedcases intest/bundler/bundler_html.test.ts, plus a dev-server pass-through case intest/bake/dev/html.test.ts. All 22 existingbundler_htmlcases still pass.[review] gate passed · iteration 1 · 6 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 5 passed · 0 rejected · iteration 1
evidence per changed file