Skip to content
Merged
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
23 changes: 19 additions & 4 deletions src/bundler/linker_context/MetafileBuilder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,14 +293,29 @@ pub(crate) fn generate(c: &mut LinkerContext, chunks: &mut [Chunk]) -> crate::Re
first_import = false;

j.push_static(b"\n {\n \"path\": ");
// Write path with JSON escaping - chunk references (unique_keys) will be resolved
// by breakOutputIntoPieces and code() below
// Bundled imports use the target source's pretty path (same string as the
// "inputs" key). `record.path.text` is unreliable here: dedup can set
// `source_index` without rewriting the path. Externals/chunk refs fall through.
Comment thread
robobun marked this conversation as resolved.
Resolved
let import_path: &[u8] = 'path: {
if record.source_index.is_valid()
&& record.source_index.get() != Index::RUNTIME.get()
{
let idx = record.source_index.get() as usize;
if idx < sources.len() {
let pretty = sources[idx].path.pretty;
if !pretty.is_empty() {
break 'path pretty;
}
}
}
record.path.text
};
{
let mut buf: Vec<u8> = Vec::new();
write!(
buf,
"{}",
bfmt::format_json_string_utf8(record.path.text, Default::default())
bfmt::format_json_string_utf8(import_path, Default::default())
)?;
j.push_owned(buf.into_boxed_slice());
}
Expand All @@ -309,7 +324,7 @@ pub(crate) fn generate(c: &mut LinkerContext, chunks: &mut [Chunk]) -> crate::Re
j.push_static(b"\"");

// Add "original" field if different from path
if !record.original_path.is_empty() && record.original_path != record.path.text {
if !record.original_path.is_empty() && record.original_path != import_path {
j.push_static(b",\n \"original\": ");
let mut buf: Vec<u8> = Vec::new();
write!(
Expand Down
89 changes: 89 additions & 0 deletions test/bundler/metafile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,95 @@ describe("bundler metafile", () => {
expect(foundCssBundle).toBe(true);
});

test("metafile import paths match input keys for all importers of a shared module", async () => {
// When the same module is imported from many files, every import record must emit the
// resolved pretty path (matching the "inputs" key), not the raw "./b/shared.js" specifier.
const N = 30;
const files: Record<string, string> = { "b/shared.js": `export const s = 1;` };
for (let i = 0; i < N; i++) {
files[`mid${i}.js`] = `import { s } from "./b/shared.js"; export const m${i} = s;`;
}
files["entry.js"] = Array.from({ length: N }, (_, i) => `export * from "./mid${i}.js";`).join("\n");

using dir = tempDir("metafile-shared-import", files);

const result = await Bun.build({
entrypoints: [`${dir}/entry.js`],
metafile: true,
});
expect(result.success).toBe(true);

const metafile = result.metafile as Metafile;
const inputKeys = Object.keys(metafile.inputs);
const sharedKey = inputKeys.find(k => k.endsWith("b/shared.js") || k.endsWith("b\\shared.js"));
expect(sharedKey).toBeDefined();

// Every midN.js must report its import of shared.js using the exact input key,
// and must carry the original specifier.
const midImports: Array<{ from: string; path: string; original?: string }> = [];
for (const [key, input] of Object.entries(metafile.inputs)) {
if (!/[\\/]mid\d+\.js$/.test(key)) continue;
expect(input.imports.length).toBe(1);
midImports.push({ from: key, path: input.imports[0].path, original: input.imports[0].original });
}
expect(midImports.length).toBe(N);

const bad = midImports.filter(m => m.path !== sharedKey);
expect(bad).toEqual([]);
for (const m of midImports) {
expect(m.original).toBe("./b/shared.js");
}

// Also verify entry.js imports of midN.js all resolve to input keys.
const entryKey = inputKeys.find(k => k.endsWith("entry.js"))!;
for (const imp of metafile.inputs[entryKey].imports) {
expect(imp.path in metafile.inputs).toBe(true);
}
});

test("metafile import paths are deterministic across repeated builds", async () => {
const N = 30;
const files: Record<string, string> = { "b/shared.js": `export const s = 1;` };
for (let i = 0; i < N; i++) {
files[`mid${i}.js`] = `import { s } from "./b/shared.js"; export const m${i} = s;`;
}
files["entry.js"] = Array.from({ length: N }, (_, i) => `export * from "./mid${i}.js";`).join("\n");

using dir = tempDir("metafile-determinism", files);

async function collectImportPaths() {
const r = await Bun.build({ entrypoints: [`${dir}/entry.js`], metafile: true });
expect(r.success).toBe(true);
const m = r.metafile as Metafile;
return Object.keys(m.inputs)
.sort()
.map(k => [k, m.inputs[k].imports.map(i => ({ path: i.path, original: i.original }))]);
}

const first = await collectImportPaths();
for (let i = 0; i < 4; i++) {
expect(await collectImportPaths()).toEqual(first);
}
});

test("metafile does not leak internal runtime source name for runtime-helper imports", async () => {
using dir = tempDir("metafile-runtime-helper", {
"entry.js": `using x = { [Symbol.dispose]() {} };\nconsole.log(x);\n`,
});

const result = await Bun.build({
entrypoints: [`${dir}/entry.js`],
metafile: true,
});
expect(result.success).toBe(true);

const metafile = result.metafile as Metafile;
const entryKey = Object.keys(metafile.inputs).find(k => k.endsWith("entry.js"))!;
const importPaths = metafile.inputs[entryKey].imports.map(i => i.path);
expect(importPaths).toEqual(["bun:wrap"]);
expect("runtime" in metafile.inputs).toBe(false);
Comment thread
robobun marked this conversation as resolved.
Resolved
});

test("metafile handles circular imports", async () => {
using dir = tempDir("metafile-circular-test", {
"a.js": `import { b } from "./b.js"; export const a = 1; console.log(b);`,
Expand Down