From 33d4aa4eb1a073086b0a8266d00f63c0ad41b57c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 8 Sep 2026 05:57:50 +0000 Subject: [PATCH 01/13] install: check peer ranges in the linkers, against the copy each dependent resolves The resolver bound a peer to any package in the lockfile whose version satisfied the range and warned only when none did. Both linkers then serve the dependent whatever copy its position resolves (the hoisted tree dedupes a peer onto a root dependency regardless of range, the isolated store takes the nearest ancestor's dependency of that name), so a dependent could load an out-of-range copy with no warning, and the warning that did exist named neither the dependent nor the range. The range check now runs where the copy is chosen: in the hoisted tree built for the install and in the isolated store builder. It compares the copy actually served against the range the resolver enforces (overrides, then catalogs), names the dependent, and runs on every install. The resolver keeps its binding behaviour and no longer warns. Fixes #7403 --- .../PackageManager/PackageManagerEnqueue.rs | 68 ++----- src/install/isolated_install.rs | 42 ++--- src/install/lockfile.rs | 110 ++++++++++++ src/install/lockfile/Tree.rs | 101 +++++++---- test/cli/install/bun-install-registry.test.ts | 167 +++++++++++++++++- 5 files changed, 382 insertions(+), 106 deletions(-) diff --git a/src/install/PackageManager/PackageManagerEnqueue.rs b/src/install/PackageManager/PackageManagerEnqueue.rs index 990321e3d219..dacd973ffe4b 100644 --- a/src/install/PackageManager/PackageManagerEnqueue.rs +++ b/src/install/PackageManager/PackageManagerEnqueue.rs @@ -2538,30 +2538,13 @@ fn get_or_put_resolved_package( })); } - let res_tag = resolutions[existing_id as usize].tag; - let ver_tag = version.tag; - if (res_tag == ResolutionTag::Npm - && ver_tag == dependency::version::Tag::Npm) - || (res_tag == ResolutionTag::Git - && ver_tag == dependency::version::Tag::Git) - || (res_tag == ResolutionTag::Github - && ver_tag == dependency::version::Tag::Github) - { - let existing_package = this.lockfile.packages.get(existing_id as usize); - this.log_mut().add_warning_fmt( - None, - bun_ast::Loc::EMPTY, - format_args!( - "incorrect peer dependency \"{}@{}\"", - existing_package - .name - .fmt(this.lockfile.buffers.string_bytes.as_slice()), - existing_package.resolution.fmt( - this.lockfile.buffers.string_bytes.as_slice(), - bun_fmt::PathSep::Auto - ), - ), - ); + // Nothing satisfies the range: bind the copy that exists anyway. The + // linker reports the mismatch against the copy it actually serves + // (`Lockfile::warn_if_peer_out_of_range`), which may be a different one. + if peer_binds_out_of_range( + resolutions[existing_id as usize].tag, + version.tag, + ) { success_fn(this, dependency_id, existing_id); return Ok(Some(ResolvedPackageResult { // we must fetch it from the packages array again, incase the package array mutates the value in the `successFn` @@ -2587,32 +2570,8 @@ fn get_or_put_resolved_package( } if (list[0] as usize) < resolutions.len() { - let res_tag = resolutions[list[0] as usize].tag; - let ver_tag = version.tag; - if (res_tag == ResolutionTag::Npm - && ver_tag == dependency::version::Tag::Npm) - || (res_tag == ResolutionTag::Git - && ver_tag == dependency::version::Tag::Git) - || (res_tag == ResolutionTag::Github - && ver_tag == dependency::version::Tag::Github) - { + if peer_binds_out_of_range(resolutions[list[0] as usize].tag, version.tag) { let existing_package_id = list[0]; - let existing_package = - this.lockfile.packages.get(existing_package_id as usize); - this.log_mut().add_warning_fmt( - None, - bun_ast::Loc::EMPTY, - format_args!( - "incorrect peer dependency \"{}@{}\"", - existing_package - .name - .fmt(this.lockfile.buffers.string_bytes.as_slice()), - existing_package.resolution.fmt( - this.lockfile.buffers.string_bytes.as_slice(), - bun_fmt::PathSep::Auto - ), - ), - ); success_fn(this, dependency_id, list[0]); return Ok(Some(ResolvedPackageResult { // we must fetch it from the packages array again, incase the package array mutates the value in the `successFn` @@ -3147,6 +3106,17 @@ fn resolution_satisfies_dependency( resolution.satisfies_dependency_version(dependency, buf, buf) } +/// A peer nothing in the lockfile satisfies still binds to an existing copy of the same kind +/// instead of pulling in its own version. +fn peer_binds_out_of_range(existing: ResolutionTag, range: dependency::version::Tag) -> bool { + matches!( + (existing, range), + (ResolutionTag::Npm, dependency::version::Tag::Npm) + | (ResolutionTag::Git, dependency::version::Tag::Git) + | (ResolutionTag::Github, dependency::version::Tag::Github) + ) +} + fn patched_package_satisfying( this: &PackageManager, name_hash: PackageNameHash, diff --git a/src/install/isolated_install.rs b/src/install/isolated_install.rs index 65128085d4be..6df6e9c4c2b7 100644 --- a/src/install/isolated_install.rs +++ b/src/install/isolated_install.rs @@ -398,6 +398,10 @@ pub(crate) fn build_store( let mut visited_parent_node_ids: Vec = Vec::new(); + // A package is visited once per peer context, so the same edge can resolve the same way many + // times; each distinct `(peer edge, resolved package)` is range-checked once. + let mut reported_peers: HashMap<(DependencyID, PackageID), ()> = HashMap::default(); + // First pass: create full dependency tree with resolved peers 'next_node: while let Some(entry) = node_queue.pop() { 'check_cycle: { @@ -745,24 +749,8 @@ pub(crate) fn build_store( continue; } - let res = &pkg_resolutions[ids.pkg_id as usize]; - - if peer_dep.version.tag != VersionTag::Npm || res.tag != ResolutionTag::Npm - { - // TODO: print warning for this? we don't have a version - // to compare to say if this satisfies or not. - break 'resolved_pkg_id (ids.pkg_id, false); - } - - // SAFETY: tag was checked == .Npm directly above for both - // `peer_dep.version` and `res`. - let peer_dep_version = &peer_dep.version.npm().version; - let res_version = &res.npm().version; - - if !peer_dep_version.satisfies(*res_version, string_buf, string_buf) { - // TODO: add warning! - } - + // The nearest ancestor that provides the name wins whether or not its + // version is in range; the range is checked once the peer is resolved. break 'resolved_pkg_id (ids.pkg_id, false); } @@ -780,8 +768,6 @@ pub(crate) fn build_store( if !ids.auto_installed { // The resolution was found here or above. Choose the same // peer resolution. No need to mark this node or above. - - // TODO: add warning if not satisfies()! break 'resolved_pkg_id (ids.pkg_id, false); } @@ -827,6 +813,22 @@ pub(crate) fn build_store( continue; } + if packages_to_install.is_none() + && !dependencies[peer_dep_id as usize] + .behavior + .is_optional_peer() + && reported_peers + .insert((peer_dep_id, resolved_pkg_id), ()) + .is_none() + { + lockfile.warn_if_peer_out_of_range( + manager.log_mut(), + entry.pkg_id, + peer_dep_id, + resolved_pkg_id, + ); + } + for &visited_parent_id in &visited_parent_node_ids { let ctx = store::node::TransitivePeerOrderedArraySetCtx { string_buf, diff --git a/src/install/lockfile.rs b/src/install/lockfile.rs index 3e473b67b8c3..c3ab79d94253 100644 --- a/src/install/lockfile.rs +++ b/src/install/lockfile.rs @@ -2,6 +2,7 @@ use core::cmp::Ordering; use core::fmt; +use std::borrow::Cow; use std::io::Write as _; use crate::Error as BunError; @@ -97,6 +98,13 @@ type ResolutionTag = resolution::Tag; type SemverStringBuf<'a> = bun_semver::semver_string::Buf<'a>; type SemverStringBuilder = bun_semver::semver_string::Builder; +/// See [`Lockfile::enforced_range`]. +pub(crate) struct EnforcedRange<'a> { + pub version: Cow<'a, DependencyVersion>, + /// The range came from an `overrides` rule rather than the dependent's manifest. + pub overridden: bool, +} + // ──────────────────────────────────────────────────────────────────────────── // Type aliases / collection types // ──────────────────────────────────────────────────────────────────────────── @@ -748,6 +756,107 @@ impl Lockfile { Some(catalog_dep.version) } + /// The range the resolver resolves an edge against: an `overrides` rule replaces the declared + /// range, then a `catalog:` reference is looked up. Mirrors + /// `enqueue_dependency_with_main_and_success_fn`, minus its per-session npm alias redirects. + pub(crate) fn enforced_range(&self, dep_id: DependencyID) -> EnforcedRange<'_> { + use dependency::DependencyExt as _; + + let buf = self.buffers.string_bytes.as_slice(); + let dep = &self.buffers.dependencies[dep_id as usize]; + + let overridable = !dep.behavior.is_workspace() + && (dep.version.tag != dependency::Tag::Npm || !dep.version.npm().is_alias); + if overridable && !self.overrides.is_empty() { + let name = dep.realname(); + let name_hash = match dep.version.tag { + dependency::Tag::DistTag + | dependency::Tag::Git + | dependency::Tag::Github + | dependency::Tag::Npm + | dependency::Tag::Tarball + | dependency::Tag::Workspace => SemverStringBuilder::string_hash(name.slice(buf)), + _ => dep.name_hash, + }; + if let Some(rule) = self.overrides.get(self, dep_id, name_hash) { + if rule.tag == dependency::Tag::Catalog { + if let Some(entry) = self.catalogs.get_ref(buf, *rule.catalog(), name) { + return EnforcedRange { + version: Cow::Borrowed(&entry.version), + overridden: true, + }; + } + } + return EnforcedRange { + version: Cow::Owned(rule), + overridden: true, + }; + } + } + + EnforcedRange { + version: Cow::Borrowed(self.catalogs.resolve_range(buf, dep)), + overridden: false, + } + } + + /// A linker calls this with the package it wires a peer edge of `dependent` to. Warns when + /// that package is outside the range the edge enforces. Only like kinds are compared (an npm + /// range against an npm version, a git range against a git resolution): a peer served by a + /// workspace, folder or tarball package has nothing to reject. + pub(crate) fn warn_if_peer_out_of_range( + &self, + log: &mut bun_ast::Log, + dependent: PackageID, + peer_dep_id: DependencyID, + served: PackageID, + ) { + let dep = &self.buffers.dependencies[peer_dep_id as usize]; + debug_assert!(dep.behavior.is_peer()); + if dep.behavior.is_optional_peer() { + return; + } + let pkg_resolutions = self.packages.items_resolution(); + let served_res = &pkg_resolutions[served as usize]; + let range = self.enforced_range(peer_dep_id); + let comparable = matches!( + (served_res.tag, range.version.tag), + (ResolutionTag::Npm, dependency::Tag::Npm) + | (ResolutionTag::Git, dependency::Tag::Git) + | (ResolutionTag::Github, dependency::Tag::Github) + ); + let buf = self.buffers.string_bytes.as_slice(); + if !comparable || served_res.satisfies_dependency_version(&range.version, buf, buf) { + return; + } + + let pkg_names = self.packages.items_name(); + let dependent_res = &pkg_resolutions[dependent as usize]; + let dependent_name = pkg_names[dependent as usize].slice(buf); + log.add_warning_fmt( + None, + bun_ast::Loc::EMPTY, + format_args!( + "incorrect peer dependency \"{}@{}\" ({}{}{} requires \"{}\"{})", + bstr::BStr::new(pkg_names[served as usize].slice(buf)), + served_res.fmt(buf, PathSep::Auto), + bstr::BStr::new(if dependent_name.is_empty() && dependent == 0 { + b"package.json".as_slice() + } else { + dependent_name + }), + if dependent_res.tag == ResolutionTag::Root { + "" + } else { + "@" + }, + dependent_res.fmt(buf, PathSep::Posix), + bstr::BStr::new(range.version.literal.slice(buf)), + if range.overridden { " by override" } else { "" }, + ), + ); + } + /// Is this a direct dependency of the workspace root package.json? pub(crate) fn is_workspace_root_dependency(&self, id: DependencyID) -> bool { self.packages.items_dependencies()[0].contains(id) @@ -1394,6 +1503,7 @@ impl Lockfile { packages_to_install, pending_optional_peers: Default::default(), late_bound_optional_peer: false, + reported_peers: Default::default(), list: Default::default(), sort_buf: Default::default(), }; diff --git a/src/install/lockfile/Tree.rs b/src/install/lockfile/Tree.rs index 6d9a998d001b..d2a32ec48980 100644 --- a/src/install/lockfile/Tree.rs +++ b/src/install/lockfile/Tree.rs @@ -2,7 +2,7 @@ use core::marker::ConstParamTy; use core::mem::MaybeUninit; use bun_alloc::AllocError; -use bun_collections::{ArrayHashMap, DynamicBitSet, MultiArrayList, index_sort}; +use bun_collections::{ArrayHashMap, DynamicBitSet, HashMap, MultiArrayList, index_sort}; use bun_core::Output; use bun_core::ZStr; use bun_paths::{MAX_PATH_BYTES, PathBuffer, SEP}; @@ -127,8 +127,9 @@ enum HoistDependencyResult { Resolve(PackageID), ResolveReplace(ResolveReplace), ResolveLater, - /// `Hoisted`, plus the optional peer's slot now points at the version it deduplicated onto. - Rebind(PackageID), + /// `Hoisted`, for a peer: nothing is placed and the dependent resolves this other package, + /// already on its path, instead of the one the edge is bound to. + Dedupe(PackageID), Placement(Placement), } @@ -436,6 +437,9 @@ pub struct Builder<'a, const METHOD: BuilderMethod> { ArrayHashMap>, /// An optional peer got bound after its dependent was placed; see `Lockfile::resolve`. pub(crate) late_bound_optional_peer: bool, + /// `(peer edge, package it is served by)` pairs already checked by `report_peer`, so a + /// dependent placed at several paths is reported once per distinct outcome. + pub(crate) reported_peers: HashMap<(DependencyID, PackageID), ()>, pub(crate) manager: Option<&'a PackageManager>, pub(crate) sort_buf: Vec, pub(crate) workspace_filters: &'a [WorkspaceFilter], @@ -483,6 +487,23 @@ impl<'a, const METHOD: BuilderMethod> Builder<'a, METHOD> { let _ = self.log.add_error_fmt(None, bun_ast::Loc::EMPTY, args); } + /// The tree being installed decided which package `dependent` resolves for its peer edge + /// `dep_id`; warn if that package is outside the peer's range. The saved (`Resolvable`) tree + /// is built on every load and is not what ends up on disk, so it stays quiet, as does the + /// partial tree built to install a security scanner ahead of the real install. + fn report_peer(&mut self, dependent: PackageID, dep_id: DependencyID, served: PackageID) { + if METHOD != BuilderMethod::Filter || self.packages_to_install.is_some() { + return; + } + if self.reported_peers.insert((dep_id, served), ()).is_some() { + return; + } + let lockfile = self.lockfile; + lockfile + .get() + .warn_if_peer_out_of_range(self.log, dependent, dep_id, served); + } + fn buf(&self) -> &[u8] { self.lockfile().buffers.string_bytes.as_slice() } @@ -792,20 +813,21 @@ impl Tree { if pkg_resolutions[pkg_id as usize].tag == crate::resolution::Tag::Folder { // A peer an ancestor edge already provides dedupes instead of nesting // a second copy of the folder (#40561). - if dependency.behavior.is_peer() - && matches!( - Tree::hoist_dependency::( - next_id, - hoist_root_id, - pkg_id, - dep_id, - resolution_list, - builder, - ), - HoistDependencyResult::Hoisted - ) - { - break 'hoisted HoistDependencyResult::Hoisted; + if dependency.behavior.is_peer() { + let probe = Tree::hoist_dependency::( + next_id, + hoist_root_id, + pkg_id, + dep_id, + resolution_list, + builder, + ); + if matches!( + probe, + HoistDependencyResult::Hoisted | HoistDependencyResult::Dedupe(_) + ) { + break 'hoisted probe; + } } // Folder packages never hoist, so a cycle between them would nest forever. @@ -839,7 +861,12 @@ impl Tree { }; match hoisted { - HoistDependencyResult::DependencyLoop | HoistDependencyResult::Hoisted => continue, + HoistDependencyResult::DependencyLoop => continue, + HoistDependencyResult::Hoisted => { + if dependency.behavior.is_peer() && !dependency.behavior.is_optional_peer() { + builder.report_peer(parent_pkg_id, dep_id, pkg_id); + } + } HoistDependencyResult::Resolve(res_id) => { debug_assert!(pkg_id == invalid_package_id); @@ -906,9 +933,17 @@ impl Tree { })?; } } - HoistDependencyResult::Rebind(res_id) => { - debug_assert!(dependency.behavior.is_optional_peer()); - builder.resolutions[dep_id as usize] = res_id; + HoistDependencyResult::Dedupe(res_id) => { + debug_assert!(dependency.behavior.is_peer()); + if dependency.behavior.is_optional_peer() { + // An optional peer's binding follows the dedupe, but only in the tree + // being saved. + if METHOD == BuilderMethod::Resolvable { + builder.resolutions[dep_id as usize] = res_id; + } + } else { + builder.report_peer(parent_pkg_id, dep_id, res_id); + } } HoistDependencyResult::ResolveLater => { // `dep_id` is an unresolved optional peer. while hoisting it deduplicated @@ -932,6 +967,9 @@ impl Tree { .dependencies .len += 1; } + if dependency.behavior.is_peer() && !dependency.behavior.is_optional_peer() { + builder.report_peer(parent_pkg_id, dep_id, pkg_id); + } if pkg_id != invalid_package_id && builder.resolution_lists[pkg_id as usize].len > 0 { @@ -1027,6 +1065,9 @@ impl Tree { if input_dep_range.contains(dep_id) { // same package lists this name in another dependency group + if dependency.behavior.is_peer() && !dependency.behavior.is_optional_peer() { + return HoistDependencyResult::Dedupe(res_id); // 1 + } return HoistDependencyResult::Hoisted; // 1 } @@ -1034,16 +1075,6 @@ impl Tree { // or hoist if peer version allows it if dependency.behavior.is_peer() { - // An optional peer's binding follows the dedupe, but only in the tree being saved. - let dedupe = || { - if METHOD == BuilderMethod::Resolvable && dependency.behavior.is_optional_peer() - { - HoistDependencyResult::Rebind(res_id) - } else { - HoistDependencyResult::Hoisted - } - }; - let peer_range: &crate::dependency::Version = builder .lockfile() .catalogs @@ -1055,15 +1086,15 @@ impl Tree { if resolution.tag == crate::resolution::Tag::Npm && version.satisfies(resolution.npm().version, builder.buf(), builder.buf()) { - return dedupe(); // 1 + return HoistDependencyResult::Dedupe(res_id); // 1 } } // Root dependencies are manually chosen by the user. Allow them - // to hoist other peers even if they don't satisfy the version + // to hoist other peers even if they don't satisfy the version; + // the tree being installed reports the mismatch (`Builder::report_peer`). if builder.lockfile().is_workspace_root_dependency(dep_id) { - // TODO: warning about peer dependency version mismatch - return dedupe(); // 1 + return HoistDependencyResult::Dedupe(res_id); // 1 } } diff --git a/test/cli/install/bun-install-registry.test.ts b/test/cli/install/bun-install-registry.test.ts index dc76901d5a69..ebcd482c2899 100644 --- a/test/cli/install/bun-install-registry.test.ts +++ b/test/cli/install/bun-install-registry.test.ts @@ -1,8 +1,9 @@ import { file, spawn, write } from "bun"; import { install_test_helpers, npm_manifest_test_helpers } from "bun:internal-for-testing"; import { afterAll, beforeAll, beforeEach, describe, expect, setDefaultTimeout, test } from "bun:test"; -import { copyFileSync, mkdirSync } from "fs"; +import { copyFileSync, mkdirSync, realpathSync } from "fs"; import { cp, exists, lstat, mkdir, readlink, rename, rm, writeFile } from "fs/promises"; +import { createRequire } from "module"; import { assertManifestsPopulated, bunExe, @@ -67,6 +68,14 @@ function registryUrl() { return registry.registryUrl(); } +/** The `incorrect peer dependency` lines of an install's stderr, sorted (their order follows the tree walk). */ +function peerWarnings(stderr: string): string[] { + return stderr + .split(/\r?\n/) + .filter(line => line.includes("incorrect peer dependency")) + .sort(); +} + /** * Returns auth token */ @@ -4256,6 +4265,11 @@ describe("hoisting", async () => { expect(err).toContain("Saved lockfile"); expect(err).not.toContain("not found"); expect(err).not.toContain("error:"); + // The resolver does not run again for peer-deps-fixed, but the tree now serves its peer from + // the root's 2.0.0, and the linker reports that. + expect(peerWarnings(err)).toEqual([ + `warn: incorrect peer dependency "no-deps@2.0.0" (peer-deps-fixed@1.0.0 requires "^1.0.0")`, + ]); expect(out.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ expect.stringContaining("bun install v1."), @@ -4380,7 +4394,11 @@ describe("hoisting", async () => { expect(err).toContain("Saved lockfile"); expect(err).not.toContain("not found"); expect(err).not.toContain("error:"); - expect(err).toContain("incorrect peer dependency"); + // One line, naming the dependent and its range (the resolver alone used to print + // `incorrect peer dependency "no-deps@2.0.0"` with neither). + expect(peerWarnings(err)).toEqual([ + `warn: incorrect peer dependency "no-deps@2.0.0" (peer-deps-fixed@1.0.0 requires "^1.0.0")`, + ]); expect(out.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ expect.stringContaining("bun install v1."), @@ -4432,6 +4450,7 @@ describe("hoisting", async () => { expect(err).toContain("Saved lockfile"); expect(err).not.toContain("not found"); expect(err).not.toContain("error:"); + expect(peerWarnings(err)).toEqual([]); expect(out.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ expect.stringContaining("bun install v1."), @@ -4458,6 +4477,150 @@ describe("hoisting", async () => { expect(await exists(join(packageDir, "node_modules", "peer-deps-fixed", "node_modules"))).toBeFalse(); }); + // The linker that lays out node_modules decides which copy of a peer a package resolves, so it + // is the one that checks the peer's range: on every install, for both linkers, naming the + // dependent (#7403). The cases below get the same report from either linker. + describe.each(["hoisted", "isolated"] as const)("peer a dependent cannot resolve in range (%s linker)", linker => { + async function install(dir: string, ...args: string[]) { + await using proc = spawn({ + cmd: [bunExe(), "install", "--linker", linker, ...args], + cwd: dir, + stdout: "pipe", + stdin: "ignore", + stderr: "pipe", + env, + }); + const [out, err, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(err).not.toContain("error:"); + expect(exitCode).toBe(0); + return { out, err }; + } + + /** The version of `no-deps` that `dependent` loads at runtime, resolved from its real directory. */ + async function noDepsSeenBy(dir: string, dependent: string): Promise { + const from = realpathSync(join(dir, "node_modules", dependent, "package.json")); + return (await file(createRequire(from).resolve("no-deps/package.json")).json()).version; + } + + test("a satisfying copy nested elsewhere does not hide that the dependent gets the root's copy", async () => { + // one-fixed-dep nests no-deps@1.0.0, which satisfies peer-deps-fixed's `^1.0.0`, but + // peer-deps-fixed sits next to the root's no-deps@2.0.0 and that is what it loads. The + // resolver bound the peer to the nested 1.0.0 and said nothing. + const { packageDir, packageJson } = await registry.createTestDir({ bunfigOpts: { linker } }); + await write( + packageJson, + JSON.stringify({ + name: "foo", + dependencies: { "one-fixed-dep": "1.0.0", "no-deps": "2.0.0", "peer-deps-fixed": "1.0.0" }, + }), + ); + + const expected = [`warn: incorrect peer dependency "no-deps@2.0.0" (peer-deps-fixed@1.0.0 requires "^1.0.0")`]; + expect(peerWarnings((await install(packageDir)).err)).toEqual(expected); + expect(await noDepsSeenBy(packageDir, "peer-deps-fixed")).toBe("2.0.0"); + expect(await noDepsSeenBy(packageDir, "one-fixed-dep")).toBe("1.0.0"); + + // Nothing is re-resolved on a warm install; the report comes from the layout, every time. + expect(peerWarnings((await install(packageDir)).err)).toEqual(expected); + expect(peerWarnings((await install(packageDir, "--frozen-lockfile")).err)).toEqual(expected); + }); + + test("no report when the copy the dependent resolves is in range", async () => { + const { packageDir, packageJson } = await registry.createTestDir({ bunfigOpts: { linker } }); + await write( + packageJson, + JSON.stringify({ name: "foo", dependencies: { "one-fixed-dep": "1.0.0", "peer-deps-fixed": "1.0.0" } }), + ); + + expect(peerWarnings((await install(packageDir)).err)).toEqual([]); + expect(await noDepsSeenBy(packageDir, "peer-deps-fixed")).toBe("1.0.0"); + }); + + test("one line per dependent, not one anonymous line per edge", async () => { + const { packageDir, packageJson } = await registry.createTestDir({ bunfigOpts: { linker } }); + await write( + packageJson, + JSON.stringify({ + name: "foo", + dependencies: { "no-deps": "2.0.0", "1-peer-dep-a": "1.0.0", "1-peer-dep-b": "1.0.0" }, + }), + ); + + expect(peerWarnings((await install(packageDir)).err)).toEqual([ + `warn: incorrect peer dependency "no-deps@2.0.0" (1-peer-dep-a@1.0.0 requires "1.0.0")`, + `warn: incorrect peer dependency "no-deps@2.0.0" (1-peer-dep-b@1.0.0 requires "1.0.0")`, + ]); + }); + + test("the range an override sets is the one enforced", async () => { + // A flat override rewrites every `no-deps` edge, the peer included, so it is satisfied... + { + const { packageDir, packageJson } = await registry.createTestDir({ bunfigOpts: { linker } }); + await write( + packageJson, + JSON.stringify({ + name: "foo", + dependencies: { "no-deps": "2.0.0", "peer-deps-fixed": "1.0.0" }, + overrides: { "no-deps": "2.0.0" }, + }), + ); + expect(peerWarnings((await install(packageDir)).err)).toEqual([]); + expect(await noDepsSeenBy(packageDir, "peer-deps-fixed")).toBe("2.0.0"); + } + // ...and a scoped one that narrows the peer is reported against the narrowed range. + { + const { packageDir, packageJson } = await registry.createTestDir({ bunfigOpts: { linker } }); + await write( + packageJson, + JSON.stringify({ + name: "foo", + dependencies: { "no-deps": "1.1.0", "peer-deps-fixed": "1.0.0" }, + overrides: { "peer-deps-fixed": { "no-deps": "1.0.0" } }, + }), + ); + expect(peerWarnings((await install(packageDir)).err)).toEqual([ + `warn: incorrect peer dependency "no-deps@1.1.0" (peer-deps-fixed@1.0.0 requires "1.0.0" by override)`, + ]); + expect(await noDepsSeenBy(packageDir, "peer-deps-fixed")).toBe("1.1.0"); + } + }); + + test("workspace and root dependents are named by what they are", async () => { + const { packageDir } = await registry.createTestDir({ + bunfigOpts: { linker }, + files: { + "package.json": JSON.stringify({ + name: "mono", + workspaces: ["packages/*"], + dependencies: { "no-deps": "2.0.0" }, + peerDependencies: { "no-deps": "^1.0.0" }, + }), + "packages/pkg1/package.json": JSON.stringify({ + name: "pkg1", + version: "1.0.0", + dependencies: { "peer-deps-fixed": "1.0.0" }, + peerDependencies: { "no-deps": "1.0.0" }, + }), + }, + }); + + expect(peerWarnings((await install(packageDir)).err)).toEqual([ + `warn: incorrect peer dependency "no-deps@2.0.0" (mono requires "^1.0.0")`, + `warn: incorrect peer dependency "no-deps@2.0.0" (peer-deps-fixed@1.0.0 requires "^1.0.0")`, + `warn: incorrect peer dependency "no-deps@2.0.0" (pkg1@workspace:packages/pkg1 requires "1.0.0")`, + ]); + }); + + test("--omit=peer leaves peer edges out of the install, so they are not checked", async () => { + const { packageDir, packageJson } = await registry.createTestDir({ bunfigOpts: { linker } }); + await write( + packageJson, + JSON.stringify({ name: "foo", dependencies: { "no-deps": "2.0.0", "peer-deps-fixed": "1.0.0" } }), + ); + expect(peerWarnings((await install(packageDir, "--omit=peer")).err)).toEqual([]); + }); + }); + describe("devDependencies", () => { test("from normal dependency", async () => { // Root package should choose no-deps@1.0.1. From c555bb018d8f8036578139767226b41420e496c8 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 8 Sep 2026 06:07:39 +0000 Subject: [PATCH 02/13] install: make peer reporting an explicit choice of the tree and store builders' callers --- src/install/isolated_install.rs | 15 ++++++++------- src/install/lockfile.rs | 14 +++++++++++++- src/install/lockfile/Tree.rs | 11 ++++++----- src/install/prune.rs | 10 +++++++++- 4 files changed, 36 insertions(+), 14 deletions(-) diff --git a/src/install/isolated_install.rs b/src/install/isolated_install.rs index 6df6e9c4c2b7..11a15d0b0409 100644 --- a/src/install/isolated_install.rs +++ b/src/install/isolated_install.rs @@ -220,6 +220,9 @@ pub(crate) fn build_store( workspace_filters: &[WorkspaceFilter], packages_to_install: Option<&[PackageID]>, timings: Timings, + // Where to report peers an entry resolves out of range; `None` for a store that is not + // about to be installed. + mut peer_warnings: Option<&mut bun_ast::Log>, ) -> Result { let mut timer = std::time::Instant::now(); let pkgs = lockfile.packages.slice(); @@ -813,7 +816,7 @@ pub(crate) fn build_store( continue; } - if packages_to_install.is_none() + if let Some(log) = peer_warnings.as_deref_mut() && !dependencies[peer_dep_id as usize] .behavior .is_optional_peer() @@ -821,12 +824,7 @@ pub(crate) fn build_store( .insert((peer_dep_id, resolved_pkg_id), ()) .is_none() { - lockfile.warn_if_peer_out_of_range( - manager.log_mut(), - entry.pkg_id, - peer_dep_id, - resolved_pkg_id, - ); + lockfile.warn_if_peer_out_of_range(log, entry.pkg_id, peer_dep_id, resolved_pkg_id); } for &visited_parent_id in &visited_parent_node_ids { @@ -1156,6 +1154,8 @@ pub(crate) fn install_isolated_packages( } else { Timings::Quiet }; + // The partial store that installs a security scanner ahead of the real install stays quiet. + let peer_warnings = packages_to_install.is_none().then(|| manager.log_mut()); let store: Store = build_store( &*manager, &*lockfile, @@ -1163,6 +1163,7 @@ pub(crate) fn install_isolated_packages( workspace_filters, packages_to_install, timings, + peer_warnings, )?; let global_store_path: Option> = if manager.options.enable.global_virtual_store() { diff --git a/src/install/lockfile.rs b/src/install/lockfile.rs index c3ab79d94253..2faaffe13454 100644 --- a/src/install/lockfile.rs +++ b/src/install/lockfile.rs @@ -1440,10 +1440,19 @@ impl<'a> Cloner<'a> { impl Lockfile { /// Re-hoists while a pass bound an optional peer late; a reload has that binding up front. pub(crate) fn resolve(&mut self, log: &mut bun_ast::Log) -> Result<(), tree::SubtreeError> { - while self.hoist::<{ tree::BuilderMethod::Resolvable }>(log, None, true, &[], None)? {} + while self.hoist::<{ tree::BuilderMethod::Resolvable }>( + log, + None, + true, + &[], + None, + false, + )? {} Ok(()) } + /// The tree an install lays out on disk. Peers it serves out of range are reported to `log`, + /// except for the partial tree that installs a security scanner ahead of the real install. pub(crate) fn filter( &mut self, log: &mut bun_ast::Log, @@ -1458,6 +1467,7 @@ impl Lockfile { install_root_dependencies, workspace_filters, packages_to_install, + packages_to_install.is_none(), )?; Ok(()) } @@ -1472,6 +1482,7 @@ impl Lockfile { install_root_dependencies: bool, workspace_filters: &[WorkspaceFilter], packages_to_install: Option<&[PackageID]>, + report_peers: bool, ) -> Result { let slice = self.packages.slice(); @@ -1503,6 +1514,7 @@ impl Lockfile { packages_to_install, pending_optional_peers: Default::default(), late_bound_optional_peer: false, + report_peers, reported_peers: Default::default(), list: Default::default(), sort_buf: Default::default(), diff --git a/src/install/lockfile/Tree.rs b/src/install/lockfile/Tree.rs index d2a32ec48980..569d722b1370 100644 --- a/src/install/lockfile/Tree.rs +++ b/src/install/lockfile/Tree.rs @@ -437,6 +437,9 @@ pub struct Builder<'a, const METHOD: BuilderMethod> { ArrayHashMap>, /// An optional peer got bound after its dependent was placed; see `Lockfile::resolve`. pub(crate) late_bound_optional_peer: bool, + /// Check the range of every peer this tree serves (`report_peer`). Only the tree an install + /// lays out on disk does; the saved (`Resolvable`) tree is also built on every load. + pub(crate) report_peers: bool, /// `(peer edge, package it is served by)` pairs already checked by `report_peer`, so a /// dependent placed at several paths is reported once per distinct outcome. pub(crate) reported_peers: HashMap<(DependencyID, PackageID), ()>, @@ -487,12 +490,10 @@ impl<'a, const METHOD: BuilderMethod> Builder<'a, METHOD> { let _ = self.log.add_error_fmt(None, bun_ast::Loc::EMPTY, args); } - /// The tree being installed decided which package `dependent` resolves for its peer edge - /// `dep_id`; warn if that package is outside the peer's range. The saved (`Resolvable`) tree - /// is built on every load and is not what ends up on disk, so it stays quiet, as does the - /// partial tree built to install a security scanner ahead of the real install. + /// This tree decided which package `dependent` resolves for its peer edge `dep_id`; warn if + /// that package is outside the peer's range. fn report_peer(&mut self, dependent: PackageID, dep_id: DependencyID, served: PackageID) { - if METHOD != BuilderMethod::Filter || self.packages_to_install.is_some() { + if !self.report_peers { return; } if self.reported_peers.insert((dep_id, served), ()).is_some() { diff --git a/src/install/prune.rs b/src/install/prune.rs index 668cd540e4a8..c6a6af1b0a26 100644 --- a/src/install/prune.rs +++ b/src/install/prune.rs @@ -780,7 +780,14 @@ fn hoist_install_tree( unsafe { let lf: *mut Lockfile = &raw mut *(*pm).lockfile; let log: *mut bun_ast::Log = (*pm).log; - (*lf).hoist::<{ tree::BuilderMethod::Filter }>(&mut *log, Some(&*pm), true, &[], None) + (*lf).hoist::<{ tree::BuilderMethod::Filter }>( + &mut *log, + Some(&*pm), + true, + &[], + None, + false, + ) } }); match result { @@ -1714,6 +1721,7 @@ fn build_store_with(manager: &mut PackageManager, features: InstallFeatures) -> &[], None, Timings::Quiet, + None, )) }) } From d5a5e292826d5003d7098eccecd7d8acd50e660f Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Tue, 8 Sep 2026 06:27:32 +0000 Subject: [PATCH 03/13] [autofix.ci] apply automated fixes --- test/cli/install/bun-install-registry.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/cli/install/bun-install-registry.test.ts b/test/cli/install/bun-install-registry.test.ts index ebcd482c2899..00162f71702d 100644 --- a/test/cli/install/bun-install-registry.test.ts +++ b/test/cli/install/bun-install-registry.test.ts @@ -3,7 +3,6 @@ import { install_test_helpers, npm_manifest_test_helpers } from "bun:internal-fo import { afterAll, beforeAll, beforeEach, describe, expect, setDefaultTimeout, test } from "bun:test"; import { copyFileSync, mkdirSync, realpathSync } from "fs"; import { cp, exists, lstat, mkdir, readlink, rename, rm, writeFile } from "fs/promises"; -import { createRequire } from "module"; import { assertManifestsPopulated, bunExe, @@ -26,6 +25,7 @@ import { VerdaccioRegistry, writeShebangScript, } from "harness"; +import { createRequire } from "module"; import { join, resolve } from "path"; const { parseLockfile } = install_test_helpers; From 0dc72af3598ee663419084eb0bc06554eb829cc7 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 8 Sep 2026 06:42:16 +0000 Subject: [PATCH 04/13] install: shorten the new comments --- .../PackageManager/PackageManagerEnqueue.rs | 7 ++----- src/install/isolated_install.rs | 9 +++------ src/install/lockfile.rs | 14 +++++--------- src/install/lockfile/Tree.rs | 18 ++++++------------ 4 files changed, 16 insertions(+), 32 deletions(-) diff --git a/src/install/PackageManager/PackageManagerEnqueue.rs b/src/install/PackageManager/PackageManagerEnqueue.rs index dacd973ffe4b..858f1d5a6821 100644 --- a/src/install/PackageManager/PackageManagerEnqueue.rs +++ b/src/install/PackageManager/PackageManagerEnqueue.rs @@ -2538,9 +2538,7 @@ fn get_or_put_resolved_package( })); } - // Nothing satisfies the range: bind the copy that exists anyway. The - // linker reports the mismatch against the copy it actually serves - // (`Lockfile::warn_if_peer_out_of_range`), which may be a different one. + // The linker warns, against the copy it serves (`warn_if_peer_out_of_range`). if peer_binds_out_of_range( resolutions[existing_id as usize].tag, version.tag, @@ -3106,8 +3104,7 @@ fn resolution_satisfies_dependency( resolution.satisfies_dependency_version(dependency, buf, buf) } -/// A peer nothing in the lockfile satisfies still binds to an existing copy of the same kind -/// instead of pulling in its own version. +/// A peer no lockfile package satisfies binds an existing copy of its kind rather than a new one. fn peer_binds_out_of_range(existing: ResolutionTag, range: dependency::version::Tag) -> bool { matches!( (existing, range), diff --git a/src/install/isolated_install.rs b/src/install/isolated_install.rs index 11a15d0b0409..1fc17b02f5c9 100644 --- a/src/install/isolated_install.rs +++ b/src/install/isolated_install.rs @@ -220,8 +220,7 @@ pub(crate) fn build_store( workspace_filters: &[WorkspaceFilter], packages_to_install: Option<&[PackageID]>, timings: Timings, - // Where to report peers an entry resolves out of range; `None` for a store that is not - // about to be installed. + // `Some` only for a store about to be installed: where its out-of-range peers are reported. mut peer_warnings: Option<&mut bun_ast::Log>, ) -> Result { let mut timer = std::time::Instant::now(); @@ -401,8 +400,7 @@ pub(crate) fn build_store( let mut visited_parent_node_ids: Vec = Vec::new(); - // A package is visited once per peer context, so the same edge can resolve the same way many - // times; each distinct `(peer edge, resolved package)` is range-checked once. + // A package is visited once per peer context; each `(peer edge, resolution)` is checked once. let mut reported_peers: HashMap<(DependencyID, PackageID), ()> = HashMap::default(); // First pass: create full dependency tree with resolved peers @@ -752,8 +750,7 @@ pub(crate) fn build_store( continue; } - // The nearest ancestor that provides the name wins whether or not its - // version is in range; the range is checked once the peer is resolved. + // The nearest provider wins even out of range; the range is checked below. break 'resolved_pkg_id (ids.pkg_id, false); } diff --git a/src/install/lockfile.rs b/src/install/lockfile.rs index 2faaffe13454..c2fc9116552b 100644 --- a/src/install/lockfile.rs +++ b/src/install/lockfile.rs @@ -756,9 +756,8 @@ impl Lockfile { Some(catalog_dep.version) } - /// The range the resolver resolves an edge against: an `overrides` rule replaces the declared - /// range, then a `catalog:` reference is looked up. Mirrors - /// `enqueue_dependency_with_main_and_success_fn`, minus its per-session npm alias redirects. + /// The range the resolver resolves an edge against: its `overrides` rule if any, else the + /// declared range, with `catalog:` references looked up either way. pub(crate) fn enforced_range(&self, dep_id: DependencyID) -> EnforcedRange<'_> { use dependency::DependencyExt as _; @@ -800,10 +799,7 @@ impl Lockfile { } } - /// A linker calls this with the package it wires a peer edge of `dependent` to. Warns when - /// that package is outside the range the edge enforces. Only like kinds are compared (an npm - /// range against an npm version, a git range against a git resolution): a peer served by a - /// workspace, folder or tarball package has nothing to reject. + /// Called by a linker with the package it wires a required peer edge of `dependent` to. pub(crate) fn warn_if_peer_out_of_range( &self, log: &mut bun_ast::Log, @@ -819,6 +815,7 @@ impl Lockfile { let pkg_resolutions = self.packages.items_resolution(); let served_res = &pkg_resolutions[served as usize]; let range = self.enforced_range(peer_dep_id); + // A workspace, folder or tarball copy has no version to reject. let comparable = matches!( (served_res.tag, range.version.tag), (ResolutionTag::Npm, dependency::Tag::Npm) @@ -1451,8 +1448,7 @@ impl Lockfile { Ok(()) } - /// The tree an install lays out on disk. Peers it serves out of range are reported to `log`, - /// except for the partial tree that installs a security scanner ahead of the real install. + /// The tree an install writes to disk. Reports the out-of-range peers of a full install. pub(crate) fn filter( &mut self, log: &mut bun_ast::Log, diff --git a/src/install/lockfile/Tree.rs b/src/install/lockfile/Tree.rs index 569d722b1370..0b992618866e 100644 --- a/src/install/lockfile/Tree.rs +++ b/src/install/lockfile/Tree.rs @@ -127,8 +127,7 @@ enum HoistDependencyResult { Resolve(PackageID), ResolveReplace(ResolveReplace), ResolveLater, - /// `Hoisted`, for a peer: nothing is placed and the dependent resolves this other package, - /// already on its path, instead of the one the edge is bound to. + /// `Hoisted`, for a peer served by this different package already on its path. Dedupe(PackageID), Placement(Placement), } @@ -437,11 +436,9 @@ pub struct Builder<'a, const METHOD: BuilderMethod> { ArrayHashMap>, /// An optional peer got bound after its dependent was placed; see `Lockfile::resolve`. pub(crate) late_bound_optional_peer: bool, - /// Check the range of every peer this tree serves (`report_peer`). Only the tree an install - /// lays out on disk does; the saved (`Resolvable`) tree is also built on every load. + /// Range-check the peers this tree serves (`report_peer`); only the tree an install writes does. pub(crate) report_peers: bool, - /// `(peer edge, package it is served by)` pairs already checked by `report_peer`, so a - /// dependent placed at several paths is reported once per distinct outcome. + /// `(peer edge, package serving it)` pairs already checked, one per distinct outcome. pub(crate) reported_peers: HashMap<(DependencyID, PackageID), ()>, pub(crate) manager: Option<&'a PackageManager>, pub(crate) sort_buf: Vec, @@ -490,8 +487,7 @@ impl<'a, const METHOD: BuilderMethod> Builder<'a, METHOD> { let _ = self.log.add_error_fmt(None, bun_ast::Loc::EMPTY, args); } - /// This tree decided which package `dependent` resolves for its peer edge `dep_id`; warn if - /// that package is outside the peer's range. + /// This tree serves `dependent`'s peer edge `dep_id` with `served`; warn if it is out of range. fn report_peer(&mut self, dependent: PackageID, dep_id: DependencyID, served: PackageID) { if !self.report_peers { return; @@ -937,8 +933,7 @@ impl Tree { HoistDependencyResult::Dedupe(res_id) => { debug_assert!(dependency.behavior.is_peer()); if dependency.behavior.is_optional_peer() { - // An optional peer's binding follows the dedupe, but only in the tree - // being saved. + // An optional peer's binding follows the dedupe, in the saved tree only. if METHOD == BuilderMethod::Resolvable { builder.resolutions[dep_id as usize] = res_id; } @@ -1092,8 +1087,7 @@ impl Tree { } // Root dependencies are manually chosen by the user. Allow them - // to hoist other peers even if they don't satisfy the version; - // the tree being installed reports the mismatch (`Builder::report_peer`). + // to hoist other peers even if they don't satisfy the version if builder.lockfile().is_workspace_root_dependency(dep_id) { return HoistDependencyResult::Dedupe(res_id); // 1 } From 88e7835338988d5c8e1a71ace17136378b147c1b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 8 Sep 2026 06:45:00 +0000 Subject: [PATCH 05/13] install: one-line doc for enforced_range --- src/install/lockfile.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/install/lockfile.rs b/src/install/lockfile.rs index c2fc9116552b..d8f794142ac5 100644 --- a/src/install/lockfile.rs +++ b/src/install/lockfile.rs @@ -756,8 +756,7 @@ impl Lockfile { Some(catalog_dep.version) } - /// The range the resolver resolves an edge against: its `overrides` rule if any, else the - /// declared range, with `catalog:` references looked up either way. + /// The range the resolver holds an edge to: its `overrides` rule, else the declared range. pub(crate) fn enforced_range(&self, dep_id: DependencyID) -> EnforcedRange<'_> { use dependency::DependencyExt as _; From f1fe4378135d2e8b42079931ad86074d96513b4e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 8 Sep 2026 09:53:21 +0000 Subject: [PATCH 06/13] install: name the peer-range reporting choice with an enum instead of a bare bool --- src/install/lockfile.rs | 12 ++++++++---- src/install/lockfile/Tree.rs | 12 +++++++++--- src/install/prune.rs | 2 +- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/src/install/lockfile.rs b/src/install/lockfile.rs index d8f794142ac5..04ade38ac661 100644 --- a/src/install/lockfile.rs +++ b/src/install/lockfile.rs @@ -1442,7 +1442,7 @@ impl Lockfile { true, &[], None, - false, + tree::PeerRanges::Ignore, )? {} Ok(()) } @@ -1462,7 +1462,11 @@ impl Lockfile { install_root_dependencies, workspace_filters, packages_to_install, - packages_to_install.is_none(), + if packages_to_install.is_none() { + tree::PeerRanges::Report + } else { + tree::PeerRanges::Ignore + }, )?; Ok(()) } @@ -1477,7 +1481,7 @@ impl Lockfile { install_root_dependencies: bool, workspace_filters: &[WorkspaceFilter], packages_to_install: Option<&[PackageID]>, - report_peers: bool, + peer_ranges: tree::PeerRanges, ) -> Result { let slice = self.packages.slice(); @@ -1509,7 +1513,7 @@ impl Lockfile { packages_to_install, pending_optional_peers: Default::default(), late_bound_optional_peer: false, - report_peers, + peer_ranges, reported_peers: Default::default(), list: Default::default(), sort_buf: Default::default(), diff --git a/src/install/lockfile/Tree.rs b/src/install/lockfile/Tree.rs index 0b992618866e..9e00a25a313b 100644 --- a/src/install/lockfile/Tree.rs +++ b/src/install/lockfile/Tree.rs @@ -143,6 +143,13 @@ pub(crate) struct Placement { pub bundled: bool, } +/// Whether a tree reports the peers it serves out of range; only the tree an install writes does. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum PeerRanges { + Report, + Ignore, +} + #[derive(thiserror::Error, Debug, strum::IntoStaticStr)] pub enum SubtreeError { #[error("OutOfMemory")] @@ -436,8 +443,7 @@ pub struct Builder<'a, const METHOD: BuilderMethod> { ArrayHashMap>, /// An optional peer got bound after its dependent was placed; see `Lockfile::resolve`. pub(crate) late_bound_optional_peer: bool, - /// Range-check the peers this tree serves (`report_peer`); only the tree an install writes does. - pub(crate) report_peers: bool, + pub(crate) peer_ranges: PeerRanges, /// `(peer edge, package serving it)` pairs already checked, one per distinct outcome. pub(crate) reported_peers: HashMap<(DependencyID, PackageID), ()>, pub(crate) manager: Option<&'a PackageManager>, @@ -489,7 +495,7 @@ impl<'a, const METHOD: BuilderMethod> Builder<'a, METHOD> { /// This tree serves `dependent`'s peer edge `dep_id` with `served`; warn if it is out of range. fn report_peer(&mut self, dependent: PackageID, dep_id: DependencyID, served: PackageID) { - if !self.report_peers { + if self.peer_ranges == PeerRanges::Ignore { return; } if self.reported_peers.insert((dep_id, served), ()).is_some() { diff --git a/src/install/prune.rs b/src/install/prune.rs index c6a6af1b0a26..6908ed2fe25a 100644 --- a/src/install/prune.rs +++ b/src/install/prune.rs @@ -786,7 +786,7 @@ fn hoist_install_tree( true, &[], None, - false, + tree::PeerRanges::Ignore, ) } }); From 52e5226023680fa026aa68d551fed8c9cfbd1718 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 8 Sep 2026 18:12:51 +0000 Subject: [PATCH 07/13] test: --lockfile-only reports no peers, the next install does --- test/cli/install/bun-install-registry.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/test/cli/install/bun-install-registry.test.ts b/test/cli/install/bun-install-registry.test.ts index 00162f71702d..df118c297bb0 100644 --- a/test/cli/install/bun-install-registry.test.ts +++ b/test/cli/install/bun-install-registry.test.ts @@ -4619,6 +4619,20 @@ describe("hoisting", async () => { ); expect(peerWarnings((await install(packageDir, "--omit=peer")).err)).toEqual([]); }); + + test("--lockfile-only lays nothing out, so no peer is served and none is reported", async () => { + const { packageDir, packageJson } = await registry.createTestDir({ bunfigOpts: { linker } }); + await write( + packageJson, + JSON.stringify({ name: "foo", dependencies: { "no-deps": "2.0.0", "peer-deps-fixed": "1.0.0" } }), + ); + expect(peerWarnings((await install(packageDir, "--lockfile-only")).err)).toEqual([]); + expect(await exists(join(packageDir, "node_modules"))).toBeFalse(); + // The install that follows does lay it out, and reports it. + expect(peerWarnings((await install(packageDir)).err)).toEqual([ + `warn: incorrect peer dependency "no-deps@2.0.0" (peer-deps-fixed@1.0.0 requires "^1.0.0")`, + ]); + }); }); describe("devDependencies", () => { From 7a9a836e25023bd12961c5185726a86529a9f77e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 1 Oct 2026 01:59:56 +0000 Subject: [PATCH 08/13] docs: say when a required peer reuses an existing package, and show the warning --- docs/pm/cli/install.mdx | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/pm/cli/install.mdx b/docs/pm/cli/install.mdx index 8a6f330d0fe1..20d27c01e537 100644 --- a/docs/pm/cli/install.mdx +++ b/docs/pm/cli/install.mdx @@ -454,7 +454,17 @@ These flags install packages for the specified platform instead of the current s ## Peer dependencies? -Bun handles peer dependencies like Yarn: `bun install` installs them automatically. If the dependency is marked optional in `peerDependenciesMeta`, Bun uses an existing dependency if possible. +`bun install` installs required peer dependencies. If nothing in the install depends on the peer's package, Bun installs the newest version in the peer's range. + +If your project or another dependency already depends on a version of the peer's package from the registry, Bun reuses that copy for the peer and installs no second copy. The reused copy can be outside the peer's range. In that case, Bun prints a warning that names the package and the range it requires: + +```txt +warn: incorrect peer dependency "react@17.0.2" (react-dom@18.3.1 requires "^18.3.1") +``` + +To choose the version, add the peer's package to the `dependencies` in your `package.json`. + +If `peerDependenciesMeta` marks the peer as optional, Bun does not install it. Bun uses an existing dependency if possible. ## Lockfile From d3a01becef853aaa48a76dd78426d378b4a5cb15 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 1 Oct 2026 02:19:41 +0000 Subject: [PATCH 09/13] docs: the peer warning prints on installs that write node_modules --- docs/pm/cli/install.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/pm/cli/install.mdx b/docs/pm/cli/install.mdx index 20d27c01e537..a2fe3c715746 100644 --- a/docs/pm/cli/install.mdx +++ b/docs/pm/cli/install.mdx @@ -456,7 +456,7 @@ These flags install packages for the specified platform instead of the current s `bun install` installs required peer dependencies. If nothing in the install depends on the peer's package, Bun installs the newest version in the peer's range. -If your project or another dependency already depends on a version of the peer's package from the registry, Bun reuses that copy for the peer and installs no second copy. The reused copy can be outside the peer's range. In that case, Bun prints a warning that names the package and the range it requires: +If your project or another dependency already depends on a version of the peer's package from the registry, Bun reuses that copy for the peer and installs no second copy. The reused copy can be outside the peer's range. Each install that writes `node_modules` then prints a warning that names the package and the range it requires: ```txt warn: incorrect peer dependency "react@17.0.2" (react-dom@18.3.1 requires "^18.3.1") From 57ceb74ad5a80565282ec7f49e45d5e26512e5dd Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 1 Oct 2026 03:45:51 +0000 Subject: [PATCH 10/13] install: --dry-run reports the peers the install would serve out of range A dry run skips both linkers, so it printed none of the peer warnings the real install prints. It now builds the layout the install would write (the filtered hoisted tree, or the isolated store) for the warnings only, and puts the saved tree back. --- .../PackageManager/install_with_manager.rs | 84 +++++++++++++++---- src/install/lockfile.rs | 22 +++++ test/cli/install/bun-install-registry.test.ts | 17 ++++ 3 files changed, 107 insertions(+), 16 deletions(-) diff --git a/src/install/PackageManager/install_with_manager.rs b/src/install/PackageManager/install_with_manager.rs index 89da786c5647..d4fd7da3b3d3 100644 --- a/src/install/PackageManager/install_with_manager.rs +++ b/src/install/PackageManager/install_with_manager.rs @@ -858,28 +858,28 @@ pub fn install_with_manager( let install_summary: PackageInstallSummary = 'install_summary: { if !manager.options.do_.install_packages() { + if manager.options.dry_run { + let linker = match manager.options.node_linker { + NodeLinker::Auto => auto_node_linker(manager, config_version, &load_result), + linker => linker, + }; + report_dry_run_peers( + manager, + linker, + install_root_dependencies, + &workspace_filters, + )?; + } break 'install_summary PackageInstallSummary::default(); } let mut linker = manager.options.node_linker; loop { match linker { - NodeLinker::Auto => match config_version { - ConfigVersion::V0 => { - linker = NodeLinker::Hoisted; - continue; - } - ConfigVersion::V1 => { - if !load_result.migrated_from_npm() - && manager.lockfile.workspace_paths.len() > 0 - { - linker = NodeLinker::Isolated; - continue; - } - linker = NodeLinker::Hoisted; - continue; - } - }, + NodeLinker::Auto => { + linker = auto_node_linker(manager, config_version, &load_result); + continue; + } NodeLinker::Hoisted => { let summary = install_hoisted_packages( @@ -1416,6 +1416,58 @@ pub(crate) fn get_workspace_filters( Ok((filters, install_root_dependencies)) } +/// The linker that `NodeLinker::Auto` stands for in this install. +fn auto_node_linker( + manager: &PackageManager, + config_version: ConfigVersion, + load_result: &lockfile::LoadResult, +) -> NodeLinker { + match config_version { + ConfigVersion::V0 => NodeLinker::Hoisted, + ConfigVersion::V1 => { + if !load_result.migrated_from_npm() && manager.lockfile.workspace_paths.len() > 0 { + NodeLinker::Isolated + } else { + NodeLinker::Hoisted + } + } + } +} + +/// `--dry-run` installs nothing. This builds the layout the install would write, for the peer warnings only. +fn report_dry_run_peers( + manager: &mut PackageManager, + linker: NodeLinker, + install_root_dependencies: bool, + workspace_filters: &[WorkspaceFilter], +) -> crate::Result<()> { + if linker == NodeLinker::Isolated { + crate::isolated_install::build_store( + &*manager, + &manager.lockfile, + install_root_dependencies, + workspace_filters, + None, + crate::isolated_install::Timings::Quiet, + Some(manager.log_mut()), + )?; + return Ok(()); + } + let pm: *mut PackageManager = manager; + // SAFETY: same split as `install_hoisted_packages`: `lockfile` is its own `Box` allocation and `*log` is outside `*pm`, so the three borrows are disjoint. + unsafe { + let lockfile: *mut Lockfile = &raw mut *(*pm).lockfile; + let log: *mut bun_ast::Log = (*pm).log; + (*lockfile).filter_dry_run( + &mut *log, + &mut *pm, + install_root_dependencies, + workspace_filters, + )?; + } + Ok(()) +} + fn frozen_changed_section( manager: &mut PackageManager, root_package_json_path: &ZStr, diff --git a/src/install/lockfile.rs b/src/install/lockfile.rs index 85ba1dca214f..6d46a84002be 100644 --- a/src/install/lockfile.rs +++ b/src/install/lockfile.rs @@ -1521,6 +1521,28 @@ impl Lockfile { Ok(()) } + /// `filter` for a dry run: reports the same peers, then puts the saved tree back. + pub(crate) fn filter_dry_run( + &mut self, + log: &mut bun_ast::Log, + manager: &mut PackageManager, + install_root_dependencies: bool, + workspace_filters: &[WorkspaceFilter], + ) -> Result<(), tree::SubtreeError> { + let trees = core::mem::take(&mut self.buffers.trees); + let hoisted_dependencies = core::mem::take(&mut self.buffers.hoisted_dependencies); + let result = self.filter( + log, + manager, + install_root_dependencies, + workspace_filters, + None, + ); + self.buffers.trees = trees; + self.buffers.hoisted_dependencies = hoisted_dependencies; + result + } + /// Sets `buffers.trees`/`hoisted_dependencies`; returns `Builder::late_bound_optional_peer`. pub(crate) fn hoist( &mut self, diff --git a/test/cli/install/bun-install-registry.test.ts b/test/cli/install/bun-install-registry.test.ts index 037537d11972..ba5c595f7d86 100644 --- a/test/cli/install/bun-install-registry.test.ts +++ b/test/cli/install/bun-install-registry.test.ts @@ -5238,6 +5238,23 @@ describe("hoisting", async () => { `warn: incorrect peer dependency "no-deps@2.0.0" (peer-deps-fixed@1.0.0 requires "^1.0.0")`, ]); }); + + test("--dry-run writes nothing and reports what the install will report", async () => { + const { packageDir, packageJson } = await registry.createTestDir({ bunfigOpts: { linker } }); + await write( + packageJson, + JSON.stringify({ name: "foo", dependencies: { "no-deps": "2.0.0", "peer-deps-fixed": "1.0.0" } }), + ); + const expected = [`warn: incorrect peer dependency "no-deps@2.0.0" (peer-deps-fixed@1.0.0 requires "^1.0.0")`]; + + expect(peerWarnings((await install(packageDir, "--dry-run")).err)).toEqual(expected); + expect(await exists(join(packageDir, "node_modules"))).toBeFalse(); + expect(await exists(join(packageDir, "bun.lock"))).toBeFalse(); + + expect(peerWarnings((await install(packageDir)).err)).toEqual(expected); + // Nothing is resolved this time; the preview still reports it. + expect(peerWarnings((await install(packageDir, "--dry-run")).err)).toEqual(expected); + }); }); describe("devDependencies", () => { From 1d59cf2144454f08b6637ee83bfcc6490448ba73 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 1 Oct 2026 04:12:25 +0000 Subject: [PATCH 11/13] docs: --dry-run prints the peer warning too --- docs/pm/cli/install.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/pm/cli/install.mdx b/docs/pm/cli/install.mdx index a2fe3c715746..339f7035d6e9 100644 --- a/docs/pm/cli/install.mdx +++ b/docs/pm/cli/install.mdx @@ -456,7 +456,7 @@ These flags install packages for the specified platform instead of the current s `bun install` installs required peer dependencies. If nothing in the install depends on the peer's package, Bun installs the newest version in the peer's range. -If your project or another dependency already depends on a version of the peer's package from the registry, Bun reuses that copy for the peer and installs no second copy. The reused copy can be outside the peer's range. Each install that writes `node_modules` then prints a warning that names the package and the range it requires: +If your project or another dependency already depends on a version of the peer's package from the registry, Bun reuses that copy for the peer and installs no second copy. The reused copy can be outside the peer's range. Each install that writes `node_modules`, and each `--dry-run`, then prints a warning that names the package and the range it requires: ```txt warn: incorrect peer dependency "react@17.0.2" (react-dom@18.3.1 requires "^18.3.1") From 44947a56bd5a8572a9d88d319d2b0209cbc852a6 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 2 Oct 2026 07:54:01 +0000 Subject: [PATCH 12/13] install: report an unmet peer only when an installed entry resolved it The isolated store builder checked a peer's range while it walked the dependency tree. Not every walked node reaches the disk: - The second pass folds a node into the entry of another node with the same package and an equal peer set. The folded subtree is dropped. - A workspace has one node_modules. The installer links only the first store entry of a workspace, so a second entry and the entries that only it depends on are never linked. The warning could therefore name a copy that no package loads. The first pass now records each node that resolved a required peer to a copy outside its range. After the second pass, a record is reported only if its node became an entry that the installer links: the root entry, the first entry of each workspace, and what those depend on. --- src/install/isolated_install.rs | 91 ++++++++++++++-- src/install/lockfile.rs | 32 ++++-- test/cli/install/bun-install-registry.test.ts | 103 ++++++++++++++++++ 3 files changed, 210 insertions(+), 16 deletions(-) diff --git a/src/install/isolated_install.rs b/src/install/isolated_install.rs index 8c1230b1a922..d9ca7c5bbc4a 100644 --- a/src/install/isolated_install.rs +++ b/src/install/isolated_install.rs @@ -68,6 +68,14 @@ struct QueuedNode { pkg_id: PackageID, } +/// A required peer edge of a node, and the package outside its range that the node resolved it to. +#[derive(Clone, Copy)] +struct UnmetPeer { + node_id: store::node::Id, + dep_id: DependencyID, + pkg_id: PackageID, +} + #[derive(Clone, Copy, PartialEq, Eq, Hash)] struct EarlyDedupeKey { pkg_id: PackageID, @@ -222,7 +230,7 @@ pub(crate) fn build_store( packages_to_install: Option<&[PackageID]>, timings: Timings, // `Some` only for a store about to be installed: where its out-of-range peers are reported. - mut peer_warnings: Option<&mut bun_ast::Log>, + peer_warnings: Option<&mut bun_ast::Log>, ) -> Result { let mut timer = std::time::Instant::now(); let pkgs = lockfile.packages.slice(); @@ -402,7 +410,8 @@ pub(crate) fn build_store( let mut visited_parent_node_ids: Vec = Vec::new(); // A package is visited once per peer context; each `(peer edge, resolution)` is checked once. - let mut reported_peers: HashMap<(DependencyID, PackageID), ()> = HashMap::default(); + let mut peer_is_unmet: HashMap<(DependencyID, PackageID), bool> = HashMap::default(); + let mut unmet_peers: Vec = Vec::new(); // First pass: create full dependency tree with resolved peers 'next_node: while let Some(entry) = node_queue.pop() { @@ -814,15 +823,24 @@ pub(crate) fn build_store( continue; } - if let Some(log) = peer_warnings.as_deref_mut() + if peer_warnings.is_some() && !dependencies[peer_dep_id as usize] .behavior .is_optional_peer() - && reported_peers - .insert((peer_dep_id, resolved_pkg_id), ()) - .is_none() { - lockfile.warn_if_peer_out_of_range(log, entry.pkg_id, peer_dep_id, resolved_pkg_id); + let check = peer_is_unmet.get_or_put((peer_dep_id, resolved_pkg_id))?; + if !check.found_existing { + *check.value_ptr = lockfile + .unmet_peer_range(peer_dep_id, resolved_pkg_id) + .is_some(); + } + if *check.value_ptr { + unmet_peers.push(UnmetPeer { + node_id, + dep_id: peer_dep_id, + pkg_id: resolved_pkg_id, + }); + } } for &visited_parent_id in &visited_parent_node_ids { @@ -1115,6 +1133,12 @@ pub(crate) fn build_store( } } + if let Some(log) = peer_warnings + && !unmet_peers.is_empty() + { + report_unmet_peers(log, lockfile, node_pkg_ids, &store_entries, &unmet_peers)?; + } + if matches!(timings, Timings::Print) { let dedupe_end = timer.elapsed(); bun_core::pretty_errorln!( @@ -1129,6 +1153,59 @@ pub(crate) fn build_store( }) } +/// Reports the unmet peers of the nodes whose resolutions reach the disk, once per `(peer edge, package)`. +fn report_unmet_peers( + log: &mut bun_ast::Log, + lockfile: &Lockfile, + node_pkg_ids: &[PackageID], + entries: &store::entry::List, + unmet_peers: &[UnmetPeer], +) -> Result<(), AllocError> { + let pkg_resolutions = lockfile.packages.items_resolution(); + let entry_node_ids = entries.items_node_id(); + let entry_dependencies = entries.items_dependencies(); + let pkg_of = |entry_id: store::entry::Id| { + node_pkg_ids[entry_node_ids[entry_id.get() as usize].get() as usize] + }; + let is_workspace = |entry_id: store::entry::Id| { + pkg_resolutions[pkg_of(entry_id) as usize].tag == ResolutionTag::Workspace + }; + + // The installer links the root entry and the first entry of each workspace, then what they depend on. + let mut queue: Vec = vec![store::entry::Id::ROOT]; + let mut workspaces: HashMap = HashMap::default(); + for index in 1..entry_node_ids.len() { + let entry_id = store::entry::Id::from(u32::try_from(index).expect("int cast")); + if is_workspace(entry_id) && workspaces.insert(pkg_of(entry_id), ()).is_none() { + queue.push(entry_id); + } + } + + // A node that the second pass folded into the entry of another node is not on disk. + let mut linked = DynamicBitSet::init_empty(node_pkg_ids.len())?; + while let Some(entry_id) = queue.pop() { + let node = entry_node_ids[entry_id.get() as usize].get() as usize; + if linked.is_set(node) { + continue; + } + linked.set(node); + for dependency in entry_dependencies[entry_id.get() as usize].slice() { + if !is_workspace(dependency.entry_id) { + queue.push(dependency.entry_id); + } + } + } + + let mut reported: HashMap<(DependencyID, PackageID), ()> = HashMap::default(); + for unmet in unmet_peers { + let node = unmet.node_id.get() as usize; + if linked.is_set(node) && reported.insert((unmet.dep_id, unmet.pkg_id), ()).is_none() { + lockfile.warn_if_peer_out_of_range(log, node_pkg_ids[node], unmet.dep_id, unmet.pkg_id); + } + } + Ok(()) +} + /// Runs on main thread pub(crate) fn install_isolated_packages( manager: &mut PackageManager, diff --git a/src/install/lockfile.rs b/src/install/lockfile.rs index 6d46a84002be..94c7aa4ecfa4 100644 --- a/src/install/lockfile.rs +++ b/src/install/lockfile.rs @@ -798,21 +798,18 @@ impl Lockfile { } } - /// Called by a linker with the package it wires a required peer edge of `dependent` to. - pub(crate) fn warn_if_peer_out_of_range( + /// The range a required peer edge is held to, when `served` is outside it. + pub(crate) fn unmet_peer_range( &self, - log: &mut bun_ast::Log, - dependent: PackageID, peer_dep_id: DependencyID, served: PackageID, - ) { + ) -> Option> { let dep = &self.buffers.dependencies[peer_dep_id as usize]; debug_assert!(dep.behavior.is_peer()); if dep.behavior.is_optional_peer() { - return; + return None; } - let pkg_resolutions = self.packages.items_resolution(); - let served_res = &pkg_resolutions[served as usize]; + let served_res = &self.packages.items_resolution()[served as usize]; let range = self.enforced_range(peer_dep_id); // A workspace, folder or tarball copy has no version to reject. let comparable = matches!( @@ -823,9 +820,26 @@ impl Lockfile { ); let buf = self.buffers.string_bytes.as_slice(); if !comparable || served_res.satisfies_dependency_version(&range.version, buf, buf) { - return; + return None; } + Some(range) + } + + /// Called by a linker with the package it wires a required peer edge of `dependent` to. + pub(crate) fn warn_if_peer_out_of_range( + &self, + log: &mut bun_ast::Log, + dependent: PackageID, + peer_dep_id: DependencyID, + served: PackageID, + ) { + let Some(range) = self.unmet_peer_range(peer_dep_id, served) else { + return; + }; + let buf = self.buffers.string_bytes.as_slice(); + let pkg_resolutions = self.packages.items_resolution(); + let served_res = &pkg_resolutions[served as usize]; let pkg_names = self.packages.items_name(); let dependent_res = &pkg_resolutions[dependent as usize]; let dependent_name = pkg_names[dependent as usize].slice(buf); diff --git a/test/cli/install/bun-install-registry.test.ts b/test/cli/install/bun-install-registry.test.ts index ba5c595f7d86..60f0dc7f642f 100644 --- a/test/cli/install/bun-install-registry.test.ts +++ b/test/cli/install/bun-install-registry.test.ts @@ -5255,6 +5255,109 @@ describe("hoisting", async () => { // Nothing is resolved this time; the preview still reports it. expect(peerWarnings((await install(packageDir, "--dry-run")).err)).toEqual(expected); }); + + test("a copy is reported only when a dependent loads it from disk", async () => { + // Both workspaces depend on dedupe-divergent-peers, whose dedupe-divergent-strict wants + // no-deps@^2.0.0. Only `provider` has a no-deps of its own, and it is 1.0.0. The isolated + // linker resolves the peer once per workspace and then keeps one store entry for both, so + // one of the two resolutions is never installed. + for (const [bare, provider] of [ + ["ws-a", "ws-b"], + ["ws-b", "ws-a"], + ]) { + const { packageDir } = await registry.createTestDir({ + bunfigOpts: { linker }, + files: { + "package.json": JSON.stringify({ name: "mono", workspaces: ["ws-a", "ws-b", "ws-seed"] }), + [`${bare}/package.json`]: JSON.stringify({ + name: bare, + version: "1.0.0", + dependencies: { "dedupe-divergent-peers": "1.0.0" }, + }), + [`${provider}/package.json`]: JSON.stringify({ + name: provider, + version: "1.0.0", + dependencies: { "dedupe-divergent-peers": "1.0.0", "no-deps": "1.0.0" }, + }), + // An alias puts no-deps@2.0.0 in the lockfile without providing the name `no-deps`. + "ws-seed/package.json": JSON.stringify({ + name: "ws-seed", + version: "1.0.0", + dependencies: { "aliased-no-deps": "npm:no-deps@2.0.0" }, + }), + }, + }); + + const { err } = await install(packageDir); + + // The no-deps that dedupe-divergent-strict loads, as node resolves it from each workspace. + const loaded = new Set(); + for (const workspace of [bare, provider]) { + let at = join(packageDir, workspace, "package.json"); + for (const name of ["dedupe-divergent-peers", "dedupe-divergent-strict", "no-deps"]) { + at = realpathSync(createRequire(at).resolve(`${name}/package.json`)); + } + loaded.add((await file(at).json()).version); + } + + expect({ bare, warnings: peerWarnings(err) }).toEqual({ + bare, + warnings: [...loaded] + .filter(version => !Bun.semver.satisfies(version, "^2.0.0")) + .map( + version => + `warn: incorrect peer dependency "no-deps@${version}" (dedupe-divergent-strict@1.0.0 requires "^2.0.0")`, + ), + }); + } + }); + + test("a workspace reached twice is reported for what its one node_modules holds", async () => { + // `lib` is a workspace named no-deps. It wants a-dep@1.0.1 and its peer-a-dep-1-0-2 wants + // a-dep@1.0.2. The root provides one a-dep and `app` the other. peer-deps-fixed's peer + // reaches `lib` again from `app`, and the isolated linker resolves both peers there too, + // but `lib` has one node_modules, and the root's side fills it. + for (const [atRoot, atApp, unmet] of [ + ["1.0.1", "1.0.2", `"a-dep@1.0.1" (peer-a-dep-1-0-2@1.0.0 requires "1.0.2")`], + ["1.0.2", "1.0.1", `"a-dep@1.0.2" (no-deps@workspace:lib requires "1.0.1")`], + ]) { + const { packageDir } = await registry.createTestDir({ + bunfigOpts: { linker }, + files: { + "package.json": JSON.stringify({ + name: "mono", + workspaces: ["lib", "app"], + dependencies: { "a-dep": atRoot }, + }), + "lib/package.json": JSON.stringify({ + name: "no-deps", + version: "2.0.0", + dependencies: { "peer-a-dep-1-0-2": "1.0.0" }, + peerDependencies: { "a-dep": "1.0.1" }, + }), + "app/package.json": JSON.stringify({ + name: "app", + version: "1.0.0", + dependencies: { "no-deps": "workspace:*", "peer-deps-fixed": "1.0.0", "a-dep": atApp }, + }), + }, + }); + + const { err } = await install(packageDir); + + const lib = realpathSync(join(packageDir, "lib", "package.json")); + const dependency = realpathSync(createRequire(lib).resolve("peer-a-dep-1-0-2/package.json")); + expect({ + lib: (await file(createRequire(lib).resolve("a-dep/package.json")).json()).version, + dependency: (await file(createRequire(dependency).resolve("a-dep/package.json")).json()).version, + warnings: peerWarnings(err), + }).toEqual({ + lib: atRoot, + dependency: atRoot, + warnings: [`warn: incorrect peer dependency ${unmet}`], + }); + } + }); }); describe("devDependencies", () => { From cb81faabc0f54dea7bdbae5d67dc9770542fa14b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 2 Oct 2026 17:06:34 +0000 Subject: [PATCH 13/13] install: run the peer cases concurrently and tighten two of them - The peer cases each use their own project, so they run concurrently, each with its own cache directory. - The folded-node case runs for the isolated linker only. The hoisted linker has no subtree that it resolves and then does not install, so that half passed with and without the fix. - The same case now fails if no out-of-range copy was compared. - docs: the dry-run sentence names `bun install --dry-run`. --- docs/pm/cli/install.mdx | 2 +- test/cli/install/bun-install-registry.test.ts | 30 +++++++++++-------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/docs/pm/cli/install.mdx b/docs/pm/cli/install.mdx index 339f7035d6e9..4671b7253b33 100644 --- a/docs/pm/cli/install.mdx +++ b/docs/pm/cli/install.mdx @@ -456,7 +456,7 @@ These flags install packages for the specified platform instead of the current s `bun install` installs required peer dependencies. If nothing in the install depends on the peer's package, Bun installs the newest version in the peer's range. -If your project or another dependency already depends on a version of the peer's package from the registry, Bun reuses that copy for the peer and installs no second copy. The reused copy can be outside the peer's range. Each install that writes `node_modules`, and each `--dry-run`, then prints a warning that names the package and the range it requires: +If your project or another dependency already depends on a version of the peer's package from the registry, Bun reuses that copy for the peer and installs no second copy. The reused copy can be outside the peer's range. Each install that writes `node_modules`, and each `bun install --dry-run`, then prints a warning that names the package and the range it requires: ```txt warn: incorrect peer dependency "react@17.0.2" (react-dom@18.3.1 requires "^18.3.1") diff --git a/test/cli/install/bun-install-registry.test.ts b/test/cli/install/bun-install-registry.test.ts index 60f0dc7f642f..54754fa2f531 100644 --- a/test/cli/install/bun-install-registry.test.ts +++ b/test/cli/install/bun-install-registry.test.ts @@ -5085,15 +5085,18 @@ describe("hoisting", async () => { // The linker that lays out node_modules decides which copy of a peer a package resolves, so it // is the one that checks the peer's range: on every install, for both linkers, naming the // dependent (#7403). The cases below get the same report from either linker. - describe.each(["hoisted", "isolated"] as const)("peer a dependent cannot resolve in range (%s linker)", linker => { + const linkers = ["hoisted", "isolated"] as const; + describe.concurrent.each(linkers)("peer a dependent cannot resolve in range (%s linker)", linker => { async function install(dir: string, ...args: string[]) { + // These cases run concurrently: each project gets its own cache, not the one in the shared `env`. + const tmp = join(dir, ".bun-tmp"); await using proc = spawn({ cmd: [bunExe(), "install", "--linker", linker, ...args], cwd: dir, stdout: "pipe", stdin: "ignore", stderr: "pipe", - env, + env: { ...env, BUN_INSTALL_CACHE_DIR: join(dir, ".bun-cache"), BUN_TMPDIR: tmp, TMPDIR: tmp, TEMP: tmp }, }); const [out, err, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); expect(err).not.toContain("error:"); @@ -5256,11 +5259,13 @@ describe("hoisting", async () => { expect(peerWarnings((await install(packageDir, "--dry-run")).err)).toEqual(expected); }); - test("a copy is reported only when a dependent loads it from disk", async () => { + // Only the isolated linker resolves a peer in a subtree that it then does not install. + test.skipIf(linker !== "isolated")("a copy is reported only when a dependent loads it from disk", async () => { // Both workspaces depend on dedupe-divergent-peers, whose dedupe-divergent-strict wants // no-deps@^2.0.0. Only `provider` has a no-deps of its own, and it is 1.0.0. The isolated // linker resolves the peer once per workspace and then keeps one store entry for both, so // one of the two resolutions is never installed. + let reported = 0; for (const [bare, provider] of [ ["ws-a", "ws-b"], ["ws-b", "ws-a"], @@ -5300,16 +5305,17 @@ describe("hoisting", async () => { loaded.add((await file(at).json()).version); } - expect({ bare, warnings: peerWarnings(err) }).toEqual({ - bare, - warnings: [...loaded] - .filter(version => !Bun.semver.satisfies(version, "^2.0.0")) - .map( - version => - `warn: incorrect peer dependency "no-deps@${version}" (dedupe-divergent-strict@1.0.0 requires "^2.0.0")`, - ), - }); + const expected = [...loaded] + .filter(version => !Bun.semver.satisfies(version, "^2.0.0")) + .map( + version => + `warn: incorrect peer dependency "no-deps@${version}" (dedupe-divergent-strict@1.0.0 requires "^2.0.0")`, + ); + expect({ bare, warnings: peerWarnings(err) }).toEqual({ bare, warnings: expected }); + reported += expected.length; } + // One of the two layouts installs the provider's resolution, so a line was compared. + expect(reported).toBeGreaterThan(0); }); test("a workspace reached twice is reported for what its one node_modules holds", async () => {