Skip to content
Open
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
8 changes: 5 additions & 3 deletions docs/bundler/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1582,20 +1582,22 @@ await Bun.build({
await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
metafile: "./dist/meta.json",
metafile: "meta.json", // ./dist/meta.json
});

// Object — specify separate paths for JSON and markdown output
await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
metafile: {
json: "./dist/meta.json",
markdown: "./dist/meta.md",
json: "meta.json", // ./dist/meta.json
markdown: "meta.md", // ./dist/meta.md
},
});
```

When the build has an `outdir`, Bun resolves a relative `metafile` path from `outdir` and uses an absolute path unchanged. The `--metafile` and `--metafile-md` flags resolve a relative path from the working directory.

The metafile structure contains:

```ts
Expand Down
48 changes: 34 additions & 14 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub(crate) use bv2_impl::write_metafile_output;
pub use bv2_impl::{
CompileResult, CompileResultForSourceMap, CompileResultForSourceMapColumns, ContentHasher,
EventLoop, ImportTracker, PartRange, StableRef, WrapKind, generic_path_with_pretty_initialized,
target_from_hashbang,
metafile_disk_path, target_from_hashbang,
};
pub use bv2_impl::{DevServerInput, DevServerOutput, ImportTrackerIterator, ImportTrackerStatus};
// Flatten the impl-body module into this file's namespace so external callers
Expand Down Expand Up @@ -5588,7 +5588,6 @@ pub mod bv2_impl {
};

// Write metafile outputs to disk and add them as OutputFiles.
// Metafile paths are relative to outdir, like all other output files.
// `LinkerContext::resolver()` wraps the `*mut Resolver` backref deref.
let outdir = &self.linker.resolver().opts.output_dir;
if !self.transpiler.options.metafile_json_path.is_empty() {
Expand Down Expand Up @@ -5622,32 +5621,53 @@ pub mod bv2_impl {
}
}

/// Where a build with an outdir writes a metafile. A relative path is relative to outdir.
/// An absolute one is used as it is. `None`: the path does not fit `buf`.
pub fn metafile_disk_path<'a>(
outdir: &[u8],
file_path: &[u8],
buf: &'a mut bun_paths::PathBuffer,
) -> Option<&'a bun_core::ZStr> {
if bun_paths::is_absolute(file_path) {
// Windows: a path with a root and no drive takes the drive of the working directory.
bun_paths::resolve_path::PosixToWinNormalizer::resolve_cwd_with_external_buf_z(
buf, file_path,
)
.ok()
.map(|destination| &*destination)
} else {
bun_paths::resolve_path::join_z_buf_checked::<bun_paths::resolve_path::platform::Auto>(
&mut buf.0[..],
&[outdir, file_path],
)
}
}

/// Writes a metafile (JSON or markdown) to disk and appends it to the output_files list.
/// Metafile paths are relative to outdir, like all other output files.
pub(crate) fn write_metafile_output(
output_files: &mut Vec<options::OutputFile>,
outdir: &[u8],
file_path: &[u8],
content: &[u8],
output_kind: crate::options::OutputKind,
) -> Result<(), Error> {
let mut output_path = None;
if !outdir.is_empty() {
// Open the output directory and write the metafile relative to it,
// routed through `bun_sys::File`.
let mut buf = bun_paths::path_buffer_pool::get();
let written = match bun_paths::resolve_path::join_z_buf_checked::<
bun_paths::resolve_path::platform::Auto,
>(&mut buf.0[..], &[outdir, file_path])
{
Some(joined_z) => {
// Create parent directories if needed (relative to outdir).
let written = match metafile_disk_path(outdir, file_path, &mut buf) {
Some(destination) => {
if bun_paths::is_absolute(file_path) {
// On Windows the destination has the drive that a path like `\a\b` lacks, and the artifact has to name it.
output_path = Some(Box::<[u8]>::from(destination.as_bytes()));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
// Create parent directories if needed.
let parent = bun_paths::resolve_path::dirname::<
bun_paths::resolve_path::platform::Loose,
>(joined_z.as_bytes());
>(destination.as_bytes());
if !parent.is_empty() {
let _ = bun_sys::mkdir_recursive(parent);
}
bun_sys::File::write_file(bun_core::Fd::cwd(), joined_z, content)
bun_sys::File::write_file(bun_core::Fd::cwd(), destination, content)
}
None => Err(bun_sys::Error::from_code(
bun_sys::E::ENAMETOOLONG,
Expand Down Expand Up @@ -5676,7 +5696,7 @@ pub mod bv2_impl {
} else {
b"metafile.md".as_slice()
}),
output_path: Box::<[u8]>::from(file_path),
output_path: output_path.unwrap_or_else(|| Box::from(file_path)),
data: crate::output_file::OptionsData::Saved(content.len()),
output_kind,
is_executable: false,
Expand Down
11 changes: 6 additions & 5 deletions src/runtime/api/compile_ahead_of_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use bun_alloc::Arena;
use bun_aot::report::ReportMessage;
use bun_ast::{Data, Kind, Log, Msg};
use bun_bundler::aot::{MetafileFiles, PluginSetup, write_metafile_files};
use bun_bundler::bundle_v2::{BuildResult, BundleV2Result, CompletionStruct};
use bun_bundler::bundle_v2::{BuildResult, BundleV2Result, CompletionStruct, metafile_disk_path};
use bun_bundler::options;
use bun_bundler::transpiler::Transpiler;
use bun_options_types::WindowsOptions;
Expand Down Expand Up @@ -218,13 +218,14 @@ impl JSBundleCompletionTask {

// Without an output directory a metafile is handed to the caller and not written.
let outdir = &self.config.outdir.list[..];
let in_output_directory = |path: &[u8]| match path.is_empty() || outdir.is_empty() {
let written_at = |path: &[u8]| match path.is_empty() || outdir.is_empty() {
true => Vec::new(),
false => [outdir, b"/", path].concat(),
false => metafile_disk_path(outdir, path, &mut paths::path_buffer_pool::get())
.map_or_else(Vec::new, |path| path.as_bytes().to_vec()),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
};
let metafiles = [
in_output_directory(&self.config.metafile_json_path.list),
in_output_directory(&self.config.metafile_markdown_path.list),
written_at(&self.config.metafile_json_path.list),
written_at(&self.config.metafile_markdown_path.list),
];
let mut request = CompileRequest {
origin: RequestOrigin::BuildApi,
Expand Down
38 changes: 38 additions & 0 deletions test/aot/cli/metafile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,4 +296,42 @@ process.stdout.write(
}),
buildLimit,
);

test(
"Bun.build writes an absolute metafile path where it points",
() =>
slot(async () => {
using dir = tempDir("aot-metafile-api-absolute", {
// The metafile of the first build lies where this path may point. It is no file of the program.
"main.ts": `const report = process.argv[2] ? require("./reports/" + process.argv[2] + ".json") : undefined;\nconsole.log(typeof report);\n`,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
"build.ts": `import { readFileSync } from "fs";
import { join } from "path";
const reports = join(process.cwd(), "reports");
const builds = [];
for (let turn = 0; turn < 2; turn++) {
const build = await Bun.build({
entrypoints: ["./main.ts"],
outdir: "./out",
metafile: { json: join(reports, "build.json"), markdown: join(reports, "build.md") },
compile: { outfile: "app", aot: true },
});
const inputs = Object.keys(JSON.parse(readFileSync(join(reports, "build.json"), "utf8")).inputs);
builds.push({ success: build.success, outputs: build.outputs.length, inputs });
}
const files = [...new Bun.Glob("{out,reports}/**/*").scanSync()].map(file => file.replaceAll("\\\\", "/")).sort();
process.stdout.write(JSON.stringify({ builds, files }));
`,
});
const folder = String(dir);
const build = await bun(folder, "build.ts");
expect({ stderr: build.stderr, exitCode: build.exitCode }).toEqual({ stderr: expect.any(String), exitCode: 0 });
const eachBuild = { success: true, outputs: 1, inputs: ["main.ts"] };
expect(JSON.parse(build.stdout)).toEqual({
builds: [eachBuild, eachBuild],
files: [isWindows ? "out/app.exe" : "out/app", "reports/build.json", "reports/build.md"],
});
expect(readFileSync(join(folder, "reports", "build.md"), "utf8")).toStartWith("# Bundle Analysis Report");
}),
buildLimit,
);
});
Loading
Loading