Skip to content
36 changes: 16 additions & 20 deletions src/resolver/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -486,9 +486,9 @@ 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` (and `pretty`, when it is a sub-string of `text`) into
/// the process-lifetime `FilenameStore`; a disjoint `pretty` goes in
/// `alloc` (the per-build bundle arena) — see the impl for why.
fn dupe_alloc(&self, alloc: &bun_alloc::MimallocArena)
-> crate::CrateResult<Path<'static>>;
fn dupe_alloc_fix_pretty(
Expand Down Expand Up @@ -582,25 +582,21 @@ pub mod fs {
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);
// Disjoint `text`/`pretty` (e.g. a file outside
// `top_level_dir`, whose `pretty` starts with `../`).
// `text` is interned like every other branch: the file
// watcher stores it without copying and outlives the
// per-build arena. Only `pretty` — a display path recomputed
// every build — goes in the arena, so repeated `Bun.build()`
// calls don't grow `FilenameStore` by it.
let text = FilenameStore::instance().append_slice(self.text)?;
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
let pretty: &mut [u8] = alloc.alloc_slice_copy(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()];
let pretty: &'static [u8] =
unsafe { core::slice::from_raw_parts(pretty.as_ptr(), pretty.len()) };
let mut p = Path::<'static>::init(text);
p.pretty = pretty;
p
};
new_path.namespace = dupe_namespace(self.namespace)?;
Expand Down
9 changes: 6 additions & 3 deletions src/runtime/bake/DevServer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,12 @@ pub(crate) fn init(options: Options) -> JsResult<Box<DevServer>> {
// exactly once before `assume_init()` below.
unsafe {
w!(magic, Magic::Valid);
w!(root, Box::from(options.root.as_bytes()));
w!(
root,
Box::from(paths::string_paths::without_trailing_slash_windows_path(
options.root.as_bytes()
))
);
w!(vm, bun_ptr::BackRef::new(options.vm));
w!(vm_handle, options.vm.handle());
w!(server, None);
Expand Down Expand Up @@ -6002,8 +6007,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;
}
Expand Down
10 changes: 8 additions & 2 deletions test/bake/bake-harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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")[];
/**
Expand Down Expand Up @@ -2080,8 +2086,8 @@ function testImpl<T extends DevServerTest>(
};

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,
{
Expand Down
34 changes: 34 additions & 0 deletions test/bake/dev/html.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,3 +370,37 @@ devTest("error report endpoint blanks stray non-text bytes in reported frames",
await dev.fetch("/").expect.toInclude("<h1>Frame Bytes</h1>");
},
});
devTest("editing a file imported from outside the project root hot-reloads", {
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");
},
});
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
20 changes: 20 additions & 0 deletions test/js/bun/http/bun-serve-html.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1095,6 +1095,26 @@ 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 when reporting a bundle failure.
test.concurrent("dev server started after process.chdir() reports bundle failures", async () => {
using dir = tempDir("bun-serve-html-chdir", {
"app/index.html": `<!DOCTYPE html><html><head></head><body><script type="module" src="./app.ts"></script></body></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, exitCode }, stderr).toEqual({ stdout: JSON.stringify({ status: 500 }), exitCode: 0 });
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});

test("wildcard static routes", async () => {
await using dir = tempDir("bun-serve-html-error-handling", {
"index.html": /*html*/ `
Expand Down
Loading