From 217d35f639bd7e4baa2e4422dc17fbaecc8febfb Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 21:27:10 +0000 Subject: [PATCH 1/7] bun patch: select an aliased dependency by its package name too `bun patch ` compared `` with the dependency's name in package.json only. For `"my-alias": "npm:dep@1.0.0"` that name is the alias, so `bun patch dep` and `bun patch dep@1.0.0` failed with "package dep not found", although `dep` is the name that bun prints and the name that keys the patch. The lookup now matches the name in package.json or the name of the resolved package. The folder name comes from the dependency, not from the argument, and passes the same check as an install before it becomes a path. When an alias and the plain name install different versions, the lookup asks for a version, as it does for nested versions. `bun patch ` looked up the existing patch as `@`, so a second `bun patch ` started from the unpatched package. It now uses the package name, which is the key in `patchedDependencies`. --- src/install/PackageManager/patchPackage.rs | 70 +++++++---- test/cli/install/bun-patch.test.ts | 139 ++++++++++++++++++++- 2 files changed, 183 insertions(+), 26 deletions(-) diff --git a/src/install/PackageManager/patchPackage.rs b/src/install/PackageManager/patchPackage.rs index 22f89dfd3146..ec92c533a854 100644 --- a/src/install/PackageManager/patchPackage.rs +++ b/src/install/PackageManager/patchPackage.rs @@ -16,6 +16,7 @@ use crate::isolated_install::FileCopier; use crate::lockfile_real::package::{Package, PackageColumns as _}; use crate::lockfile_real::tree; use crate::lockfile_real::{self as lockfile, Lockfile, PackageIndexEntry}; +use crate::package_installer::alias_is_safe_install_target; use crate::package_manager_real::PackageManager; use crate::package_manager_real::options::{LogLevel, PatchFeatures}; use crate::package_manager_real::package_manager_directories::{ @@ -254,12 +255,12 @@ pub fn do_patch_commit( } PatchArgKind::NameAndVersion => 'brk: { let (name, version) = Dependency::split_name_and_maybe_version(argument); - let (pkg_id, node_modules_relative_path) = + let (pkg_id, node_modules_relative_path, folder_name) = pkg_info_for_name_and_version(&lockfile, &mut iterator, argument, name, version); let changes_dir = resolve_path::join_z_buf::( &mut pathbuf[..], - &[&node_modules_relative_path, name], + &[&node_modules_relative_path, &folder_name], ) .as_bytes() .to_vec(); @@ -879,7 +880,7 @@ pub fn prepare_patch(manager: &mut PackageManager) -> Result<(), crate::Error> { let mut iterator = tree::Iterator::<{ tree::IteratorPathStyle::NodeModules }>::init( &manager.lockfile, ); - let (pkg_id, folder_relative_path) = pkg_info_for_name_and_version( + let (pkg_id, folder_relative_path, folder_name) = pkg_info_for_name_and_version( &manager.lockfile, &mut iterator, pkg_maybe_version_to_patch, @@ -896,7 +897,7 @@ pub fn prepare_patch(manager: &mut PackageManager) -> Result<(), crate::Error> { write!( &mut name_and_version, "{}@{}", - bstr::BStr::new(name), + bstr::BStr::new(&pkg_name), pkg.resolution.fmt(strbuf, PathSep::Posix) ) .expect("unreachable"); @@ -926,7 +927,7 @@ pub fn prepare_patch(manager: &mut PackageManager) -> Result<(), crate::Error> { let cache_dir_subpath = cache_result.cache_dir_subpath; let module_folder_ = - resolve_path::join::(&[&folder_relative_path, name]); + resolve_path::join::(&[&folder_relative_path, &folder_name]); #[cfg(windows)] let buf = resolve_path::path_to_posix_buf::(module_folder_, &mut win_normalizer[..]) @@ -1220,18 +1221,14 @@ type NodeModulesIterator<'a> = tree::Iterator<'a, { tree::IteratorPathStyle::Nod fn node_modules_folder_for_dependency_ids( iterator: &mut NodeModulesIterator<'_>, ids: &[IdPair], -) -> Option> { +) -> Option<(DependencyID, Vec)> { loop { let node_modules = iterator.next(None)?; - let mut found = false; - for id in ids { - if node_modules.dependencies.contains(&id.0) { - found = true; - break; - } - } - if found { - return Some(node_modules.relative_path.as_bytes().to_vec()); + if let Some(id) = ids + .iter() + .find(|id| node_modules.dependencies.contains(&id.0)) + { + return Some((id.0, node_modules.relative_path.as_bytes().to_vec())); } } } @@ -1251,13 +1248,19 @@ fn node_modules_folder_for_dependency_id( type IdPair = (DependencyID, PackageID); +/// Returns the package that `name` (and `version`, when given) selects, the node_modules folder +/// that holds it, and the name of its folder there. +/// +/// `name` selects a dependency by its name in package.json or by the name of the package it +/// resolves to. An `npm:` alias makes the two differ: the first names the folder, the second keys +/// the patch. fn pkg_info_for_name_and_version( lockfile: &Lockfile, iterator: &mut NodeModulesIterator<'_>, pkg_maybe_version_to_patch: &[u8], name: &[u8], version: Option<&[u8]>, -) -> (PackageID, Vec) { +) -> (PackageID, Vec, Vec) { let mut pairs: Vec = Vec::with_capacity(8); let name_hash = string_hash(name); @@ -1266,15 +1269,28 @@ fn pkg_info_for_name_and_version( let mut resolution_label = Vec::new(); let dependencies = lockfile.buffers.dependencies.as_slice(); + let pkg_name_hashes = lockfile.packages.items_name_hash(); + // The name becomes a path that `bun patch` deletes and writes, the same as an install. + let folder_name = |dep_id: DependencyID| { + let folder_name = dependencies[dep_id as usize].name.slice(strbuf); + if !alias_is_safe_install_target(folder_name) { + bun_core::pretty_errorln!( + "error: refusing to patch dependency with unsafe name {}", + bstr::BStr::new(folder_name), + ); + Global::crash(); + } + folder_name.to_vec() + }; for (dep_id, dep) in dependencies.iter().enumerate() { - if dep.name_hash != name_hash { - continue; - } let pkg_id = lockfile.buffers.resolutions.as_slice()[dep_id]; if pkg_id == invalid_package_id { continue; } + if dep.name_hash != name_hash && pkg_name_hashes[pkg_id as usize] != name_hash { + continue; + } let pkg = *lockfile.packages.get(pkg_id as usize); if let Some(v) = version { if print_resolution_label(&mut resolution_label, &pkg.resolution, strbuf) == v { @@ -1285,6 +1301,10 @@ fn pkg_info_for_name_and_version( } } + // One node_modules folder can hold the package as `name` and under an alias. The folder lookup + // takes the first pair it finds there, so the folder that has `name` goes first. + pairs.sort_by_key(|&(dep_id, _)| dependencies[dep_id as usize].name_hash != name_hash); + if pairs.is_empty() { bun_core::pretty_errorln!( "\nerror: package {} not found", @@ -1307,14 +1327,14 @@ fn pkg_info_for_name_and_version( Global::crash(); } }; - return (pkg_id, folder); + return (pkg_id, folder, folder_name(dep_id)); } // we found multiple dependents of the supplied pkg + version // the final package in the node_modules might be hoisted // so we are going to try looking for each dep id in node_modules let (_, pkg_id) = pairs[0]; - let folder = match node_modules_folder_for_dependency_ids(iterator, &pairs) { + let (dep_id, folder) = match node_modules_folder_for_dependency_ids(iterator, &pairs) { Some(f) => f, None => { bun_core::pretty_error!( @@ -1325,7 +1345,7 @@ fn pkg_info_for_name_and_version( } }; - return (pkg_id, folder); + return (pkg_id, folder, folder_name(dep_id)); } // Otherwise the user did not supply a version, just the pkg name @@ -1343,7 +1363,7 @@ fn pkg_info_for_name_and_version( Global::crash(); } }; - return (pkg_id, folder); + return (pkg_id, folder, folder_name(dep_id)); } // Otherwise we have multiple matches @@ -1366,7 +1386,7 @@ fn pkg_info_for_name_and_version( // Disambiguate case a) from b) if count as usize == pairs.len() { // It may be hoisted, so we'll try the first one that matches - let folder = match node_modules_folder_for_dependency_ids(iterator, &pairs) { + let (dep_id, folder) = match node_modules_folder_for_dependency_ids(iterator, &pairs) { Some(f) => f, None => { bun_core::pretty_error!( @@ -1376,7 +1396,7 @@ fn pkg_info_for_name_and_version( Global::crash(); } }; - return (pkg_id, folder); + return (pkg_id, folder, folder_name(dep_id)); } bun_core::pretty_errorln!( diff --git a/test/cli/install/bun-patch.test.ts b/test/cli/install/bun-patch.test.ts index 0e61d4526398..6f5c780dbcf0 100644 --- a/test/cli/install/bun-patch.test.ts +++ b/test/cli/install/bun-patch.test.ts @@ -1,7 +1,7 @@ import { $, ShellOutput } from "bun"; import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from "bun:test"; import { lstatSync, readFileSync } from "fs"; -import { bunEnv, bunExe, isASAN, tempDir, VerdaccioRegistry } from "harness"; +import { bunEnv, bunExe, isASAN, readdirSorted, tempDir, VerdaccioRegistry } from "harness"; import { isAbsolute, join, sep } from "path"; const expectNoError = (o: ShellOutput) => expect(o.stderr.toString()).not.toContain("error"); @@ -1234,3 +1234,140 @@ describe.concurrent("bun patch --commit for non-registry dependencies", () => { expect(patchKey).toBe("pkg-to-patch@./dep.tgz"); }); }); + +// `"my-alias": "npm:no-deps@1.0.0"` installs the package `no-deps` into `node_modules/my-alias`. +// `bun patch` prints the package's own name and keys the patch by it (`no-deps@1.0.0`), so that +// name has to select the package too, not only the alias. +describe("an npm: aliased dependency", () => { + const registry = new VerdaccioRegistry(); + + beforeAll(async () => { + await registry.start(); + }); + + afterAll(() => { + registry.stop(); + }); + + // CI exports BUN_INSTALL_CACHE_DIR, which overrides the harness bunfig's per-test `cache`. + async function runBun(cwd: string, ...args: string[]) { + await using proc = Bun.spawn({ + cmd: [bunExe(), ...args], + cwd, + env: { ...bunEnv, BUN_INSTALL_CACHE_DIR: join(cwd, ".bun-cache") }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { stdout, stderr, exitCode }; + } + + async function writeProject(dependencies: Record) { + const { packageDir } = await registry.createTestDir({ + bunfigOpts: { linker: "hoisted" }, + files: { "package.json": JSON.stringify({ name: "root", dependencies }) }, + }); + return packageDir; + } + + async function createProject(dependencies: Record) { + const packageDir = await writeProject(dependencies); + const { stderr, exitCode } = await runBun(packageDir, "install"); + expect(stderr).not.toContain("error:"); + expect(exitCode).toBe(0); + return packageDir; + } + + async function expectPrepared(packageDir: string, argument: string, folder: string) { + const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", argument); + expect(stderr).not.toContain("error:"); + expect(stdout).toContain(`To patch no-deps, edit the following folder:\n\n ${folder}\n`); + expect(stdout).toContain(`bun patch --commit '${folder}'`); + expect(exitCode).toBe(0); + } + + for (const argument of ["my-alias", "my-alias@1.0.0", "no-deps", "no-deps@1.0.0"]) { + test.concurrent(`bun patch ${argument}`, async () => { + const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0" }); + await expectPrepared(packageDir, argument, "node_modules/my-alias"); + expect(await readdirSorted(join(packageDir, "node_modules"))).toEqual(["my-alias"]); + }); + } + + test.concurrent("bun patch --commit ", async () => { + const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0" }); + await expectPrepared(packageDir, "no-deps", "node_modules/my-alias"); + await Bun.write(join(packageDir, "node_modules", "my-alias", "index.js"), "module.exports = 'patched';\n"); + + const { stderr, exitCode } = await runBun(packageDir, "patch", "--commit", "no-deps"); + expect(stderr).not.toContain("error:"); + expect(exitCode).toBe(0); + expect((await Bun.file(join(packageDir, "package.json")).json()).patchedDependencies).toEqual({ + "no-deps@1.0.0": "patches/no-deps@1.0.0.patch", + }); + expect(await Bun.file(join(packageDir, "patches", "no-deps@1.0.0.patch")).text()).toContain( + "+module.exports = 'patched';", + ); + expect(await readdirSorted(join(packageDir, "node_modules"))).toEqual(["my-alias"]); + }); + + // A second `bun patch` starts from the patched package, so the next commit keeps the first change. + for (const argument of ["my-alias", "no-deps"]) { + test.concurrent(`bun patch ${argument} of a package that is already patched`, async () => { + const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0" }); + const index = join(packageDir, "node_modules", "my-alias", "index.js"); + await expectPrepared(packageDir, argument, "node_modules/my-alias"); + await Bun.write(index, "module.exports = 'patched';\n"); + const { stderr, exitCode } = await runBun(packageDir, "patch", "--commit", "node_modules/my-alias"); + expect(stderr).not.toContain("error:"); + expect(exitCode).toBe(0); + + await expectPrepared(packageDir, argument, "node_modules/my-alias"); + expect(await Bun.file(index).text()).toBe("module.exports = 'patched';\n"); + }); + } + + test.concurrent("bun patch asks for a version when an alias installs another one", async () => { + const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0", "no-deps": "2.0.0" }); + + const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", "no-deps"); + expect(stderr).toContain( + "error: Found multiple versions of no-deps, please specify a precise version from the following list:\n" + + " no-deps@2.0.0\n" + + " no-deps@1.0.0\n", + ); + expect(stdout).not.toContain("To patch"); + expect(exitCode).toBe(1); + + await expectPrepared(packageDir, "no-deps@1.0.0", "node_modules/my-alias"); + await expectPrepared(packageDir, "no-deps@2.0.0", "node_modules/no-deps"); + await expectPrepared(packageDir, "my-alias", "node_modules/my-alias"); + }); + + test.concurrent( + "bun patch prefers the folder with that name to an alias of the same package", + async () => { + const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0", "no-deps": "1.0.0" }); + await expectPrepared(packageDir, "no-deps", "node_modules/no-deps"); + await expectPrepared(packageDir, "no-deps@1.0.0", "node_modules/no-deps"); + await expectPrepared(packageDir, "my-alias", "node_modules/my-alias"); + }, + ); + + // The alias names the folder. `bun install` refuses to write `node_modules/a/b`, because only + // `@scope/name` can have a `/`, so `bun patch` does not create that folder either. + for (const argument of ["no-deps", "a/b"]) { + test.concurrent(`bun patch ${argument} refuses an alias that bun install refuses`, async () => { + const packageDir = await writeProject({ "a/b": "npm:no-deps@1.0.0" }); + const install = await runBun(packageDir, "install"); + expect(install.stderr).toContain("error: refusing to install dependency with unsafe name a/b\n"); + expect(install.exitCode).toBe(1); + + const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", argument); + expect(stderr).toContain("error: refusing to patch dependency with unsafe name a/b\n"); + expect(stdout).not.toContain("To patch"); + expect(exitCode).toBe(1); + expect(await readdirSorted(join(packageDir, "node_modules"))).toEqual([]); + }); + } +}); From eb2ffca7e005d98ebdc3c4553d784489c617a29a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 22:29:06 +0000 Subject: [PATCH 2/7] bun patch: use the package name only when no dependency has the typed name A name that selects a dependency selects the same dependency and folder as before. The dependencies that only resolve to a package with that name (npm: aliases) are a fallback for when none has it, after the version filter. So an alias of another version somewhere in the tree does not make `bun patch ` ambiguous, and the sort is not needed. The folder lookup returns the pair it found, so the folder, the folder name and the package always come from the same dependency. --- src/install/PackageManager/patchPackage.rs | 40 +++++++++++++--------- test/cli/install/bun-patch.test.ts | 19 +++++++--- 2 files changed, 38 insertions(+), 21 deletions(-) diff --git a/src/install/PackageManager/patchPackage.rs b/src/install/PackageManager/patchPackage.rs index ec92c533a854..17cdedc04aad 100644 --- a/src/install/PackageManager/patchPackage.rs +++ b/src/install/PackageManager/patchPackage.rs @@ -1221,14 +1221,14 @@ type NodeModulesIterator<'a> = tree::Iterator<'a, { tree::IteratorPathStyle::Nod fn node_modules_folder_for_dependency_ids( iterator: &mut NodeModulesIterator<'_>, ids: &[IdPair], -) -> Option<(DependencyID, Vec)> { +) -> Option<(IdPair, Vec)> { loop { let node_modules = iterator.next(None)?; - if let Some(id) = ids + if let Some(&id) = ids .iter() .find(|id| node_modules.dependencies.contains(&id.0)) { - return Some((id.0, node_modules.relative_path.as_bytes().to_vec())); + return Some((id, node_modules.relative_path.as_bytes().to_vec())); } } } @@ -1251,9 +1251,9 @@ type IdPair = (DependencyID, PackageID); /// Returns the package that `name` (and `version`, when given) selects, the node_modules folder /// that holds it, and the name of its folder there. /// -/// `name` selects a dependency by its name in package.json or by the name of the package it -/// resolves to. An `npm:` alias makes the two differ: the first names the folder, the second keys -/// the patch. +/// `name` is the name of a dependency in package.json, which names the folder. An `npm:` alias +/// installs a package under another name. When no dependency has `name`, it selects the +/// dependencies that resolve to a package with that name, the name that keys the patch. fn pkg_info_for_name_and_version( lockfile: &Lockfile, iterator: &mut NodeModulesIterator<'_>, @@ -1262,6 +1262,7 @@ fn pkg_info_for_name_and_version( version: Option<&[u8]>, ) -> (PackageID, Vec, Vec) { let mut pairs: Vec = Vec::with_capacity(8); + let mut aliased: Vec = Vec::new(); let name_hash = string_hash(name); @@ -1288,22 +1289,28 @@ fn pkg_info_for_name_and_version( if pkg_id == invalid_package_id { continue; } - if dep.name_hash != name_hash && pkg_name_hashes[pkg_id as usize] != name_hash { + let matches = if dep.name_hash == name_hash { + &mut pairs + } else if pkg_name_hashes[pkg_id as usize] == name_hash { + &mut aliased + } else { continue; - } + }; let pkg = *lockfile.packages.get(pkg_id as usize); if let Some(v) = version { if print_resolution_label(&mut resolution_label, &pkg.resolution, strbuf) == v { - pairs.push((dep_id as DependencyID, pkg_id)); + matches.push((dep_id as DependencyID, pkg_id)); } } else { - pairs.push((dep_id as DependencyID, pkg_id)); + matches.push((dep_id as DependencyID, pkg_id)); } } - // One node_modules folder can hold the package as `name` and under an alias. The folder lookup - // takes the first pair it finds there, so the folder that has `name` goes first. - pairs.sort_by_key(|&(dep_id, _)| dependencies[dep_id as usize].name_hash != name_hash); + // A fallback, not a union: an alias of another version somewhere in the tree does not make a + // name that selects a dependency ambiguous. + if pairs.is_empty() { + pairs = aliased; + } if pairs.is_empty() { bun_core::pretty_errorln!( @@ -1333,8 +1340,9 @@ fn pkg_info_for_name_and_version( // we found multiple dependents of the supplied pkg + version // the final package in the node_modules might be hoisted // so we are going to try looking for each dep id in node_modules - let (_, pkg_id) = pairs[0]; - let (dep_id, folder) = match node_modules_folder_for_dependency_ids(iterator, &pairs) { + let ((dep_id, pkg_id), folder) = match node_modules_folder_for_dependency_ids( + iterator, &pairs, + ) { Some(f) => f, None => { bun_core::pretty_error!( @@ -1386,7 +1394,7 @@ fn pkg_info_for_name_and_version( // Disambiguate case a) from b) if count as usize == pairs.len() { // It may be hoisted, so we'll try the first one that matches - let (dep_id, folder) = match node_modules_folder_for_dependency_ids(iterator, &pairs) { + let ((dep_id, _), folder) = match node_modules_folder_for_dependency_ids(iterator, &pairs) { Some(f) => f, None => { bun_core::pretty_error!( diff --git a/test/cli/install/bun-patch.test.ts b/test/cli/install/bun-patch.test.ts index 6f5c780dbcf0..72d15595a6ec 100644 --- a/test/cli/install/bun-patch.test.ts +++ b/test/cli/install/bun-patch.test.ts @@ -1327,20 +1327,29 @@ describe("an npm: aliased dependency", () => { }); } - test.concurrent("bun patch asks for a version when an alias installs another one", async () => { - const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0", "no-deps": "2.0.0" }); + test.concurrent("bun patch asks for a version when two aliases install different ones", async () => { + const packageDir = await createProject({ "a1": "npm:no-deps@1.0.0", "a2": "npm:no-deps@2.0.0" }); const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", "no-deps"); expect(stderr).toContain( "error: Found multiple versions of no-deps, please specify a precise version from the following list:\n" + - " no-deps@2.0.0\n" + - " no-deps@1.0.0\n", + " no-deps@1.0.0\n" + + " no-deps@2.0.0\n", ); expect(stdout).not.toContain("To patch"); expect(exitCode).toBe(1); - await expectPrepared(packageDir, "no-deps@1.0.0", "node_modules/my-alias"); + await expectPrepared(packageDir, "no-deps@1.0.0", "node_modules/a1"); + await expectPrepared(packageDir, "no-deps@2.0.0", "node_modules/a2"); + await expectPrepared(packageDir, "a2", "node_modules/a2"); + }); + + // An alias of another version does not make the name of a dependency ambiguous. + test.concurrent("bun patch selects the dependency with that name before an alias", async () => { + const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0", "no-deps": "2.0.0" }); + await expectPrepared(packageDir, "no-deps", "node_modules/no-deps"); await expectPrepared(packageDir, "no-deps@2.0.0", "node_modules/no-deps"); + await expectPrepared(packageDir, "no-deps@1.0.0", "node_modules/my-alias"); await expectPrepared(packageDir, "my-alias", "node_modules/my-alias"); }); From 256be1a6abc5c31ee5eb12221f753a3c3523f722 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 22:31:03 +0000 Subject: [PATCH 3/7] bun patch: shorten two comments in the name lookup --- src/install/PackageManager/patchPackage.rs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/install/PackageManager/patchPackage.rs b/src/install/PackageManager/patchPackage.rs index 17cdedc04aad..ed3e77aea1d7 100644 --- a/src/install/PackageManager/patchPackage.rs +++ b/src/install/PackageManager/patchPackage.rs @@ -1248,12 +1248,7 @@ fn node_modules_folder_for_dependency_id( type IdPair = (DependencyID, PackageID); -/// Returns the package that `name` (and `version`, when given) selects, the node_modules folder -/// that holds it, and the name of its folder there. -/// -/// `name` is the name of a dependency in package.json, which names the folder. An `npm:` alias -/// installs a package under another name. When no dependency has `name`, it selects the -/// dependencies that resolve to a package with that name, the name that keys the patch. +/// Returns the package, the node_modules folder that holds it, and the name of its folder there. fn pkg_info_for_name_and_version( lockfile: &Lockfile, iterator: &mut NodeModulesIterator<'_>, @@ -1306,8 +1301,7 @@ fn pkg_info_for_name_and_version( } } - // A fallback, not a union: an alias of another version somewhere in the tree does not make a - // name that selects a dependency ambiguous. + // Not a union: an alias of another version must not make a dependency's name ambiguous. if pairs.is_empty() { pairs = aliased; } From 9a85dd3c0d74ca41a079672df2a48e2de4ea566a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 22:41:38 +0000 Subject: [PATCH 4/7] bun patch test: use test.concurrent.each, cover a scoped alias and the isolated linker The three argument loops become `test.concurrent.each`. New cases: a scoped alias (`@my/alias`) by alias and by package name, and prepare plus `--commit ` with the isolated linker, where `node_modules/my-alias` is a symlink that `bun patch` detaches. --- test/cli/install/bun-patch.test.ts | 98 ++++++++++++++++++------------ 1 file changed, 60 insertions(+), 38 deletions(-) diff --git a/test/cli/install/bun-patch.test.ts b/test/cli/install/bun-patch.test.ts index 72d15595a6ec..6969170ebcd1 100644 --- a/test/cli/install/bun-patch.test.ts +++ b/test/cli/install/bun-patch.test.ts @@ -1262,16 +1262,16 @@ describe("an npm: aliased dependency", () => { return { stdout, stderr, exitCode }; } - async function writeProject(dependencies: Record) { + async function writeProject(dependencies: Record, linker: "hoisted" | "isolated" = "hoisted") { const { packageDir } = await registry.createTestDir({ - bunfigOpts: { linker: "hoisted" }, + bunfigOpts: { linker }, files: { "package.json": JSON.stringify({ name: "root", dependencies }) }, }); return packageDir; } - async function createProject(dependencies: Record) { - const packageDir = await writeProject(dependencies); + async function createProject(dependencies: Record, linker?: "hoisted" | "isolated") { + const packageDir = await writeProject(dependencies, linker); const { stderr, exitCode } = await runBun(packageDir, "install"); expect(stderr).not.toContain("error:"); expect(exitCode).toBe(0); @@ -1286,13 +1286,39 @@ describe("an npm: aliased dependency", () => { expect(exitCode).toBe(0); } - for (const argument of ["my-alias", "my-alias@1.0.0", "no-deps", "no-deps@1.0.0"]) { - test.concurrent(`bun patch ${argument}`, async () => { - const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0" }); - await expectPrepared(packageDir, argument, "node_modules/my-alias"); - expect(await readdirSorted(join(packageDir, "node_modules"))).toEqual(["my-alias"]); + test.concurrent.each(["my-alias", "my-alias@1.0.0", "no-deps", "no-deps@1.0.0"])("bun patch %s", async argument => { + const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0" }); + await expectPrepared(packageDir, argument, "node_modules/my-alias"); + expect(await readdirSorted(join(packageDir, "node_modules"))).toEqual(["my-alias"]); + }); + + test.concurrent.each(["@my/alias", "no-deps"])("bun patch %s with a scoped alias", async argument => { + const packageDir = await createProject({ "@my/alias": "npm:no-deps@1.0.0" }); + await expectPrepared(packageDir, argument, "node_modules/@my/alias"); + expect(await readdirSorted(join(packageDir, "node_modules"))).toEqual(["@my"]); + }); + + // The isolated linker makes `node_modules/my-alias` a symlink into `node_modules/.bun`. + test.concurrent("bun patch and --commit with the isolated linker", async () => { + const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0" }, "isolated"); + const folder = join(packageDir, "node_modules", "my-alias"); + expect(lstatSync(folder).isSymbolicLink()).toBe(true); + + await expectPrepared(packageDir, "no-deps", "node_modules/my-alias"); + expect(lstatSync(folder).isSymbolicLink()).toBe(false); + expect(await readdirSorted(join(packageDir, "node_modules"))).not.toContain("no-deps"); + await Bun.write(join(folder, "index.js"), "module.exports = 'patched';\n"); + + const { stderr, exitCode } = await runBun(packageDir, "patch", "--commit", "no-deps"); + expect(stderr).not.toContain("error:"); + expect(exitCode).toBe(0); + expect((await Bun.file(join(packageDir, "package.json")).json()).patchedDependencies).toEqual({ + "no-deps@1.0.0": "patches/no-deps@1.0.0.patch", }); - } + expect(await Bun.file(join(packageDir, "patches", "no-deps@1.0.0.patch")).text()).toContain( + "+module.exports = 'patched';", + ); + }); test.concurrent("bun patch --commit ", async () => { const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0" }); @@ -1312,20 +1338,18 @@ describe("an npm: aliased dependency", () => { }); // A second `bun patch` starts from the patched package, so the next commit keeps the first change. - for (const argument of ["my-alias", "no-deps"]) { - test.concurrent(`bun patch ${argument} of a package that is already patched`, async () => { - const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0" }); - const index = join(packageDir, "node_modules", "my-alias", "index.js"); - await expectPrepared(packageDir, argument, "node_modules/my-alias"); - await Bun.write(index, "module.exports = 'patched';\n"); - const { stderr, exitCode } = await runBun(packageDir, "patch", "--commit", "node_modules/my-alias"); - expect(stderr).not.toContain("error:"); - expect(exitCode).toBe(0); - - await expectPrepared(packageDir, argument, "node_modules/my-alias"); - expect(await Bun.file(index).text()).toBe("module.exports = 'patched';\n"); - }); - } + test.concurrent.each(["my-alias", "no-deps"])("bun patch %s of a package that is already patched", async argument => { + const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0" }); + const index = join(packageDir, "node_modules", "my-alias", "index.js"); + await expectPrepared(packageDir, argument, "node_modules/my-alias"); + await Bun.write(index, "module.exports = 'patched';\n"); + const { stderr, exitCode } = await runBun(packageDir, "patch", "--commit", "node_modules/my-alias"); + expect(stderr).not.toContain("error:"); + expect(exitCode).toBe(0); + + await expectPrepared(packageDir, argument, "node_modules/my-alias"); + expect(await Bun.file(index).text()).toBe("module.exports = 'patched';\n"); + }); test.concurrent("bun patch asks for a version when two aliases install different ones", async () => { const packageDir = await createProject({ "a1": "npm:no-deps@1.0.0", "a2": "npm:no-deps@2.0.0" }); @@ -1365,18 +1389,16 @@ describe("an npm: aliased dependency", () => { // The alias names the folder. `bun install` refuses to write `node_modules/a/b`, because only // `@scope/name` can have a `/`, so `bun patch` does not create that folder either. - for (const argument of ["no-deps", "a/b"]) { - test.concurrent(`bun patch ${argument} refuses an alias that bun install refuses`, async () => { - const packageDir = await writeProject({ "a/b": "npm:no-deps@1.0.0" }); - const install = await runBun(packageDir, "install"); - expect(install.stderr).toContain("error: refusing to install dependency with unsafe name a/b\n"); - expect(install.exitCode).toBe(1); - - const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", argument); - expect(stderr).toContain("error: refusing to patch dependency with unsafe name a/b\n"); - expect(stdout).not.toContain("To patch"); - expect(exitCode).toBe(1); - expect(await readdirSorted(join(packageDir, "node_modules"))).toEqual([]); - }); - } + test.concurrent.each(["no-deps", "a/b"])("bun patch %s refuses an alias that bun install refuses", async argument => { + const packageDir = await writeProject({ "a/b": "npm:no-deps@1.0.0" }); + const install = await runBun(packageDir, "install"); + expect(install.stderr).toContain("error: refusing to install dependency with unsafe name a/b\n"); + expect(install.exitCode).toBe(1); + + const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", argument); + expect(stderr).toContain("error: refusing to patch dependency with unsafe name a/b\n"); + expect(stdout).not.toContain("To patch"); + expect(exitCode).toBe(1); + expect(await readdirSorted(join(packageDir, "node_modules"))).toEqual([]); + }); }); From 803787d225a0a4f5830214e209bac59df8312a22 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 19 Sep 2026 17:51:38 +0000 Subject: [PATCH 5/7] bun patch: do not index packages with a resolution id past the end The name lookup reads the resolution id of every dependency since it also matches by package name. It indexed the package list with that id after a check for `invalid_package_id` only, so one bad id in `bun.lockb`, on any dependency, was an index out of bounds. Before this branch only the named dependency's id was read, and that one panicked too (`MultiArrayList::Slice::get: index out of bounds`). Any id past the end now counts as not resolved, the same test as `is_filtered_dependency_or_workspace` in Tree.rs. The loop zips the dependencies with the resolutions, so a short resolutions buffer is not an index either. --- src/install/PackageManager/patchPackage.rs | 11 ++++---- test/cli/install/bun-patch.test.ts | 32 ++++++++++++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/src/install/PackageManager/patchPackage.rs b/src/install/PackageManager/patchPackage.rs index ed3e77aea1d7..11b6afd32ee4 100644 --- a/src/install/PackageManager/patchPackage.rs +++ b/src/install/PackageManager/patchPackage.rs @@ -1279,14 +1279,15 @@ fn pkg_info_for_name_and_version( folder_name.to_vec() }; - for (dep_id, dep) in dependencies.iter().enumerate() { - let pkg_id = lockfile.buffers.resolutions.as_slice()[dep_id]; - if pkg_id == invalid_package_id { + let resolutions = lockfile.buffers.resolutions.as_slice(); + for (dep_id, (dep, &pkg_id)) in dependencies.iter().zip(resolutions).enumerate() { + // `invalid_package_id` and any other id past the end: the dependency did not resolve. + let Some(&pkg_name_hash) = pkg_name_hashes.get(pkg_id as usize) else { continue; - } + }; let matches = if dep.name_hash == name_hash { &mut pairs - } else if pkg_name_hashes[pkg_id as usize] == name_hash { + } else if pkg_name_hash == name_hash { &mut aliased } else { continue; diff --git a/test/cli/install/bun-patch.test.ts b/test/cli/install/bun-patch.test.ts index 6969170ebcd1..82a8709b791c 100644 --- a/test/cli/install/bun-patch.test.ts +++ b/test/cli/install/bun-patch.test.ts @@ -1387,6 +1387,38 @@ describe("an npm: aliased dependency", () => { }, ); + // `bun.lockb` is read as is. One resolution id past the end of the package list used to be an + // index out of bounds when the id belonged to the named dependency. The name lookup now reads + // the id of every dependency, so it must not trust any of them. + test.concurrent.each([ + ["another dependency", 0, "failed to resolve"], + ["the named dependency", 1, "error: package no-deps not found"], + ])("bun patch --commit with a resolution id past the end for %s", async (_, index, message) => { + const { packageDir } = await registry.createTestDir({ + bunfigOpts: { linker: "hoisted", saveTextLockfile: false }, + files: { + "package.json": JSON.stringify({ name: "root", dependencies: { "a-dep": "1.0.1", "no-deps": "1.0.0" } }), + }, + }); + expect((await runBun(packageDir, "install")).exitCode).toBe(0); + await expectPrepared(packageDir, "no-deps", "node_modules/no-deps"); + + // `buffers.resolutions` is the second u32 array. Its [start, end) offsets come before the prefix. + const lockb = Buffer.from(await Bun.file(join(packageDir, "bun.lockb")).arrayBuffer()); + const prefix = "\n 4 sizeof, 4 alignof\n"; + const at = lockb.indexOf(prefix, lockb.indexOf(prefix) + 1); + const start = Number(lockb.readBigUInt64LE(at - 16)); + const end = Number(lockb.readBigUInt64LE(at - 8)); + expect((end - start) / 4).toBe(2); + lockb.writeUInt32LE(0x7fffffff, start + 4 * index); + await Bun.write(join(packageDir, "bun.lockb"), lockb); + + const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", "--commit", "no-deps"); + expect(stderr).toContain(message); + expect(stdout).not.toContain("To patch"); + expect(exitCode).toBe(1); + }); + // The alias names the folder. `bun install` refuses to write `node_modules/a/b`, because only // `@scope/name` can have a `/`, so `bun patch` does not create that folder either. test.concurrent.each(["no-deps", "a/b"])("bun patch %s refuses an alias that bun install refuses", async argument => { From 39a768bbee5fcb38fc19fa65d2a795cf459198cc Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 19 Sep 2026 18:31:18 +0000 Subject: [PATCH 6/7] bun patch: quote the unsafe name in the refusal message The refused name comes from the lockfile. The message printed it raw, so a name with ESC, CR or LF wrote control characters to the terminal. `bun_fmt::quote` escapes them, as the other messages in this file do for paths. The corrupt lockfile test asserted that `--commit` does not print "To patch", which it never prints. It now checks that no patch file and no `patchedDependencies` entry were written. --- src/install/PackageManager/patchPackage.rs | 4 ++-- test/cli/install/bun-patch.test.ts | 20 +++++++++++++++++--- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/install/PackageManager/patchPackage.rs b/src/install/PackageManager/patchPackage.rs index 11b6afd32ee4..3dda89ccc26d 100644 --- a/src/install/PackageManager/patchPackage.rs +++ b/src/install/PackageManager/patchPackage.rs @@ -1271,8 +1271,8 @@ fn pkg_info_for_name_and_version( let folder_name = dependencies[dep_id as usize].name.slice(strbuf); if !alias_is_safe_install_target(folder_name) { bun_core::pretty_errorln!( - "error: refusing to patch dependency with unsafe name {}", - bstr::BStr::new(folder_name), + "error: refusing to patch dependency with unsafe name {}", + bun_fmt::quote(folder_name), ); Global::crash(); } diff --git a/test/cli/install/bun-patch.test.ts b/test/cli/install/bun-patch.test.ts index 82a8709b791c..6c81ca685e13 100644 --- a/test/cli/install/bun-patch.test.ts +++ b/test/cli/install/bun-patch.test.ts @@ -1,6 +1,6 @@ import { $, ShellOutput } from "bun"; import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from "bun:test"; -import { lstatSync, readFileSync } from "fs"; +import { existsSync, lstatSync, readFileSync } from "fs"; import { bunEnv, bunExe, isASAN, readdirSorted, tempDir, VerdaccioRegistry } from "harness"; import { isAbsolute, join, sep } from "path"; @@ -1387,6 +1387,19 @@ describe("an npm: aliased dependency", () => { }, ); + // The refused name comes from the lockfile, so the message must not print its control characters. + test.concurrent("bun patch escapes the unsafe name that it refuses", async () => { + const packageDir = await writeProject({ "a/\x1b[31mRED\x1b[0m\rFAKE\nsecond": "npm:no-deps@1.0.0" }); + expect((await runBun(packageDir, "install")).exitCode).toBe(1); + + const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", "no-deps"); + expect(stderr).toContain( + String.raw`error: refusing to patch dependency with unsafe name "a/\u001B[31mRED\u001B[0m\rFAKE\nsecond"` + "\n", + ); + expect(stdout).not.toContain("To patch"); + expect(exitCode).toBe(1); + }); + // `bun.lockb` is read as is. One resolution id past the end of the package list used to be an // index out of bounds when the id belonged to the named dependency. The name lookup now reads // the id of every dependency, so it must not trust any of them. @@ -1415,8 +1428,9 @@ describe("an npm: aliased dependency", () => { const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", "--commit", "no-deps"); expect(stderr).toContain(message); - expect(stdout).not.toContain("To patch"); expect(exitCode).toBe(1); + expect(existsSync(join(packageDir, "patches"))).toBe(false); + expect((await Bun.file(join(packageDir, "package.json")).json()).patchedDependencies).toBeUndefined(); }); // The alias names the folder. `bun install` refuses to write `node_modules/a/b`, because only @@ -1428,7 +1442,7 @@ describe("an npm: aliased dependency", () => { expect(install.exitCode).toBe(1); const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", argument); - expect(stderr).toContain("error: refusing to patch dependency with unsafe name a/b\n"); + expect(stderr).toContain('error: refusing to patch dependency with unsafe name "a/b"\n'); expect(stdout).not.toContain("To patch"); expect(exitCode).toBe(1); expect(await readdirSorted(join(packageDir, "node_modules"))).toEqual([]); From 6d84aec0cf806bac621ffc8144875d46eed1ba33 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 19 Sep 2026 19:05:11 +0000 Subject: [PATCH 7/7] bun patch test: share one registry and one runBun across the describe blocks The new block started a second Verdaccio and repeated the `runBun` helper of "packages whose label is longer than 1024 bytes". Both now live at file scope. --- test/cli/install/bun-patch.test.ts | 71 ++++++++++-------------------- 1 file changed, 24 insertions(+), 47 deletions(-) diff --git a/test/cli/install/bun-patch.test.ts b/test/cli/install/bun-patch.test.ts index 6c81ca685e13..111ece2a613c 100644 --- a/test/cli/install/bun-patch.test.ts +++ b/test/cli/install/bun-patch.test.ts @@ -10,6 +10,30 @@ const platformPath = (path: string) => path; setDefaultTimeout(1000 * 60 * 5); +const registry = new VerdaccioRegistry(); + +beforeAll(async () => { + await registry.start(); +}); + +afterAll(() => { + registry.stop(); +}); + +// CI exports BUN_INSTALL_CACHE_DIR, which overrides the harness bunfig's per-test `cache`. Two of these concurrent +// tests install the same tarball spec; sharing one cache, they replace each other's `@T@` folder on Windows. +async function runBun(cwd: string, ...args: string[]) { + await using proc = Bun.spawn({ + cmd: [bunExe(), ...args], + cwd, + env: { ...bunEnv, BUN_INSTALL_CACHE_DIR: join(cwd, ".bun-cache") }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { stdout, stderr, exitCode }; +} + describe("error messages", () => { test("'bun patch' with no package name shows a usage example", async () => { await using dir = tempDir("bun-patch-noarg", { @@ -71,16 +95,6 @@ describe("error messages", () => { // stack buffers (512 bytes in the installer itself), so a long enough spec crashed // every command that formatted it. describe("packages whose label is longer than 1024 bytes", () => { - const registry = new VerdaccioRegistry(); - - beforeAll(async () => { - await registry.start(); - }); - - afterAll(() => { - registry.stop(); - }); - // `x/../` normalizes away, so the tarball still lives at a short path that is valid // on every platform while the recorded spec stays long. const longSpec = (tarball: string) => `./${Buffer.alloc(1050, "x/../").toString()}${tarball}`; @@ -96,20 +110,6 @@ describe("packages whose label is longer than 1024 bytes", () => { return packageDir; } - // CI exports BUN_INSTALL_CACHE_DIR, which overrides the harness bunfig's per-test `cache`. Two of these concurrent - // tests install the same tarball spec; sharing one cache, they replace each other's `@T@` folder on Windows. - async function runBun(cwd: string, ...args: string[]) { - await using proc = Bun.spawn({ - cmd: [bunExe(), ...args], - cwd, - env: { ...bunEnv, BUN_INSTALL_CACHE_DIR: join(cwd, ".bun-cache") }, - stdout: "pipe", - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - return { stdout, stderr, exitCode }; - } - async function install(cwd: string) { const { stderr, exitCode } = await runBun(cwd, "install"); expect(stderr).not.toContain("error:"); @@ -1239,29 +1239,6 @@ describe.concurrent("bun patch --commit for non-registry dependencies", () => { // `bun patch` prints the package's own name and keys the patch by it (`no-deps@1.0.0`), so that // name has to select the package too, not only the alias. describe("an npm: aliased dependency", () => { - const registry = new VerdaccioRegistry(); - - beforeAll(async () => { - await registry.start(); - }); - - afterAll(() => { - registry.stop(); - }); - - // CI exports BUN_INSTALL_CACHE_DIR, which overrides the harness bunfig's per-test `cache`. - async function runBun(cwd: string, ...args: string[]) { - await using proc = Bun.spawn({ - cmd: [bunExe(), ...args], - cwd, - env: { ...bunEnv, BUN_INSTALL_CACHE_DIR: join(cwd, ".bun-cache") }, - stdout: "pipe", - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - return { stdout, stderr, exitCode }; - } - async function writeProject(dependencies: Record, linker: "hoisted" | "isolated" = "hoisted") { const { packageDir } = await registry.createTestDir({ bunfigOpts: { linker },