diff --git a/src/bun_alloc/lib.rs b/src/bun_alloc/lib.rs index 288aab179dff..86cb45d1d1e9 100644 --- a/src/bun_alloc/lib.rs +++ b/src/bun_alloc/lib.rs @@ -2016,6 +2016,19 @@ impl BSSStringList Option<&'static [u8]> { + if !self.exists(value) { + return None; + } + // SAFETY: `exists` proved `value` lies inside `backing_buf`, which is + // never freed or moved (process-lifetime singleton). The caller already + // holds these bytes as a `&[u8]`, so they are past construction: the only + // `&mut` into the buffer (`append_mutable`, crate-private) covers freshly + // reserved bytes and ends before `append`/`print` return them shared. + Some(unsafe { core::slice::from_raw_parts(value.as_ptr(), value.len()) }) + } + /// Append `value` and return a mutable slice over the freshly-reserved bytes. /// /// Takes `*mut Self` (not `&mut self`) so callers can pass the raw diff --git a/src/bundler/bundle_v2.rs b/src/bundler/bundle_v2.rs index d7f720687be8..4d09a612fcd3 100644 --- a/src/bundler/bundle_v2.rs +++ b/src/bundler/bundle_v2.rs @@ -7154,18 +7154,24 @@ pub mod bv2_impl { .path .text; if this.should_add_watcher(source_path) { - // const generic `CLONE_FILE_PATH = isWindows` - // matches `cfg!(windows)` at compile time. - let _ = this - .bun_watcher_mut() - .unwrap() - .add_file::<{ cfg!(windows) }>( - parse_result.watcher_data.fd, + let fd = parse_result.watcher_data.fd; + let dir_fd = parse_result.watcher_data.dir_fd; + let hash = bun_wyhash::hash(source_path) as u32; + let bun_watcher = this.bun_watcher_mut().unwrap(); + // The watcher keeps the path past this bundle; borrow it + // only when it is interned for the process lifetime + // (`dupe_alloc` leaves other paths in the bundle arena). + let _ = if Fs::as_interned_path(source_path).is_some() { + bun_watcher.add_file::<{ cfg!(windows) }>( + fd, source_path, - bun_wyhash::hash(source_path) as u32, - parse_result.watcher_data.dir_fd, + hash, + dir_fd, None, - ); + ) + } else { + bun_watcher.add_file::(fd, source_path, hash, dir_fd, None) + }; } } } diff --git a/src/resolver/lib.rs b/src/resolver/lib.rs index 9e5c9c02fef2..a0beaf4a5355 100644 --- a/src/resolver/lib.rs +++ b/src/resolver/lib.rs @@ -122,6 +122,12 @@ pub mod fs { // SAFETY: see `append_slice`. unsafe { &*$backing() }.exists(value) } + /// `value` with the store's lifetime, if it already points into the store. + #[inline] + pub fn as_interned(&self, value: &[u8]) -> Option<&'static [u8]> { + // SAFETY: see `append_slice`; the singleton is `'static`. + unsafe { &*$backing() }.as_interned(value) + } } }; } @@ -470,6 +476,17 @@ pub mod fs { // `bun_wyhash`, `bun_options_types`) remain here as an extension trait. pub use bun_paths::fs::{Path, PathName}; + /// `value` with the stores' lifetime, if it already points into the + /// process-lifetime `DirnameStore` or `FilenameStore`. Only their fixed + /// backing buffers are checked; a path that spilled into an overflow + /// allocation reads as not interned. + #[inline] + pub fn as_interned_path(value: &[u8]) -> Option<&'static [u8]> { + DirnameStore::instance() + .as_interned(value) + .or_else(|| FilenameStore::instance().as_interned(value)) + } + /// Intern a `Path.namespace` for `dupe_alloc`. The common `file`/empty /// namespace is a static literal (no allocation); anything else is interned /// into the process-lifetime `FilenameStore`. @@ -486,9 +503,11 @@ pub mod fs { /// `bun_string`). Import this trait to call `.loader()` / `.dupe_alloc()` /// on a `Path`. pub trait PathResolverExt<'a> { - /// Intern `text`/`pretty` into the process-lifetime `FilenameStore`, - /// falling back to `alloc` (the per-build bundle arena) for the - /// disjoint-`text`/`pretty` case — see the impl for why. + /// Intern `text`/`pretty` into the process-lifetime `FilenameStore` + /// (reusing an already-interned `text`); when `pretty` is not a + /// sub-string of `text`, `pretty` and any not-yet-interned + /// `text`/`namespace` go in `alloc` (the per-build bundle arena) + /// instead. See the impl for why. fn dupe_alloc(&self, alloc: &bun_alloc::MimallocArena) -> crate::CrateResult>; fn dupe_alloc_fix_pretty( @@ -514,9 +533,7 @@ pub mod fs { &self, alloc: &bun_alloc::MimallocArena, ) -> crate::CrateResult> { - let is_interned = |slice: &[u8]| { - FilenameStore::instance().exists(slice) || DirnameStore::instance().exists(slice) - }; + let is_interned = |slice: &[u8]| as_interned_path(slice).is_some(); // Returning `self` unchanged widens `text`/`pretty`/`namespace` to // `'static`; the caller has already proven `text`/`pretty` are // interned, so assert `namespace` is too (static literal or store- @@ -576,32 +593,41 @@ pub mod fs { } let mut new_path = if let Some(offset) = bun_core::strings::index_of(self.text, self.pretty) { - // `text` contains `pretty`; intern `text` once and re-slice. - let text = FilenameStore::instance().append_slice(self.text)?; + // `text` contains `pretty`; re-slice the interned copy. + let text = match as_interned_path(self.text) { + Some(text) => text, + None => FilenameStore::instance().append_slice(self.text)?, + }; let mut p = Path::<'static>::init(text); p.pretty = &text[offset..][..self.pretty.len()]; p } else { - // Disjoint `text`/`pretty`. Allocate one combined - // `text\0pretty\0` buffer from the per-build arena (NOT the - // process-lifetime `FilenameStore`): `pretty` here is a - // freshly-relativized display path recomputed every build, so - // interning it permanently would leak one copy per - // `Bun.build()` call. The arena is reset per build; every path - // that escapes to JS is copied into an owned buffer first. - let text_len = self.text.len(); - let buf: &mut [u8] = - alloc.alloc_slice_fill_copy(text_len + self.pretty.len() + 2, 0u8); - buf[..text_len].copy_from_slice(self.text); - buf[text_len + 1..text_len + 1 + self.pretty.len()] - .copy_from_slice(self.pretty); - // SAFETY: arena memory lives for the whole bundle pass; the - // consuming `Path` (graph/import-record) never outlives it. - let buf: &'static [u8] = - unsafe { core::slice::from_raw_parts(buf.as_ptr(), buf.len()) }; - let mut p = Path::<'static>::init(&buf[..text_len]); - p.pretty = &buf[text_len + 1..text_len + 1 + self.pretty.len()]; - p + // Disjoint `text`/`pretty`: a file outside `top_level_dir` + // (`pretty` starts with `../`) or a plugin module in a + // non-`file` namespace (`pretty` is `:`). `pretty` is + // recomputed every build, and so are `text`/`namespace` unless + // the resolver already interned them, so they go in the + // per-build arena rather than growing the append-only stores + // on every `Bun.build()`. Holders that outlive the bundle (the + // file watcher) copy. + let arena_z = |s: &[u8]| -> &'static [u8] { + let buf: &mut [u8] = alloc.alloc_slice_fill_copy(s.len() + 1, 0u8); + buf[..s.len()].copy_from_slice(s); + // SAFETY: arena memory lives for the whole bundle pass; the + // consuming `Path` (graph/import-record) never outlives it. + unsafe { core::slice::from_raw_parts(buf.as_ptr(), s.len()) } + }; + let mut p = Path::<'static>::init( + as_interned_path(self.text).unwrap_or_else(|| arena_z(self.text)), + ); + p.pretty = arena_z(self.pretty); + p.namespace = match self.namespace { + b"" | b"file" => b"file", + ns => as_interned_path(ns).unwrap_or_else(|| arena_z(ns)), + }; + p.is_symlink = self.is_symlink; + p.is_disabled = self.is_disabled; + return Ok(p); }; new_path.namespace = dupe_namespace(self.namespace)?; new_path.is_symlink = self.is_symlink; diff --git a/src/runtime/bake/DevServer.rs b/src/runtime/bake/DevServer.rs index 8c362b91d4df..7cf930b20e72 100644 --- a/src/runtime/bake/DevServer.rs +++ b/src/runtime/bake/DevServer.rs @@ -478,6 +478,8 @@ pub(crate) fn init(options: Options) -> JsResult> { let mut dev_uninit: Box> = Box::new(MaybeUninit::uninit()); let p: *mut DevServer = dev_uninit.as_mut_ptr(); + let root = paths::string_paths::without_trailing_slash_windows_path(options.root.as_bytes()); + /// `addr_of_mut!((*p).$field).write($value)` — writes a single field of the /// partially-initialized `DevServer` without materializing `&mut DevServer`. macro_rules! w { @@ -492,7 +494,7 @@ pub(crate) fn init(options: Options) -> JsResult> { // exactly once before `assume_init()` below. unsafe { w!(magic, Magic::Valid); - w!(root, Box::from(options.root.as_bytes())); + w!(root, Box::from(root)); w!(vm, bun_ptr::BackRef::new(options.vm)); w!(vm_handle, options.vm.handle()); w!(server, None); @@ -574,7 +576,7 @@ pub(crate) fn init(options: Options) -> JsResult> { w!( router, FrameworkRouter { - root: Box::from(options.root.as_bytes()), + root: Box::from(root), types: Box::new([]), routes: Vec::new(), static_routes: Default::default(), @@ -590,7 +592,7 @@ pub(crate) fn init(options: Options) -> JsResult> { // FileSystem is a process-lifetime singleton; `init` interns the path into // the `DirnameStore` (process-lifetime arena) so no caller-side leak is // needed for the `'static` it stores. - let _fs = match bun_resolver::fs::FileSystem::init(Some(options.root.as_bytes())) { + let _fs = match bun_resolver::fs::FileSystem::init(Some(root)) { Ok(fs) => fs, Err(err) => return Err(global.throw_error(err, generic_action)), }; @@ -6002,8 +6004,6 @@ impl DevServer { relative_path_buf: &'a mut PathBuffer, path: &'a [u8], ) -> &'a [u8] { - debug_assert!(self.root[self.root.len() - 1] != b'/'); - if !paths::is_absolute(path) { return path; } diff --git a/test/bake/bake-harness.ts b/test/bake/bake-harness.ts index ac25e7db68be..df3335261457 100644 --- a/test/bake/bake-harness.ts +++ b/test/bake/bake-harness.ts @@ -127,6 +127,12 @@ export interface DevServerTest { * Avoid if possible, this is to reproduce specific bugs. */ mainDir?: string; + /** + * Working directory of the dev server process, relative to the test root. + * `Bun.serve` HTML routes use this as the project root, so files outside of + * it get `../` relative paths. + */ + cwd?: string; skip?: ("win32" | "darwin" | "linux" | "ci")[]; /** @@ -2080,8 +2086,8 @@ function testImpl( }; await using devProcess = Bun.spawn({ - cwd: root, - cmd: [process.execPath, "./harness_start.ts"], + cwd: path.join(root, options.cwd ?? "."), + cmd: [process.execPath, path.join(root, "harness_start.ts")], env: mergeWindowEnvs([ bunEnv, { diff --git a/test/bake/dev/html.test.ts b/test/bake/dev/html.test.ts index c79ed5d0222a..fd25b0a84801 100644 --- a/test/bake/dev/html.test.ts +++ b/test/bake/dev/html.test.ts @@ -370,3 +370,39 @@ devTest("error report endpoint blanks stray non-text bytes in reported frames", await dev.fetch("/").expect.toInclude("

Frame Bytes

"); }, }); +devTest("editing a file imported from outside the project root hot-reloads", { + // The Windows watcher does not watch files outside the project directory. + skip: ["win32"], + files: { + "web/index.html": emptyHtmlFile({ + scripts: ["index.ts"], + }), + "web/index.ts": ` + import { value } from "../outside/dep"; + console.log(value); + import.meta.hot.accept(); + `, + "outside/dep.ts": ` + export const value = "one"; + `, + }, + cwd: "web", + async test(dev) { + await using c = await dev.client("/"); + await c.expectMessage("one"); + await dev.write( + "outside/dep.ts", + ` + export const value = "two"; + `, + ); + await c.expectMessage("two"); + await dev.write( + "outside/dep.ts", + ` + export const value = "three"; + `, + ); + await c.expectMessage("three"); + }, +}); diff --git a/test/js/bun/http/bun-serve-html.test.ts b/test/js/bun/http/bun-serve-html.test.ts index d54976324d45..3b9d66175c7c 100644 --- a/test/js/bun/http/bun-serve-html.test.ts +++ b/test/js/bun/http/bun-serve-html.test.ts @@ -1095,6 +1095,30 @@ test.concurrent("server.reload() while an html route's first bundle is still in }); }); +// process.chdir() leaves the cached top-level directory with a trailing slash, +// which the dev server then used as its root. Reporting a bundle failure +// relativizes the failing file against that root and hit a debug assertion +// (abort, exit code 134). Release builds compile the assertion out and produce +// the same relative path either way, so this only fails on a debug build. +test.concurrent("dev server started after process.chdir() reports bundle failures", async () => { + using dir = tempDir("bun-serve-html-chdir", { + "app/index.html": ``, + "app/app.ts": `import { nope } from "./does-not-exist";\nconsole.log(nope);`, + "serve.ts": /*ts*/ ` + import html from "./app/index.html"; + process.chdir(import.meta.dir + "/app"); + const server = Bun.serve({ port: 0, development: true, routes: { "/": html } }); + const res = await fetch(server.url); + console.log(JSON.stringify({ status: res.status })); + server.stop(true); + `, + }); + const { stdout, stderr, exitCode } = await runServeFixture(dir); + expect(stderr).toContain(`Could not resolve: "./does-not-exist"`); + expect(stdout, stderr).toBe(JSON.stringify({ status: 500 })); + expect(exitCode).toBe(0); +}); + test("wildcard static routes", async () => { await using dir = tempDir("bun-serve-html-error-handling", { "index.html": /*html*/ `