Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions docs/bundler/executables.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -895,6 +895,12 @@ console.log(addon.hello());

If you're using `@mapbox/node-pre-gyp` or similar tools, require the `.node` file directly, or it won't bundle correctly.

An addon that links a shared library next to it (through `$ORIGIN` or `@loader_path`) works when that library is embedded too. Pass the directory with `--asset` (see below). At runtime, Bun writes every embedded shared library into one temporary directory that keeps the embedded layout, so the addon finds its dependencies where it expects them.

```bash terminal icon="terminal"
bun build --compile ./index.ts --asset ./lib --outfile myapp
```

### Embed directories

Use `--asset` (or `compile.assets` in the JavaScript API) to embed a file or directory tree into the executable under its original relative path. The embedded files live under `import.meta.dir` at runtime and are reachable via `node:fs` (`existsSync`, `statSync`, `readdirSync`, `readFileSync`) and `Bun.file()`.
Expand Down
9 changes: 9 additions & 0 deletions src/bundler/OutputFile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,15 @@ pub struct OutputFile {
}

impl OutputFile {
/// Names the file this output was read from (`src_path`).
pub fn set_src_path(&mut self, path: Box<[u8]>) {
self.owned_src_path_text = path;
// SAFETY: `owned_src_path_text` is a sibling field that outlives `src_path`; the boxed buffer never moves.
let text: &'static [u8] =
unsafe { core::mem::transmute::<&[u8], &'static [u8]>(&self.owned_src_path_text) };
self.src_path = fs::Path::init(text);
}

// Not a `const` because `Box`/`fs::Path` aren't const-constructible.
pub fn zero_value() -> OutputFile {
OutputFile {
Expand Down
93 changes: 63 additions & 30 deletions src/runtime/cli/build_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1307,31 +1307,54 @@ pub(crate) fn collect_compile_assets(
}
let _ = seen.put(strings::remove_leading_dot_slash(&f.dest_path), ());
}
let mut push =
|out: &mut Vec<options::OutputFile>, asset: &[u8], dest: Vec<u8>, bytes: Vec<u8>| {
if seen.contains_key(&dest) {
return Err(format!(
"asset {} collides with another embedded file at {}",
bun_fmt::quote(asset),
bun_fmt::quote(&dest),
));
}
let _ = seen.put(&dest, ());
out.push(options::OutputFile {
loader: Loader::File,
input_loader: Loader::File,
output_kind: options::OutputKind::Asset,
dest_path: dest.into_boxed_slice(),
size: bytes.len(),
size_without_sourcemap: bytes.len(),
value: options::OutputFileValue::Buffer {
bytes: bytes.into_boxed_slice(),
},
side: Some(options::Side::Client),
..options::OutputFile::zero_value()
});
Ok(())
// A shared library's source path lets the standalone graph tell that the
// bundler's hoisted `[name]-[hash].node` and an `--asset` copy are one file.
Comment thread
robobun marked this conversation as resolved.
Resolved
let src_path_in = |dir: Fd, name: &[u8], dest: &[u8]| -> Option<Box<[u8]>> {
if !bun_standalone_graph::native_libs::is_shared_library_name(dest) {
return None;
}
let mut dir_buf = bun_paths::path_buffer_pool::get();
let dir_path = bun_sys::get_fd_path(dir, &mut dir_buf).ok()?;
let mut abs_buf = bun_paths::path_buffer_pool::get();
let abs = bun_paths::resolve_path::join_abs_string_buf::<bun_paths::platform::Auto>(
dir_path,
&mut abs_buf[..],
&[name],
);
Some(Box::from(abs))
};
let mut push = |out: &mut Vec<options::OutputFile>,
asset: &[u8],
dest: Vec<u8>,
bytes: Vec<u8>,
src_path: Option<Box<[u8]>>| {
if seen.contains_key(&dest) {
return Err(format!(
"asset {} collides with another embedded file at {}",
bun_fmt::quote(asset),
bun_fmt::quote(&dest),
));
}
let _ = seen.put(&dest, ());
let mut file = options::OutputFile {
loader: Loader::File,
input_loader: Loader::File,
output_kind: options::OutputKind::Asset,
dest_path: dest.into_boxed_slice(),
size: bytes.len(),
size_without_sourcemap: bytes.len(),
value: options::OutputFileValue::Buffer {
bytes: bytes.into_boxed_slice(),
},
side: Some(options::Side::Client),
..options::OutputFile::zero_value()
};
if let Some(src_path) = src_path {
file.set_src_path(src_path);
}
out.push(file);
Ok(())
};

let cwd = Fd::cwd();
let mut zbuf = bun_paths::path_buffer_pool::get();
Expand Down Expand Up @@ -1392,7 +1415,7 @@ pub(crate) fn collect_compile_assets(
continue;
}
#[cfg(windows)]
let (rel, bytes) = {
let (rel, bytes, src_path) = {
let mut rel_buf = bun_paths::path_buffer_pool::get();
let rel_z = bun_paths::string_paths::from_w_path(
&mut rel_buf[..],
Expand All @@ -1413,30 +1436,40 @@ pub(crate) fn collect_compile_assets(
Ok(b) => b,
Err(e) => return fail(e.with_path(&rel)),
};
(rel, bytes)
let src_path = src_path_in(entry.dir, base_z.as_bytes(), &rel);
(rel, bytes, src_path)
};
#[cfg(not(windows))]
let (rel, bytes) = {
let (rel, bytes, src_path) = {
let rel = entry.path.as_bytes().to_vec();
let bytes = match bun_sys::File::read_from(entry.dir, entry.basename.as_bytes())
{
Ok(b) => b,
Err(e) => return fail(e.with_path(entry.path.as_bytes())),
};
(rel, bytes)
let src_path = src_path_in(entry.dir, entry.basename.as_bytes(), &rel);
(rel, bytes, src_path)
};
let mut dest = Vec::with_capacity(base.len() + 1 + rel.len());
dest.extend_from_slice(base);
dest.push(b'/');
dest.extend_from_slice(&rel);
push(out, asset, dest, bytes)?;
push(out, asset, dest, bytes, src_path)?;
}
} else if bun_core::S::ISREG(st.st_mode as _) {
let bytes = match bun_sys::File::read_from(cwd, asset_trimmed) {
Ok(b) => b,
Err(e) => return fail(e.with_path(asset)),
};
push(out, asset, base.to_vec(), bytes)?;
let src_path = bun_standalone_graph::native_libs::is_shared_library_name(base)
.then(|| {
let mut real_buf = bun_paths::path_buffer_pool::get();
bun_sys::realpath(asset_z, &mut real_buf)
.ok()
.map(Box::from)
})
.flatten();
push(out, asset, base.to_vec(), bytes, src_path)?;
} else {
return Err(format!(
"asset {} is not a regular file or directory",
Expand Down
25 changes: 6 additions & 19 deletions src/runtime/ffi/ffi_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1419,33 +1419,20 @@ impl FFI {

let mut filepath_buf = bun_paths::path_buffer_pool::get();
let name: &[u8] = 'brk: {
let ext: &[u8] = match () {
// Android shared libraries are `.so` (ELF, same as Linux/FreeBSD).
#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))]
() => b"so",
#[cfg(target_os = "macos")]
() => b"dylib",
#[cfg(windows)]
() => b"dll",
// No arm for other targets (e.g. wasm) — the match fails to
// compile there.
};
// Extract a bunfs-embedded shared
// library (added via `import lib from "./lib.so" with { type:
// "file" }` and shipped through `bun build --compile`) to a real
// on-disk temp file, returning the tmpfile path; libc `dlopen(2)`
// can't see the bunfs virtual FS. The helper lives in
// `crate::jsc_hooks` — same crate, so a direct call.
// on-disk path, returning it; libc `dlopen(2)` can't see the
// bunfs virtual FS. The helper lives in `crate::jsc_hooks` — same
// crate, so a direct call.
Comment thread
robobun marked this conversation as resolved.
Resolved
let _ = vm;
if let Some(len) = crate::jsc_hooks::resolve_embedded_file_to_buf(
name_slice.slice(),
ext,
&mut filepath_buf[..],
) {
// NUL-terminate in place so `DynLib::open`
// can pass the slice to libc without copying. `resolve_*_to_buf`
// is bounded by `Fs::FileSystem::tmpname` + a tmpdir join (both
// fit in `PATH_MAX`), so `filepath_buf[len]` is in bounds.
// NUL-terminate in place so `DynLib::open` can pass the slice
// to libc without copying. `resolve_*_to_buf` leaves room for
// the terminator, so `filepath_buf[len]` is in bounds.
Comment thread
robobun marked this conversation as resolved.
Resolved
filepath_buf[len] = 0;
break 'brk &filepath_buf[0..len];
}
Expand Down
Loading
Loading