Skip to content
Closed
2 changes: 1 addition & 1 deletion docs/bundler/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ For bundles that run in the Bun runtime. In many cases, it isn't necessary to bu

All bundles generated with `target: "bun"` are marked with a `// @bun` pragma, which tells the Bun runtime that there's no need to re-transpile the file before execution.

If any entrypoint contains a Bun shebang (`#!/usr/bin/env bun`), the bundler defaults to `target: "bun"` instead of `"browser"`.
If `target` is not set and any entrypoint starts with a Bun shebang (`#!/usr/bin/env bun`), the bundler defaults to `target: "bun"` instead of `"browser"`. An explicit `target` is always used as given.

When using `target: "bun"` and `format: "cjs"` together, the `// @bun @bun-cjs` pragma is added and the CommonJS wrapper function is not compatible with Node.js.

Expand Down
5 changes: 5 additions & 0 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2800,6 +2800,11 @@ declare module "bun" {
entrypoints: string[];

/**
* The environment the bundle will run in.
*
* When not set, defaults to `"bun"` if any entrypoint starts with a
* `#!/usr/bin/env bun` shebang, and to `"browser"` otherwise.
*
* @default "browser"
*/
target?: Target; // default: "browser"
Expand Down
35 changes: 14 additions & 21 deletions src/bundler/ParseTask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use crate::cache::{Entry as CacheEntry, ExternalFreeFunction};
use crate::html_scanner::HTMLScanner;
use crate::options::{self, Loader};
use crate::transpiler::Transpiler;
use crate::{ContentHasher, UseDirective, perf, target_from_hashbang};
use crate::{ContentHasher, UseDirective, perf};
use bun_resolver::fs::PathResolverExt as _;
use bun_resolver::{self as _resolver, Resolver};

Expand Down Expand Up @@ -2400,27 +2400,20 @@ pub mod parse_worker {
..Default::default()
});

let target = (if task.source_index.get() == 1 {
target_from_hashbang(entry_contents)
let target = if task.known_target == options::Target::ServerComponentsSsr
&& topts
.framework
.as_ref()
.unwrap()
.server_components
.as_ref()
.unwrap()
.separate_ssr_graph
{
options::Target::ServerComponentsSsr
} else {
None
})
.unwrap_or_else(|| {
if task.known_target == options::Target::ServerComponentsSsr
&& topts
.framework
.as_ref()
.unwrap()
.server_components
.as_ref()
.unwrap()
.separate_ssr_graph
{
options::Target::ServerComponentsSsr
} else {
topts.target
}
});
topts.target
};

let output_format = topts.output_format;

Expand Down
81 changes: 33 additions & 48 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ pub use bv2_impl::dispatch;
pub use bv2_impl::{
CompileResult, CompileResultForSourceMap, CompileResultForSourceMapColumns, ContentHasher,
EventLoop, ImportTracker, PartRange, StableRef, WrapKind, generic_path_with_pretty_initialized,
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 @@ -913,9 +912,7 @@ pub mod bv2_impl {
}
}
/// Returns a `resolver::Result` for a file in the map, or `None` if
/// not found. Handles direct key matches and relative specifiers
/// joined against `dirname(source_file)` (with Windows
/// drive-letter / separator normalization).
/// not found (see [`Self::lookup`] for what matches).
///
/// `arena` is the build's bump arena (`BundleV2::arena()`);
/// the matched key is copied into it so the returned
Expand All @@ -928,33 +925,46 @@ pub mod bv2_impl {
source_file: &[u8],
specifier: &[u8],
) -> Option<bun_resolver::Result> {
if self.map.is_empty() {
return None;
}

let (key, _) = self.lookup(source_file, specifier)?;
// SAFETY: ARENA — `arena` is the build-pass bump arena
// (never freed before the `Result` is consumed); detaching the
// borrow lifetime matches the established `Path<'static>`
// convention used throughout `bun_resolver` (PORTING.md
// §Lifetimes: ARENA → `&'bump T`).
let dupe = |key: &[u8]| -> &'static [u8] {
// SAFETY: see ARENA note above — bytes live in the build-pass arena.
unsafe { bun_ptr::detach_lifetime(arena.alloc_slice_copy(key)) }
};
let key: &'static [u8] =
unsafe { bun_ptr::detach_lifetime(arena.alloc_slice_copy(key)) };
Some(bun_resolver::Result {
path_pair: bun_resolver::PathPair {
primary: crate::bun_fs::Path::init_with_namespace(key, b"file"),
..Default::default()
},
module_type: crate::options::ModuleType::Unknown,
..Default::default()
})
}

/// Returns the map-owned key and contents of `specifier` as imported
/// from `source_file` (`b""` for an entry point).
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn lookup(
&self,
source_file: &[u8],
specifier: &[u8],
) -> Option<(&[u8], &[u8])> {
if self.map.is_empty() {
return None;
}

// Direct key match (must use `getKey` to return the map-owned
// key, not the parameter).
#[cfg(not(windows))]
if let Some((key, _)) = self.map.get_key_value(specifier) {
return Some(Self::result_for_key(dupe(key.as_ref())));
if let Some(found) = self.entry(specifier) {
return Some(found);
}
#[cfg(windows)]
{
let mut buf = bun_paths::path_buffer_pool::get();
let normalized =
bun_paths::resolve_path::path_to_posix_buf(specifier, &mut **buf);
if let Some((key, _)) = self.map.get_key_value(normalized) {
return Some(Self::result_for_key(dupe(key.as_ref())));
if let Some(found) = self.entry(normalized) {
return Some(found);
}
}

Expand Down Expand Up @@ -1015,30 +1025,16 @@ pub mod bv2_impl {
&mut buf[0..joined_len],
);
}
let joined = &buf[0..joined_len];
if let Some((key, _)) = self.map.get_key_value(joined) {
return Some(Self::result_for_key(dupe(key.as_ref())));
}
return self.entry(&buf[0..joined_len]);
}

None
}

/// Build a `bun_resolver::Result` for a matched key. `key` must
/// already satisfy `'static` — see [`resolve`], which copies the
/// map-owned key into the build's bump arena before calling here so
/// the resulting `Path<'static>` borrows arena memory rather than
/// forging a `'static` from a map borrow.
#[inline]
fn result_for_key(key: &'static [u8]) -> bun_resolver::Result {
bun_resolver::Result {
path_pair: bun_resolver::PathPair {
primary: crate::bun_fs::Path::init_with_namespace(key, b"file"),
..Default::default()
},
module_type: crate::options::ModuleType::Unknown,
..Default::default()
}
fn entry(&self, key: &[u8]) -> Option<(&[u8], &[u8])> {
self.map
.get_key_value(key)
.map(|(key, contents)| (key.as_ref(), &contents[..]))
}
}

Expand Down Expand Up @@ -7584,17 +7580,6 @@ pub mod bv2_impl {
Esm,
}

pub fn target_from_hashbang(buffer: &[u8]) -> Option<options::Target> {
const HB: &[u8] = b"#!/usr/bin/env bun";
if buffer.len() > HB.len() && buffer.starts_with(HB) {
match buffer[HB.len()] {
b'\n' | b' ' => return Some(options::Target::Bun),
_ => {}
}
}
None
}

pub fn generic_path_with_pretty_initialized(
path: &bun_paths::fs::Path<'static>,
target: options::Target,
Expand Down
2 changes: 1 addition & 1 deletion src/bundler/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ pub use HTMLImportManifest::html_import_manifest;
pub use bun_core::cheap_prefix_normalizer;
pub use bundle_v2::{
CompileResult, CompileResultForSourceMap, ContentHasher, EventLoop, ImportTracker, PartRange,
StableRef, WrapKind, generic_path_with_pretty_initialized, target_from_hashbang,
StableRef, WrapKind, generic_path_with_pretty_initialized,
};
pub use chunk::{
CrossChunkImport, CrossChunkImportItem, CrossChunkImportItemList, bun_renamer,
Expand Down
27 changes: 27 additions & 0 deletions src/bundler/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,33 @@ impl TargetExt for Target {
}
}

const BUN_HASHBANG: &[u8] = b"#!/usr/bin/env bun";

/// Decides the documented `target` default (docs/bundler/index.mdx): a build
/// without an explicit target is built for Bun when an entry point has this hashbang.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn any_entry_point_has_bun_hashbang(
entry_points: &[Box<[u8]>],
file_map: Option<&crate::bundle_v2::FileMap>,
) -> bool {
entry_points.iter().any(|entry_point| {
if let Some((_, contents)) = file_map.and_then(|files| files.lookup(b"", entry_point)) {
return has_bun_hashbang(contents);
}
let mut first_bytes = [0u8; BUN_HASHBANG.len() + 1];
bun_sys::File::openat(bun_sys::Fd::cwd(), entry_point, bun_sys::O::RDONLY, 0)
.and_then(|file| file.read_all(&mut first_bytes))
.is_ok_and(|len| has_bun_hashbang(&first_bytes[..len]))
})
}

fn has_bun_hashbang(contents: &[u8]) -> bool {
contents.starts_with(BUN_HASHBANG)
&& matches!(
contents.get(BUN_HASHBANG.len()),
None | Some(b'\n' | b'\r' | b' ' | b'\t')
)
}

pub use bun_options_types::Format;
pub use bun_options_types::WindowsOptions;

Expand Down
10 changes: 10 additions & 0 deletions src/runtime/api/JSBundler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,16 @@ pub mod js_bundler {
this.files = file_map_from_js(global_this, JSValue::from_cell(files_obj))?;
}

if !did_set_target
&& this.target != Target::Bun
&& options::any_entry_point_has_bun_hashbang(
this.entry_points.keys(),
Some(&this.files),
)
{
this.target = Target::Bun;
}

if let Some(flag) = config.get_boolean_loose(global_this, "emitDCEAnnotations")? {
this.emit_dce_annotations = Some(flag);
}
Expand Down
6 changes: 6 additions & 0 deletions src/runtime/cli/build_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ impl BuildCommand {
return crate::bake::production::build_command(ctx);
}

if ctx.args.target.is_none()
&& options::any_entry_point_has_bun_hashbang(&ctx.args.entry_points, None)
{
ctx.args.target = Some(api::Target::Bun);
}
Comment thread
claude[bot] marked this conversation as resolved.
Resolved

if fetcher.is_some() {
ctx.args.packages = Some(api::PackagesMode::External);
ctx.bundler_options.compile = false;
Expand Down
Loading
Loading