Skip to content
16 changes: 8 additions & 8 deletions src/base64/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -944,25 +944,25 @@ pub mod zig_base64 {
// `LinkerContext.rs::css_modules_hash_shim`). `bun_css` re-exports this as
// `css_modules::hash` for its in-crate callers.
//
// Behavior: wyhash(u64) of the formatted args,
// Behavior: wyhash(u64) of the concatenated parts,
// truncated to u32, url-safe-base64-encoded into a bump-allocated slice. If
// `at_start` and the first encoded byte is a digit, prefix `_` (CSS idents
// can't start with a digit).
//
// The parts are bytes, not `fmt::Arguments`: formatting a path replaces each
// byte that is not UTF-8, so two such paths would hash the same.
Comment thread
robobun marked this conversation as resolved.
Resolved
// ──────────────────────────────────────────────────────────────────────────

// TODO: replace with bun's hash
pub fn wyhash_url_safe<'a>(
bump: &'a bun_alloc::Arena,
args: core::fmt::Arguments<'_>,
parts: &[&[u8]],
at_start: bool,
) -> &'a [u8] {
use std::io::Write as _;

let mut hasher = bun_wyhash::Wyhash11::init(0);
// Write into a scratch Vec then hash; freed immediately.
let mut fmt_str: Vec<u8> = Vec::with_capacity(128);
write!(&mut fmt_str, "{}", args).expect("unreachable");
hasher.update(&fmt_str);
for part in parts {
hasher.update(part);
}

let h: u32 = hasher.final_() as u32; // @truncate
let h_bytes: [u8; 4] = h.to_le_bytes();
Expand Down
2 changes: 1 addition & 1 deletion src/bundler/LinkerContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2632,7 +2632,7 @@ impl<'a> LinkerContext<'a> {
let path_hash = ::bun_base64::wyhash_url_safe(
&scratch,
// use path relative to cwd for determinism
format_args!("{}", bstr::BStr::new(&source.path.pretty)),
&[source.path.pretty],
false,
);

Expand Down
15 changes: 4 additions & 11 deletions src/css/css_modules.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use core::fmt::Arguments;

use bun_alloc::Arena as Bump;
use bun_alloc::{ArenaVec as BumpVec, ArenaVecExt as _};
use bun_collections::ArrayHashMap;
Expand Down Expand Up @@ -47,7 +45,7 @@ impl<'a> CssModule<'a> {
let _ = alloced;
hashes.push(hash(
bump,
format_args!("{}", bstr::BStr::new(source)),
&[source],
matches!(config.pattern.segments.at(0), Segment::Hash),
));
}
Expand Down Expand Up @@ -152,12 +150,7 @@ impl<'a> CssModule<'a> {

let the_hash = hash(
bump,
format_args!(
"{}_{}_{}",
bstr::BStr::new(self.hashes[source_index as usize]),
bstr::BStr::new(name),
bstr::BStr::new(key)
),
&[self.hashes[source_index as usize], b"_", name, b"_", key],
false,
);

Expand Down Expand Up @@ -428,6 +421,6 @@ pub enum CssModuleReference<'a> {
/// in-crate callers (`dependencies.rs`, `rules/import.rs`) keep the
/// `css_modules::hash` path.
#[inline]
pub(crate) fn hash<'a>(bump: &'a Bump, args: Arguments<'_>, at_start: bool) -> &'a [u8] {
bun_base64::wyhash_url_safe(bump, args, at_start)
pub(crate) fn hash<'a>(bump: &'a Bump, parts: &[&[u8]], at_start: bool) -> &'a [u8] {
bun_base64::wyhash_url_safe(bump, parts, at_start)
}
16 changes: 2 additions & 14 deletions src/css/dependencies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,7 @@ impl ImportDependency {
rule: &crate::css_rules::import::ImportRule,
filename: &[u8],
) -> ImportDependency {
let placeholder = crate::css_modules::hash(
bump,
format_args!(
"{}_{}",
bstr::BStr::new(filename),
bstr::BStr::new(rule.url)
),
false,
);
let placeholder = crate::css_modules::hash(bump, &[filename, b"_", rule.url], false);

ImportDependency {
placeholder: std::ptr::from_ref::<[u8]>(placeholder),
Expand All @@ -78,11 +70,7 @@ impl UrlDependency {
import_records: &[bun_ast::ImportRecord],
) -> UrlDependency {
let theurl: &[u8] = import_records[url.import_record_idx as usize].path.pretty;
let placeholder = crate::css_modules::hash(
bump,
format_args!("{}_{}", bstr::BStr::new(filename), bstr::BStr::new(theurl)),
false,
);
let placeholder = crate::css_modules::hash(bump, &[filename, b"_", theurl], false);
UrlDependency {
placeholder: std::ptr::from_ref::<[u8]>(placeholder),
}
Expand Down
48 changes: 7 additions & 41 deletions src/runtime/cli/build_command.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::io::Write as _;

use crate::cli::command::{Context, HotReload};
use bun_bundler::bundle_v2::{self, BundleV2};
use bun_bundler::linker_context::metafile_builder as MetafileBuilder;
Expand Down Expand Up @@ -601,14 +599,9 @@ impl BuildCommand {
&& !outfile.is_empty()
&& !ctx.bundler_options.compile
{
let mut entry_naming = Vec::<u8>::new();
write!(
&mut entry_naming,
"./{}",
bstr::BStr::new(bun_paths::basename(outfile))
)
.expect("unreachable");
this_transpiler.options.entry_naming = entry_naming.into_boxed_slice();
// Concatenated, not formatted: `{}` replaces each byte of the name that is not UTF-8.
this_transpiler.options.entry_naming =
strings::concat(&[b"./", bun_paths::basename(outfile)]);
if let Some(dir) = bun_core::dirname(outfile) {
ctx.bundler_options.outdir = dir.into();
}
Expand Down Expand Up @@ -834,13 +827,11 @@ impl BuildCommand {

outfile = compile_outfile(outfile);

let mut outfile_owned: Vec<u8>;
let outfile_owned: Vec<u8>;
if compile_target.os == OperatingSystem::Windows
&& !strings::has_suffix_comptime(outfile, b".exe")
{
outfile_owned = Vec::new();
write!(&mut outfile_owned, "{}.exe", bstr::BStr::new(outfile))
.expect("unreachable");
outfile_owned = [outfile, b".exe"].concat();
outfile = &outfile_owned;
} else if was_renamed_from_index && outfile != b"index" {
// If we're going to fail due to EISDIR, we should instead pick a different name.
Expand Down Expand Up @@ -923,33 +914,8 @@ impl BuildCommand {
continue;
}

// Use the sourcemap's own dest_path basename if available,
// otherwise fall back to {outfile}.map
let mut map_basename_owned: Vec<u8>;
let map_basename: &[u8] = if !f.dest_path.is_empty() {
bun_paths::basename(&f.dest_path)
} else {
let exe_base = bun_paths::basename(outfile);
map_basename_owned = Vec::new();
if compile_target.os == OperatingSystem::Windows
&& !strings::has_suffix_comptime(exe_base, b".exe")
{
write!(
&mut map_basename_owned,
"{}.exe.map",
bstr::BStr::new(exe_base)
)
.expect("unreachable");
} else {
write!(
&mut map_basename_owned,
"{}.map",
bstr::BStr::new(exe_base)
)
.expect("unreachable");
}
&map_basename_owned
};
// The bundler names every source map `<chunk>.map`.
let map_basename = bun_paths::basename(&f.dest_path);

// root_dir already points to the outfile's parent directory,
// so use map_basename (not a path with directory components)
Expand Down
16 changes: 9 additions & 7 deletions src/runtime/cli/filter_run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,11 +364,12 @@ impl<'a> State<'a> {
content = &content[i + 1..];
write!(
&mut self.draw_buf,
"{} {}: {}",
"{} {}: ",
bun_core::fmt::escape_control_chars(&handle.config.package_name),
bun_core::fmt::escape_control_chars(&handle.config.script_name),
bstr::BStr::new(&handle.buffer),
)?;
// Append the script's bytes. Formatting them would replace invalid UTF-8 with U+FFFD.
self.draw_buf.extend_from_slice(&handle.buffer);
handle.buffer.clear();
} else {
handle.buffer.extend_from_slice(content);
Expand All @@ -380,11 +381,11 @@ impl<'a> State<'a> {
let line = &content[0..i + 1];
write!(
&mut self.draw_buf,
"{} {}: {}",
"{} {}: ",
bun_core::fmt::escape_control_chars(&handle.config.package_name),
bun_core::fmt::escape_control_chars(&handle.config.script_name),
bstr::BStr::new(line),
)?;
self.draw_buf.extend_from_slice(line);
content = &content[i + 1..];
}
if !content.is_empty() {
Expand Down Expand Up @@ -449,12 +450,13 @@ impl<'a> State<'a> {
self.draw_buf.clear();
// flush any remaining buffer
if !handle.buffer.is_empty() {
writeln!(
write!(
&mut self.draw_buf,
"{}: {}",
"{}: ",
Comment thread
robobun marked this conversation as resolved.
Resolved
bun_core::fmt::escape_control_chars(&handle.config.package_name),
bstr::BStr::new(&handle.buffer),
)?;
self.draw_buf.extend_from_slice(&handle.buffer);
self.draw_buf.push(b'\n');
handle.buffer.clear();
}
// print exit status
Expand Down
40 changes: 12 additions & 28 deletions src/runtime/shell/builtin/which.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,9 @@ impl Which {
let mut had_not_found = false;
for i in 0..argc {
let arg = Self::arg(interp, cmd, i);
match search.resolve(&arg) {
Some(resolved) => {
let buf = Builtin::fmt_error_arena(
interp,
cmd,
None,
format_args!("{}\n", bstr::BStr::new(&resolved)),
)
.to_vec();
let _ = Builtin::write_no_io(interp, cmd, IoKind::Stdout, &buf);
match search.resolve_line(&arg) {
Some(line) => {
let _ = Builtin::write_no_io(interp, cmd, IoKind::Stdout, &line);
}
None => {
had_not_found = true;
Expand Down Expand Up @@ -100,7 +93,7 @@ impl Which {
}

let arg = Self::arg(interp, cmd, arg_idx);
let resolved = SearchEnv::load(interp, cmd).resolve(&arg);
let resolved = SearchEnv::load(interp, cmd).resolve_line(&arg);

let child = ChildPtr::new(cmd, WriterTag::Builtin);
match resolved {
Expand Down Expand Up @@ -132,28 +125,18 @@ impl Which {
let _ = Builtin::write_no_io(interp, cmd, IoKind::Stdout, &buf);
Self::arg_complete(interp, cmd)
}
Some(resolved) => {
Some(line) => {
if let State::MultiArgs { waiting_write, .. } =
&mut Self::state_mut(interp, cmd).state
{
*waiting_write = true;
}
if let Some(safeguard) = Builtin::of(interp, cmd).stdout.needs_io() {
return Builtin::of_mut(interp, cmd).stdout.enqueue_fmt(
child,
None,
format_args!("{}\n", bstr::BStr::new(&resolved)),
safeguard,
);
return Builtin::of_mut(interp, cmd)
.stdout
.enqueue(child, &line, safeguard);
}
let buf = Builtin::fmt_error_arena(
interp,
cmd,
None,
format_args!("{}\n", bstr::BStr::new(&resolved)),
)
.to_vec();
let _ = Builtin::write_no_io(interp, cmd, IoKind::Stdout, &buf);
let _ = Builtin::write_no_io(interp, cmd, IoKind::Stdout, &line);
Self::arg_complete(interp, cmd)
}
}
Expand Down Expand Up @@ -219,9 +202,10 @@ impl SearchEnv {
}
}

fn resolve(&self, arg: &[u8]) -> Option<Vec<u8>> {
/// The line `which` prints for `arg`. The path is appended, not formatted: it is not always UTF-8.
fn resolve_line(&self, arg: &[u8]) -> Option<Vec<u8>> {
let mut path_buf = bun_paths::path_buffer_pool::get();
bun_which::which(&mut *path_buf, &self.path_env, &self.cwd, arg)
.map(|z| z.as_bytes().to_vec())
.map(|z| [z.as_bytes(), b"\n"].concat())
}
}
30 changes: 30 additions & 0 deletions src/wyhash/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1144,6 +1144,36 @@ mod tests {
}
}

#[test]
fn test_wyhash11_chunked_matches_oneshot() {
// `bun_base64::wyhash_url_safe` feeds the parts of a key one by one;
// the digest must not depend on where the parts are cut.
Comment thread
robobun marked this conversation as resolved.
Resolved
let mut data = [0u8; 200];
for (i, b) in data.iter_mut().enumerate() {
*b = (i as u8).wrapping_mul(31).wrapping_add(7);
}
for total in [0usize, 1, 3, 15, 16, 17, 31, 32, 33, 63, 64, 65, 150, 200] {
let direct = Wyhash11::hash(0, &data[..total]);
for first in 0..=total {
let mut h = Wyhash11::init(0);
h.update(&data[..first]);
h.update(&data[first..total]);
assert_eq!(direct, h.final_(), "total={total} first={first}");
}
}
// Three parts, as the CSS module hash has them (`hash`, `_`, `name`).
let direct = Wyhash11::hash(0, &data);
for first in 0..=data.len() {
for second in first..=data.len().min(first + 40) {
let mut h = Wyhash11::init(0);
h.update(&data[..first]);
h.update(&data[first..second]);
h.update(&data[second..]);
assert_eq!(direct, h.final_(), "first={first} second={second}");
}
}
}

#[test]
fn test_wyhash_is_not_wyhash11() {
// Guard against the historical mix-up: these are different algorithms.
Expand Down
43 changes: 42 additions & 1 deletion test/bundler/bundler_naming.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, tempDir } from "harness";
import { bunEnv, bunExe, isLinux, tempDir } from "harness";
import { readdirSync } from "node:fs";
import { ESBUILD, itBundled } from "./expectBundled";

Expand Down Expand Up @@ -452,3 +452,44 @@ describe("bundler", () => {
});
}
});

// On Linux a file name is bytes, not text. With a source map the build writes two files, and both
// take their name from --outfile. `sh` puts the byte into the argument: a JavaScript string cannot
// hold a lone 0xFF byte.
test.skipIf(!isLinux)("naming/OutfileThatIsNotUTF8", async () => {
using dir = tempDir("naming-outfile-bytes", {
"a.js": `console.log("a");`,
"b.js": `console.log("b");`,
"ff.bin": Buffer.from([0xff]),
"fe.bin": Buffer.from([0xfe]),
});
for (const [entry, byte] of [
["a.js", "ff.bin"],
["b.js", "fe.bin"],
]) {
await using proc = Bun.spawn({
cmd: [
"sh",
"-c",
`exec "$0" build "./$1" --outfile="out-$(cat "$2").js" --sourcemap=linked`,
bunExe(),
entry,
byte,
],
cwd: String(dir),
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
expect(exitCode).toBe(0);
Comment thread
robobun marked this conversation as resolved.
Resolved
}

// One byte of a name is one character of the string. Two builds, two files each.
const written = readdirSync(String(dir), { encoding: "buffer" })
.map(name => name.toString("latin1"))
.filter(name => name.startsWith("out-"))
.sort();
expect(written).toEqual(["out-\xfe.js", "out-\xfe.js.map", "out-\xff.js", "out-\xff.js.map"]);
});
Loading
Loading