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
41 changes: 30 additions & 11 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2800,6 +2800,24 @@ pub mod bv2_impl {
Ok(Some(source_index.get()))
}

/// Entry points that no plugin claimed are looked up in the `files`
/// map before the disk, like `run_resolver` does for imports. Returns
/// whether the map had the entry point (it has been enqueued if so).
pub(crate) fn enqueue_entry_point_from_file_map(
&mut self,
entry_point: &[u8],
target: options::Target,
) -> Result<bool, Error> {
let Some(file_map) = self.file_map else {
return Ok(false);
};
let Some(mut resolved) = file_map.resolve(self.arena(), b"", entry_point) else {
return Ok(false);
};
self.enqueue_entry_item(&mut resolved, true, target)?;
Ok(true)
}

/// `heap` is not freed when `deinit`ing the BundleV2
pub fn init(
transpiler: &'a mut Transpiler<'a>,
Expand Down Expand Up @@ -3062,17 +3080,11 @@ pub mod bv2_impl {
continue;
}

// Check FileMap first for in-memory entry points
if let Some(file_map) = self.file_map {
if let Some(file_map_result) = file_map.resolve(self.arena(), b"", entry_point)
{
let _ = self.enqueue_entry_item(
&mut { file_map_result },
true,
self.transpiler.options.target,
)?;
continue;
}
if self.enqueue_entry_point_from_file_map(
entry_point,
self.transpiler.options.target,
)? {
continue;
}

// no plugins were matched
Expand Down Expand Up @@ -4654,6 +4666,13 @@ pub mod bv2_impl {
if resolve.import_record.namespace.as_ref() == b"file" {
if resolve.import_record.kind == ImportKind::EntryPointBuild {
let target = resolve.import_record.original_target;
match this.enqueue_entry_point_from_file_map(
&resolve.import_record.specifier,
target,
) {
Ok(false) => {}
Ok(true) | Err(_) => return,
}
let Ok(resolved) = this
.transpiler_for_target(target)
.resolve_entry_point(&resolve.import_record.specifier)
Expand Down
124 changes: 124 additions & 0 deletions test/bundler/bundler_files.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { BunPlugin, OnResolveCallback } from "bun";
import { describe, expect, test } from "bun:test";
import { tempDir } from "harness";
import { basename } from "node:path";

describe("bundler files option", () => {
test("basic in-memory file bundling", async () => {
Expand Down Expand Up @@ -582,4 +584,126 @@ describe("bundler files option", () => {
const output = await result.outputs[0].text();
expect(output).toContain("injected by plugin");
});

// An onResolve filter that matches the entry point runs before the files map
// is consulted. When the callback declines, the entry point must still come
// from the files map, exactly as it does when no plugin matches it.
describe("onResolve plugin matching an in-memory entry point and declining", () => {
function decliningPlugin(
filter: RegExp,
seen: string[] = [],
result: ReturnType<OnResolveCallback> = undefined,
): BunPlugin {
return {
name: "declining",
setup(build) {
build.onResolve({ filter }, args => {
seen.push(`${args.kind} ${args.path}`);
return result;
});
},
};
}

async function buildOutputs(entrypoint: string, files: Record<string, string>, plugins: BunPlugin[]) {
const result = await Bun.build({ entrypoints: [entrypoint], files, plugins, throw: false });
expect(result.logs.map(String)).toEqual([]);
expect(result.success).toBe(true);
return Promise.all(result.outputs.map(async output => [output.path, await output.text()]));
}

const byPath = ([a]: string[], [b]: string[]) => (a < b ? -1 : a > b ? 1 : 0);

const jsFiles = {
"/app/entry.js": `import { value } from "./lib.js"; console.log(value);`,
"/app/lib.js": `export const value = "js entry from files";`,
};

const htmlFiles = {
"/app/index.html": `<!doctype html><html><body><script src="./app.js"></script></body></html>`,
"/app/app.js": `console.log("html entry from files");`,
};

test("JS entry point is bundled from the files map", async () => {
const seen: string[] = [];
const outputs = await buildOutputs("/app/entry.js", jsFiles, [decliningPlugin(/.*/, seen)]);

expect(seen).toEqual(["entry-point-build /app/entry.js", "import-statement ./lib.js"]);
expect(outputs).toEqual([[expect.any(String), expect.stringContaining("js entry from files")]]);
});

test("HTML entry point is bundled from the files map", async () => {
const seen: string[] = [];
const outputs = await buildOutputs("/app/index.html", htmlFiles, [decliningPlugin(/.*/, seen)]);

expect(seen).toEqual(["entry-point-build /app/index.html", "import-statement ./app.js"]);
expect(outputs.sort(byPath)).toEqual([
[expect.stringMatching(/\.js$/), expect.stringContaining("html entry from files")],
[expect.stringMatching(/\.html$/), expect.stringContaining("<script")],
]);
});

test("declining asynchronously is bundled from the files map too", async () => {
const outputs = await buildOutputs("/app/entry.js", jsFiles, [
decliningPlugin(/.*/, [], Promise.resolve(undefined)),
]);

expect(outputs).toEqual([[expect.any(String), expect.stringContaining("js entry from files")]]);
});

// These filters match only the entry point, so the imports take the same
// route in both builds and the outputs have to be byte-for-byte identical.
test.each([
["JS", "/app/entry.js", /entry\.js$/, jsFiles],
["HTML", "/app/index.html", /index\.html$/, htmlFiles],
])("%s build output is identical to a build without the plugin", async (_, entrypoint, filter, files) => {
const withPlugin = await buildOutputs(entrypoint, files, [decliningPlugin(filter)]);
const withoutPlugin = await buildOutputs(entrypoint, files, []);

expect(withPlugin).toEqual(withoutPlugin);
});

test("in-memory and on-disk entry points in one build", async () => {
using dir = tempDir("bundler-files-declining-plugin", {
"disk.js": `console.log("disk entry");`,
});

const result = await Bun.build({
entrypoints: [`${dir}/disk.js`, `${dir}/virtual.js`],
files: {
[`${dir}/virtual.js`]: `console.log("virtual entry");`,
},
plugins: [decliningPlugin(/.*/)],
throw: false,
});
expect(result.logs.map(String)).toEqual([]);
expect(result.success).toBe(true);

const outputs = await Promise.all(
result.outputs.map(async output => [basename(output.path), await output.text()]),
);
expect(outputs.sort(byPath)).toEqual([
["disk.js", expect.stringContaining("disk entry")],
["virtual.js", expect.stringContaining("virtual entry")],
]);
});

test("entry point missing from both the files map and disk is still an error", async () => {
using dir = tempDir("bundler-files-declining-plugin-missing", {});

const result = await Bun.build({
entrypoints: [`${dir}/missing.js`],
files: {
[`${dir}/other.js`]: `console.log("other");`,
},
plugins: [decliningPlugin(/.*/)],
throw: false,
});

expect(result.logs.map(String)).toEqual([
expect.stringMatching(/^BuildMessage: ModuleNotFound resolving ".*missing\.js" \(entry point\)$/),
]);
expect(result.success).toBe(false);
});
});
});
Loading