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
3 changes: 3 additions & 0 deletions src/ast/import_record.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ bitflags::bitflags! {
/// `IS_UNUSED` for its own reasons (an unused TypeScript import, a macro
/// import), and those records must never be resolved.
const IS_BARREL_DEFERRED = 1 << 18;

/// Dev server: the import resolved with a secondary path, kept in `BundleV2::dev_server_secondary_paths`.
const HAS_SECONDARY_PATH = 1 << 19;
}
}

Expand Down
20 changes: 19 additions & 1 deletion src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,9 @@ pub struct BundleV2<'a> {
/// dense and this is probed once per import in `on_parse_task_complete`
/// (the main-thread parse-phase throughput limiter).
pub(crate) requested_exports: Vec<Option<RequestedExports>>,

/// Dev server only. See `secondary_paths`.
pub(crate) dev_secondary_paths: crate::secondary_paths::SecondaryPaths,
}

bun_core::declare_scope!(Bundle, visible);
Expand Down Expand Up @@ -2942,6 +2945,16 @@ pub mod bv2_impl {
return;
}

if self.dev_server.is_some()
&& import_record.original_target.bake_graph() == bake::Graph::Client
{
let record: &mut ImportRecord = &mut self.graph.ast.items_import_records_mut()
[import_record.importer_source_index as usize]
.as_mut_slice()[import_record.import_record_index as usize];
self.dev_secondary_paths
.note(record, &resolve_result, &path);
}

if path.pretty.as_ptr() == path.text.as_ptr() {
// TODO: outbase
let rel = bun_paths::resolve_path::relative_platform::<
Expand Down Expand Up @@ -3337,6 +3350,7 @@ pub mod bv2_impl {
asynchronous: false,
has_any_top_level_await_modules: false,
requested_exports: Vec::new(),
dev_secondary_paths: Default::default(),
});
if let Some(bo) = bake_options {
// SAFETY: `bo.client_transpiler` is the caller's live, write-capable
Expand Down Expand Up @@ -7221,7 +7235,7 @@ pub mod bv2_impl {
continue;
}

if let Some(dev_server) = self.dev_server_handle() {
if let Some(dev_server) = self.dev_server {
'brk: {
if path.loader(&self.transpiler.options.loaders) == Some(Loader::Html)
&& (import_record.loader.is_none()
Expand Down Expand Up @@ -7249,6 +7263,10 @@ pub mod bv2_impl {
}

import_record.source_index = Index::INVALID;
if ctx.target.bake_graph() == bake::Graph::Client {
self.dev_secondary_paths
.note(import_record, &resolve_result, path);
}

if let Some(entry) = dev_server.is_file_cached(path.text, bake_graph) {
let rel = bun_paths::resolve_path::relative_platform::<
Expand Down
1 change: 1 addition & 0 deletions src/bundler/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ pub mod defines;
pub mod linker;
#[path = "LinkerGraph.rs"]
pub mod linker_graph;
pub mod secondary_paths;
// Moved down to `bun_js_parser::defines_table` so the parser reads its own
// const without a cross-crate hook. Re-export for existing callers.
pub use bun_js_parser::defines_table;
Expand Down
52 changes: 52 additions & 0 deletions src/bundler/secondary_paths.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
//! The dev server's stand-in for `BundleV2::scan_for_secondary_paths`: the "main" file behind each import of a "module" file.

use bun_ast::{ImportRecord, ImportRecordFlags};
use bun_collections::StringHashMap;

use crate::bun_fs as Fs;
use crate::bundle_v2::BundleV2;

/// The secondary paths of a dev server bundle, by primary path.
#[derive(Default)]
pub struct SecondaryPaths {
by_primary: StringHashMap<&'static [u8]>,
}

impl SecondaryPaths {
/// For an import record that the dev server resolved for a client file. The record is bound to `primary`.
#[inline]
pub(crate) fn note(
&mut self,
record: &mut ImportRecord,
resolved: &bun_resolver::Result,
primary: &Fs::Path<'_>,
) {
let Some(secondary) = &resolved.path_pair.secondary else {
return;
};
if secondary.is_disabled || bun_core::strings::eql_long(secondary.text, primary.text, true)
{
return;
}
record.flags.insert(ImportRecordFlags::HAS_SECONDARY_PATH);
bun_core::handle_oom(self.by_primary.put(primary.text, secondary.text));
}

/// The secondary path of an import record with `HAS_SECONDARY_PATH` that is bound to `primary`.
pub fn get(&self, primary: &[u8]) -> Option<&'static [u8]> {
self.by_primary.get(primary).copied()
}

/// Each primary path of `get` with its secondary path.
pub fn iter(&self) -> impl Iterator<Item = (&[u8], &'static [u8])> {
self.by_primary
.iter()
.map(|(primary, secondary)| (&**primary, *secondary))
}
}

impl<'a> BundleV2<'a> {
pub fn dev_server_secondary_paths(&self) -> &SecondaryPaths {
&self.dev_secondary_paths
}
}
2 changes: 2 additions & 0 deletions src/runtime/bake/bake.private.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ interface Config {
* If true, the client will receive console logs from the server.
*/
console: boolean;
/** Ids in the code of this page that go one step to another id: the "module" file of a package to its "main" file. */
forwards?: Record<Id, Id>;
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/runtime/bake/dev_server/ensure_route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,7 @@ impl DevServer {
script_injection_offset: None,
cached_response: None,
bundled_html_text: None,
forwards: Vec::new(),
});
}
},
Expand Down
8 changes: 6 additions & 2 deletions src/runtime/bake/dev_server/finalize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub(crate) struct HotUpdateContext<'a> {
/// Used to tell if the server should replace or append import records.
pub server_seen_bit_set: DynamicBitSet,
pub gts: &'a mut GraphTraceState,
pub secondary_paths: &'a bun_bundler::secondary_paths::SecondaryPaths,
}

/// Sentinel-encoded `Option<FileIndex>` packed into a `u32` (`u32::MAX` == none).
Expand Down Expand Up @@ -269,6 +270,7 @@ pub(super) fn finalize_bundle(
server_bits: DynamicBitSet::default(),
client_bits: DynamicBitSet::default(),
failures: Vec::new(),
forwards: Vec::new(),
};
let mut ctx = HotUpdateContext {
import_records,
Expand All @@ -278,6 +280,7 @@ pub(super) fn finalize_bundle(
resolved_index_cache: &mut resolved_index_cache,
server_seen_bit_set: DynamicBitSet::default(), // assigned below
gts: &mut gts_storage,
secondary_paths: bv2.dev_server_secondary_paths(),
};

let quoted_source_contents = bv2.linker.graph.files.items_quoted_source_contents();
Expand Down Expand Up @@ -643,6 +646,7 @@ pub(super) fn finalize_bundle(
entry_index,
)?;
}
dev.client_graph.refresh_pairs(ctx.secondary_paths);

// Index all failed files now that the incremental graph has been updated.
if !dev.incremental_result.failures_removed.is_empty()
Expand Down Expand Up @@ -959,10 +963,10 @@ pub(super) fn finalize_bundle(
if had_adjusted_edges {
ctx.gts.clear();
dev.client_graph.current_css_files.clear();
// SAFETY: `trace_all_route_imports` does not mutate `route_bundles`;
// SAFETY: `trace_open_page_imports` does not mutate `route_bundles`;
// shared, call-scoped reborrow.
let route_bundle_ref = unsafe { &*route_bundle };
dev.trace_all_route_imports(route_bundle_ref, ctx.gts, TraceImportGoal::FindCss)?;
dev.trace_open_page_imports(route_bundle_ref, ctx.gts, TraceImportGoal::FindCss)?;
Comment on lines 963 to +969

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟣 pre-existing, not blocking: A developer who adds a require() of a package the open page already imports gets two copies of it after the hot update, until a manual reload that nothing prompts. The base fails the same way (pre-existing), but this is the hazard the change sets out to fix. At finalize.rs:963-980 the route is hot-updated with the stale html.forwards; the HMR chunk carries no forwards, so the page keeps the "module" file while the new require loads "main". Fix: when a bundle changes what an html route forwards (compare the route's new find_forwards with html.forwards), list the route for a reload instead of a hot update, so an open page never runs both files.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

A page of an HTML route is open with index.js doing import moment from "moment" and no file requiring it, so the chunk has no forwards (hmr-module.ts:39 reads config.forwards once at load). The user saves other.js adding require("moment"). src/runtime/bake/dev_server/finalize.rs:963-980 only recomputes the stylesheet list with the old html.forwards, and the HMR chunk at finalize.rs:1074 ships other.js plus the newly parsed moment "main" file with no forwards. In the browser loadModuleSync at hmr-module.ts:320 finds no forward for the main id and loads it as a second instance, while index.js keeps the "module" instance. The page is now in the dual-package state (moment.tz is not a function) and stays there: no update puts the route in List 1 (finalize.rs:840-848), which is what makes hmr-runtime-client.ts:198 call performRouteReload/fullReload. The base branch always runs two copies, so the state is not worse than base, but the PR's own page load would give one copy.

Verification: pre-existing; acknowledged in diff. /home/claude/bun/src/runtime/bake/hmr-module.ts:39 reads the map once from the initial-response config; the hot-update chunk at /home/claude/bun/src/runtime/bake/dev_server/finalize.rs:1071-1079 has forwards: &[], and finalize.rs:963-969 only recomputes CSS via the stale html.forwards. test/bake/dev/bundle.test.ts:2050-2060 pins exactly this.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not in this PR. This PR makes a page load bind one file. It leaves an open page as the base has it until its next load (Downsides, and "What still differs from a build" in the notes). The reload that you describe is the follow-up that the notes name. It is more than the compare:

  • The compare must run before List 1 is written. So each save that adds or removes an import walks a route with such a package one more time.
  • List 1 reloads a page by the route of its socket. A page whose socket has the route of another URL (for example /admin/* beside /*) then loads again for the other route and not for its own. dev server: tell a page that loaded an outdated client bundle to reload #42041 works on the reload of a page with an outdated client bundle.
  • The reload of List 1 prints "Server-side code changed, reloading!". That is not the reason here, and a true reason needs a change in hmr-runtime-client.ts.

If a maintainer wants it in this PR, I can add it here.

let css_ids = &dev.client_graph.current_css_files;

w_int!(i32, i32::try_from(css_ids.len()).expect("int cast"));
Expand Down
Loading
Loading