diff --git a/docs/pm/cli/install.mdx b/docs/pm/cli/install.mdx index 8a6f330d0fe1..511ba2cd9574 100644 --- a/docs/pm/cli/install.mdx +++ b/docs/pm/cli/install.mdx @@ -172,6 +172,8 @@ For reproducible installs, use `--frozen-lockfile`. Bun installs the exact versi bun install --frozen-lockfile ``` +`package.json` disagrees with `bun.lock` when a dependency would resolve to a different package, and also when every package stays as locked but the next `bun install` would rewrite `bun.lock`: a version range written differently (`^1.0.0` changed to `>=1.0.0`), a dependency moved between `dependencies`, `devDependencies`, `optionalDependencies` and `peerDependencies`, or a changed `overrides`, `catalog`, `trustedDependencies` or `patchedDependencies` entry, like `pnpm install --frozen-lockfile` and `yarn install --immutable`. The error names the section and the `package.json` it is in. Run `bun install` and commit the updated `bun.lock` to fix it. `bun ci` and `bun install --production` run the same check, so a Dockerfile that installs with `--production` also fails on a `bun.lock` that is out of date. A bumped workspace `version` on its own is accepted. A release tool that also rewrites the ranges other workspaces declare on it needs one `bun install` before the commit. A workspace project has two exceptions, because a pruned checkout can look like this: a removed `trustedDependencies` name is accepted (`bun.lock` records one list for all workspaces), and a `trustedDependencies` or `patchedDependencies` section is only compared when `bun.lock` already records it. With the legacy binary `bun.lockb`, only resolution, `overrides` and `catalog` changes are detected. + Bun does not enable `--frozen-lockfile` automatically in CI; pass the flag or use `bun ci`. If there is no lockfile at all, `--frozen-lockfile` installs from `package.json` without writing one. `--frozen-lockfile` works on a pruned monorepo checkout (e.g. `turbo prune` output, or a Docker context with only some workspace folders copied in). If a workspace listed in `bun.lock` is missing its `package.json` on disk, Bun skips it with a `note:` and does not install its exclusive dependencies. If a remaining workspace depends on a skipped one, the install fails. diff --git a/src/install/PackageManager/install_with_manager.rs b/src/install/PackageManager/install_with_manager.rs index 89da786c5647..65f036b22f43 100644 --- a/src/install/PackageManager/install_with_manager.rs +++ b/src/install/PackageManager/install_with_manager.rs @@ -134,6 +134,7 @@ pub fn install_with_manager( // this defaults to false // but we force allowing updates to the lockfile when you do bun add let mut had_any_diffs = false; + let mut loaded_manifest_sections: Option = None; let mut direct_deps_before = DirectDependencies::default(); manager.progress = Default::default(); @@ -235,6 +236,14 @@ pub fn install_with_manager( }; had_any_diffs = manager.summary.has_diffs(); + // For the frozen-lockfile check; the loaded sections are replaced below. + if had_any_diffs + && manager.options.enable.frozen_lockfile() + && ok.format == lockfile::Format::Text + && ok.migrated == lockfile::Migrated::None + { + loaded_manifest_sections = Some(manager.lockfile.manifest_sections()); + } // The lockfile does not store the set. Every install takes it from the manifests. manager .lockfile @@ -789,6 +798,8 @@ pub fn install_with_manager( { 'frozen_lockfile: { let changed_section = frozen_changed_section(manager, root_package_json_path); + // A section bun.lock records differently, and the directory of its package.json. + let mut mismatch: Option<(&'static str, Box<[u8]>)> = None; if changed_section.is_none() { if load_result.loaded_from_text_lockfile() { if bun_core::handle_oom(Lockfile::eql( @@ -796,7 +807,16 @@ pub fn install_with_manager( &lockfile_before_clean, lockfile_before_clean.loaded_package_count as usize, )) { - break 'frozen_lockfile; + if let Some(loaded) = &loaded_manifest_sections { + mismatch = manager + .lockfile + .manifest_sections() + .changed_since(loaded) + .map(|(section, dir)| (section, Box::from(dir))); + } + if mismatch.is_none() { + break 'frozen_lockfile; + } } } else if !(manager .lockfile @@ -821,6 +841,14 @@ pub fn install_with_manager( section, loaded_lockfile_name(&load_result) ); + } else if let Some((section, dir)) = &mismatch { + bun_core::note!( + "{} does not match {} in {}{}package.json", + loaded_lockfile_name(&load_result), + section, + bstr::BStr::new(dir), + if dir.is_empty() { "" } else { "/" }, + ); } bun_core::note!( "try re-running without --frozen-lockfile and commit the updated lockfile" diff --git a/src/install/lockfile.rs b/src/install/lockfile.rs index 4c46bc82500e..610fc1f46bb9 100644 --- a/src/install/lockfile.rs +++ b/src/install/lockfile.rs @@ -2874,7 +2874,218 @@ impl<'a> EqlSorter<'a> { } } +/// One dependency row of a workspace entry in bun.lock. +#[derive(PartialEq, Eq, PartialOrd, Ord)] +struct ManifestDependency { + name: Box<[u8]>, + /// `Behavior` bits of the dependency groups it is listed under. + groups: u8, + literal: Box<[u8]>, + /// The range a `catalog:` literal stands for. + catalog_range: Option>, +} + +impl ManifestDependency { + const OPTIONAL_PEER: u8 = + dependency::Behavior::PEER.bits() | dependency::Behavior::OPTIONAL.bits(); + + /// Migrating a pnpm-lock.yaml records the catalog's range where package.json says `catalog:`. + fn is_recorded_as(&self, recorded: &Self) -> bool { + self.name == recorded.name + && self.groups == recorded.groups + && (self.literal == recorded.literal + || self.catalog_range.as_ref() == Some(&recorded.literal)) + } + + /// A `peerDependenciesMeta`-only name is a `*` optional peer; older bun.lock files lack the row. + fn may_be_unrecorded(&self) -> bool { + self.groups == Self::OPTIONAL_PEER && *self.literal == *b"*" + } + + /// Both sorted. + fn all_recorded(now: &[Self], recorded: &[Self]) -> bool { + let mut recorded = recorded.iter().peekable(); + for dep in now { + if recorded.peek().is_some_and(|row| dep.is_recorded_as(row)) { + recorded.next(); + } else if !dep.may_be_unrecorded() { + return false; + } + } + recorded.next().is_none() + } +} + +/// The manifest-derived sections of bun.lock, mirrored from `bun_lock::Stringifier::save_from_binary`. +/// Overrides, catalogs and workspace versions are not part of it. +pub(crate) struct ManifestSections { + /// Workspace path (`""` for the root) with its sorted dependencies. + workspaces: Vec<(Box<[u8]>, Vec)>, + /// Sorted names that apply to the tree. `None` when the lockfile has no list. + trusted_dependencies: Option>>, + /// Sorted (`name@version`, patch path) that apply to the tree. `None` when there are none. + patched_dependencies: Option, Box<[u8]>)>>, +} + +impl ManifestSections { + /// The first section where `self` differs from `loaded`, with its package.json's directory. + pub(crate) fn changed_since(&self, loaded: &ManifestSections) -> Option<(&'static str, &[u8])> { + if self.workspaces.len() != loaded.workspaces.len() { + return Some(("workspaces", b"")); + } + for ((path, now), (recorded_path, recorded)) in + self.workspaces.iter().zip(&loaded.workspaces) + { + if path != recorded_path { + return Some(("workspaces", b"")); + } + if !ManifestDependency::all_recorded(now, recorded) { + return Some(("dependencies", path)); + } + } + + // A pruned checkout declares fewer trusted names, and its bun.lock may lack either list. + let maybe_pruned = loaded.workspaces.len() > 1; + + let recorded = loaded.trusted_dependencies.as_deref(); + if recorded.is_some() || !maybe_pruned { + let recorded = recorded.unwrap_or_default(); + let declared = self.trusted_dependencies.as_deref().unwrap_or_default(); + let added = declared + .iter() + .any(|name| recorded.binary_search(name).is_err()); + let removed = !maybe_pruned && declared.len() < recorded.len(); + if added || removed { + return Some(("trustedDependencies", b"")); + } + } + + let recorded = loaded.patched_dependencies.as_deref(); + if (recorded.is_some() || !maybe_pruned) + && self.patched_dependencies.as_deref().unwrap_or_default() + != recorded.unwrap_or_default() + { + return Some(("patchedDependencies", b"")); + } + None + } +} + impl Lockfile { + pub(crate) fn manifest_sections(&self) -> ManifestSections { + let buf = self.buffers.string_bytes.as_slice(); + let deps_buf = self.buffers.dependencies.as_slice(); + let hoisted_deps = self.buffers.hoisted_dependencies.as_slice(); + let pkgs = self.packages.slice(); + let pkg_names = pkgs.items_name(); + let pkg_name_hashes = pkgs.items_name_hash(); + let pkg_resolutions = pkgs.items_resolution(); + let pkg_deps = pkgs.items_dependencies(); + + let groups = dependency::Behavior::PROD + | dependency::Behavior::DEV + | dependency::Behavior::OPTIONAL + | dependency::Behavior::PEER; + let mut workspaces = Vec::new(); + for pkg_id in 0..pkgs.len() { + let res = &pkg_resolutions[pkg_id]; + let path: &[u8] = match res.tag { + ResolutionTag::Root => b"", + ResolutionTag::Workspace => res.workspace().slice(buf), + _ => continue, + }; + let mut deps: Vec = pkg_deps[pkg_id] + .get(deps_buf) + .iter() + .filter(|dep| dep.behavior.intersects(groups)) + .map(|dep| ManifestDependency { + name: Box::from(dep.name.slice(buf)), + groups: dep.behavior.intersection(groups).bits(), + literal: Box::from(dep.version.literal.slice(buf)), + catalog_range: (dep.version.tag == dependency::Tag::Catalog).then(|| { + Box::from(self.catalogs.resolve_range(buf, dep).literal.slice(buf)) + }), + }) + .collect(); + deps.sort_unstable(); + workspaces.push((Box::<[u8]>::from(path), deps)); + } + workspaces.sort_unstable_by(|l, r| l.0.cmp(&r.0)); + + let mut trusted_dependencies: Option>> = + self.trusted_dependencies.as_ref().map(|_| Vec::new()); + let mut patched_dependencies: Option, Box<[u8]>)>> = + (self.patched_dependencies.count() > 0).then(Vec::new); + let mut name_and_version: Vec = Vec::new(); + for tree in self.buffers.trees.iter() { + for &dep_id in tree.dependencies.get(hoisted_deps) { + if dep_id == invalid_dependency_id { + continue; + } + let pkg_id = self.buffers.resolutions[dep_id as usize]; + if pkg_id == invalid_package_id { + continue; + } + let dep = &deps_buf[dep_id as usize]; + + if let (Some(trusted), Some(found)) = + (&self.trusted_dependencies, &mut trusted_dependencies) + { + let name = dep.name.slice(buf); + if trusted + .get(&(dep.name_hash as TruncatedPackageNameHash)) + .is_some_and(|trusted_name| **trusted_name == *name) + { + found.push(Box::from(name)); + } + } + + if let Some(found) = &mut patched_dependencies { + let res = &pkg_resolutions[pkg_id as usize]; + name_and_version.clear(); + let _ = write!( + &mut name_and_version, + "{}@", + bstr::BStr::new(pkg_names[pkg_id as usize].slice(buf)) + ); + if res.tag == ResolutionTag::Workspace { + if let Some(version) = self + .workspace_versions + .get(&pkg_name_hashes[pkg_id as usize]) + { + let _ = write!(&mut name_and_version, "{}", version.fmt(buf)); + } + } else { + let _ = write!(&mut name_and_version, "{}", res.fmt(buf, PathSep::Posix)); + } + if let Some(patch) = self + .patched_dependencies + .get(&SemverStringBuilder::string_hash(&name_and_version)) + { + found.push(( + Box::from(name_and_version.as_slice()), + Box::from(patch.path.slice(buf)), + )); + } + } + } + } + if let Some(found) = &mut trusted_dependencies { + found.sort_unstable(); + found.dedup(); + } + if let Some(found) = &mut patched_dependencies { + found.sort_unstable(); + found.dedup(); + } + + ManifestSections { + workspaces, + trusted_dependencies, + patched_dependencies, + } + } + /// A placement of `r` bound past `r_loaded_package_count` was rebound after loading: a change. pub(crate) fn eql( &self, diff --git a/src/install/lockfile/Package.rs b/src/install/lockfile/Package.rs index 20316ef6323b..c8225276520a 100644 --- a/src/install/lockfile/Package.rs +++ b/src/install/lockfile/Package.rs @@ -1428,12 +1428,25 @@ impl Diff { let cur_to_i = to_i; to_i += 1; - if Dependency::eql( - &to_deps!()[cur_to_i], - from_dep, - to_lockfile.buffers.string_bytes.as_slice(), - from_lockfile.buffers.string_bytes.as_slice(), - ) { + // Workspace versions compare by path; bun.lock records the literal, so a retyped one is an update. + let workspace_literal_retyped = { + let to_dep = &to_deps!()[cur_to_i]; + to_dep.version.tag == dependency::version::Tag::Workspace + && !from_dep.behavior.is_workspace() + && !to_dep.version.literal.eql( + from_dep.version.literal, + to_lockfile.buffers.string_bytes.as_slice(), + from_lockfile.buffers.string_bytes.as_slice(), + ) + }; + if !workspace_literal_retyped + && Dependency::eql( + &to_deps!()[cur_to_i], + from_dep, + to_lockfile.buffers.string_bytes.as_slice(), + from_lockfile.buffers.string_bytes.as_slice(), + ) + { if let Some(updates) = update_requests { if updates.is_empty() || (named_update_here diff --git a/test/cli/install/frozen-lockfile-outdated.test.ts b/test/cli/install/frozen-lockfile-outdated.test.ts new file mode 100644 index 000000000000..d9456501d7c6 --- /dev/null +++ b/test/cli/install/frozen-lockfile-outdated.test.ts @@ -0,0 +1,672 @@ +// `--frozen-lockfile` / `bun ci` on a checkout where package.json and bun.lock disagree (an edited +// package.json, a mis-merged bun.lock) in ways that leave every package resolved exactly as locked. +// A plain `bun install` rewrites bun.lock for these, so a frozen install has to fail on them, and +// it has to keep passing on the differences a plain install does not record. +import { file, write } from "bun"; +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { rm } from "fs/promises"; +import { VerdaccioRegistry, bunEnv, bunExe, normalizeBunSnapshot } from "harness"; +import { join } from "path"; + +const registry = new VerdaccioRegistry(); + +beforeAll(async () => { + await registry.start(); +}); + +afterAll(() => { + registry.stop(); +}); + +type PackageJson = Record; + +const patch = `diff --git a/patched.txt b/patched.txt +new file mode 100644 +index 0000000000000000000000000000000000000000..3b18e512dba79e4c8300dd08aeb37f8e728b8dad +--- /dev/null ++++ b/patched.txt +@@ -0,0 +1 @@ ++hello world +`; + +// no-deps@^1.0.0 locks 1.1.0 (the registry also has 1.0.0, 1.0.1 and 2.0.0). +const root: PackageJson = { + name: "root", + version: "1.0.0", + workspaces: ["packages/*"], + dependencies: { "a-dep": "1.0.1", "no-deps": "^1.0.0" }, + trustedDependencies: ["a-dep"], + patchedDependencies: { "a-dep@1.0.1": "patches/a-dep@1.0.1.patch" }, +}; +const member: PackageJson = { + name: "member", + version: "1.0.0", + scripts: { postinstall: "echo postinstall" }, + dependencies: { "a-dep": "1.0.1" }, +}; + +async function bun(cwd: string, ...args: string[]) { + await using proc = Bun.spawn({ + cmd: [bunExe(), ...args], + cwd, + env: { ...bunEnv, BUN_INSTALL_CACHE_DIR: join(cwd, ".bun-cache") }, + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { stdout, stderr, exitCode }; +} + +// A project installed once from `rootJson` / `memberJson`, returning its dir and the bun.lock that install wrote. +// A `rootJson` without "workspaces" gets no workspace folders. +async function installed(rootJson: PackageJson = root, memberJson: PackageJson = member) { + const { packageDir } = await registry.createTestDir({ + bunfigOpts: { linker: "hoisted" }, + files: { + "package.json": JSON.stringify(rootJson), + ...(rootJson.workspaces && { + "packages/member/package.json": JSON.stringify(memberJson), + "packages/shared/package.json": JSON.stringify({ name: "shared", version: "1.0.0" }), + }), + "patches/a-dep@1.0.1.patch": patch, + "patches/no-deps@1.1.0.patch": patch, + }, + }); + const { stderr, exitCode } = await bun(packageDir, "install"); + expect(stderr).toContain("Saved lockfile"); + expect(exitCode).toBe(0); + return { packageDir, lock: await file(join(packageDir, "bun.lock")).text() }; +} + +const writeRoot = (dir: string, json: PackageJson) => write(join(dir, "package.json"), JSON.stringify(json)); +const writeMember = (dir: string, json: PackageJson) => + write(join(dir, "packages", "member", "package.json"), JSON.stringify(json)); +const lockText = (dir: string) => file(join(dir, "bun.lock")).text(); + +const frozenError = "error: lockfile had changes, but lockfile is frozen"; +const sectionNote = (section: string, packageJson = "package.json") => + `note: bun.lock does not match ${section} in ${packageJson}`; + +type Edit = { + section: "dependencies" | "trustedDependencies" | "patchedDependencies"; + /** The root package.json the project is installed from, `root` by default. */ + from?: PackageJson; + root?: (json: PackageJson) => PackageJson; + member?: (json: PackageJson) => PackageJson; +}; + +const without = (json: PackageJson, key: string) => { + const { [key]: _, ...rest } = json; + return rest; +}; + +const singlePackage = without(root, "workspaces"); +// Two catalogs with the same range, so only the literal tells `catalog:` from `catalog:other`. +const twoCatalogs: PackageJson = { + ...root, + workspaces: { + packages: ["packages/*"], + catalog: { "no-deps": "^1.0.0" }, + catalogs: { other: { "no-deps": "^1.0.0" } }, + }, + dependencies: { ...root.dependencies, "no-deps": "catalog:" }, +}; +// one-dep@1.0.0 depends on no-deps@1.0.1, so no-deps is in the tree without the root listing it. +const transitive: PackageJson = { name: "root", version: "1.0.0", dependencies: { "one-dep": "1.0.0" } }; + +// Each edit keeps every package at its locked version; the next plain `bun install` rewrites bun.lock for all of them. +const rewrittenByInstall: Record = { + "a dependency's range is loosened but still satisfied by the locked version": { + section: "dependencies", + root: json => ({ ...json, dependencies: { ...json.dependencies, "no-deps": ">=1.0.0" } }), + }, + "a dependency's range is raised to the locked version": { + section: "dependencies", + root: json => ({ ...json, dependencies: { ...json.dependencies, "no-deps": "^1.1.0" } }), + }, + "a dependency's range is pinned to the locked version": { + section: "dependencies", + root: json => ({ ...json, dependencies: { ...json.dependencies, "no-deps": "1.1.0" } }), + }, + "a dependency is added that the lockfile already resolves transitively": { + section: "dependencies", + from: transitive, + root: json => ({ ...json, dependencies: { ...json.dependencies, "no-deps": "1.0.1" } }), + }, + "a dependency that stays in the tree transitively is removed": { + section: "dependencies", + from: { ...transitive, dependencies: { ...transitive.dependencies, "no-deps": "1.0.1" } }, + root: json => ({ ...json, dependencies: without(json.dependencies, "no-deps") }), + }, + "a catalog: dependency moves to another catalog with the same range": { + section: "dependencies", + from: twoCatalogs, + root: json => ({ ...json, dependencies: { ...json.dependencies, "no-deps": "catalog:other" } }), + }, + "a dependency moves from dependencies to devDependencies": { + section: "dependencies", + root: json => ({ + ...json, + dependencies: without(json.dependencies, "no-deps"), + devDependencies: { "no-deps": "^1.0.0" }, + }), + }, + "a workspace drops a dependency that the root still needs": { + section: "dependencies", + member: json => ({ ...json, dependencies: without(json.dependencies, "a-dep") }), + }, + "a workspace adds a dependency that the lockfile already resolves for another workspace": { + section: "dependencies", + member: json => ({ ...json, dependencies: { ...json.dependencies, "no-deps": "^1.0.0" } }), + }, + "a patchedDependencies entry is added for a locked package": { + section: "patchedDependencies", + root: json => ({ + ...json, + patchedDependencies: { ...json.patchedDependencies, "no-deps@1.1.0": "patches/no-deps@1.1.0.patch" }, + }), + }, + "a patchedDependencies entry is removed": { + section: "patchedDependencies", + root: json => without(json, "patchedDependencies"), + }, + "a locked package is added to trustedDependencies": { + section: "trustedDependencies", + root: json => ({ ...json, trustedDependencies: ["a-dep", "no-deps"] }), + }, + // The rest only counts without workspaces: a pruned workspace checkout can lack names or the whole list, see below. + "the first trustedDependencies list is added": { + section: "trustedDependencies", + from: without(singlePackage, "trustedDependencies"), + root: json => ({ ...json, trustedDependencies: ["a-dep"] }), + }, + "the first patchedDependencies entry is added": { + section: "patchedDependencies", + from: without(singlePackage, "patchedDependencies"), + root: json => ({ ...json, patchedDependencies: { "a-dep@1.0.1": "patches/a-dep@1.0.1.patch" } }), + }, + "trustedDependencies is emptied": { + section: "trustedDependencies", + from: singlePackage, + root: json => ({ ...json, trustedDependencies: [] }), + }, + "trustedDependencies is removed": { + section: "trustedDependencies", + from: singlePackage, + root: json => without(json, "trustedDependencies"), + }, +}; + +describe.concurrent("--frozen-lockfile fails when bun install would rewrite bun.lock for", () => { + test.each(Object.entries(rewrittenByInstall))("%s", async (_name, edit) => { + const from = edit.from ?? root; + const { packageDir, lock } = await installed(from); + if (edit.root) await writeRoot(packageDir, edit.root(from)); + if (edit.member) await writeMember(packageDir, edit.member(member)); + + const frozen = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(frozen.stderr).toContain(frozenError); + expect(frozen.stderr).toContain( + sectionNote(edit.section, edit.member ? "packages/member/package.json" : "package.json"), + ); + expect(await lockText(packageDir)).toBe(lock); + expect(frozen.exitCode).toBe(1); + + // What the failure protects: the lockfile a plain install leaves behind differs. + const plain = await bun(packageDir, "install"); + + expect(plain.stderr).toContain("Saved lockfile"); + expect(await lockText(packageDir)).not.toBe(lock); + expect(plain.exitCode).toBe(0); + + const after = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(after.stderr).not.toContain("error:"); + expect(after.exitCode).toBe(0); + }); + + // While bun.lock does not record the trust, the differ reports the package as newly trusted on every install and its + // lifecycle scripts run again on the installed tree. Only a plain install can record it, so a frozen one has to stop. + test("a newly trusted package's postinstall is not run by every frozen install", async () => { + const untrusted = { name: "root", version: "1.0.0", dependencies: { "lifecycle-postinstall": "1.0.0" } }; + const { packageDir, lock } = await installed(untrusted); + // A BunFile keeps the size it first saw, so every read takes a new one. + const postinstallTxt = () => file(join(packageDir, "node_modules", "lifecycle-postinstall", "postinstall.txt")); + expect(await postinstallTxt().exists()).toBeFalse(); + await writeRoot(packageDir, { ...untrusted, trustedDependencies: ["lifecycle-postinstall"] }); + + for (const _ of [1, 2]) { + const frozen = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(frozen.stderr).toContain(sectionNote("trustedDependencies")); + expect(await postinstallTxt().exists()).toBeFalse(); + expect(await lockText(packageDir)).toBe(lock); + expect(frozen.exitCode).toBe(1); + } + + const plain = await bun(packageDir, "install"); + + expect(plain.stderr).toContain("Saved lockfile"); + expect(await postinstallTxt().text()).toBe("postinstall!"); + expect(plain.exitCode).toBe(0); + + const after = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(after.stderr).not.toContain("error:"); + // The script writes "postinstall exists!" when it runs a second time. + expect(await postinstallTxt().text()).toBe("postinstall!"); + expect(after.exitCode).toBe(0); + }); + + // `git merge` joins two branches' bun.lock without conflict markers when a workspace's block ends with the same line + // as the root's, and the new root dependency lands in the workspace's block. The tree is the same either way. + test("a root dependency that a merge put into a workspace's block of bun.lock", async () => { + const { packageDir, lock } = await installed(); + const row = ' "no-deps": "^1.0.0",\n'; + const memberDependencies = + '"packages/member": {\n "name": "member",\n "version": "1.0.0",\n "dependencies": {\n "a-dep": "1.0.1",\n'; + expect(lock.indexOf(row)).toBeGreaterThan(-1); + expect(lock.indexOf(row)).toBeLessThan(lock.indexOf(memberDependencies)); + const merged = lock.replace(row, "").replace(memberDependencies, memberDependencies + row); + expect(merged).not.toBe(lock); + await write(join(packageDir, "bun.lock"), merged); + + const frozen = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(frozen.stderr).toContain(frozenError); + expect(frozen.stderr).toContain(sectionNote("dependencies")); + expect(await lockText(packageDir)).toBe(merged); + expect(frozen.exitCode).toBe(1); + + const plain = await bun(packageDir, "install"); + + expect(plain.stderr).toContain("Saved lockfile"); + expect(await lockText(packageDir)).toBe(lock); + expect(plain.exitCode).toBe(0); + + const after = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(after.stderr).not.toContain("error:"); + expect(after.exitCode).toBe(0); + }); + + test("prints which section changed, also as bun ci and bun install --production", async () => { + const unpatched = without(root, "patchedDependencies"); + const { packageDir, lock } = await installed(unpatched); + await writeRoot(packageDir, { ...unpatched, dependencies: { ...unpatched.dependencies, "no-deps": ">=1.0.0" } }); + + const { stdout, stderr, exitCode } = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(normalizeBunSnapshot(stderr, packageDir)).toMatchInlineSnapshot(` + "error: lockfile had changes, but lockfile is frozen + note: bun.lock does not match dependencies in package.json + note: try re-running without --frozen-lockfile and commit the updated lockfile" + `); + expect(normalizeBunSnapshot(stdout, packageDir)).toMatchInlineSnapshot(`"bun install ()"`); + expect(exitCode).toBe(1); + + // Both imply --frozen-lockfile. + for (const args of [["ci"], ["install", "--production"]]) { + const implied = await bun(packageDir, ...args); + + expect(implied.stderr).toContain(frozenError); + expect(implied.stderr).toContain(sectionNote("dependencies")); + expect(await lockText(packageDir)).toBe(lock); + expect(implied.exitCode).toBe(1); + } + }); +}); + +// Names bun.lock does not list because they are not in the tree. The differ reports them as added on every install, so +// adding them to a fixture guarantees the comparison runs even when nothing recorded changed. +const staleTrustedDependencies = ["a-dep", "not-installed", "esbuild", "sharp", "@prisma/client", "core-js", "bcrypt"]; + +// Edits for which a plain `bun install` leaves bun.lock byte for byte as it is. +const notRecorded: Record> = { + "a trustedDependencies name that is not in the tree": { + root: json => ({ ...json, trustedDependencies: ["a-dep", "not-installed"] }), + }, + "several trustedDependencies names that are not in the tree": { + root: json => ({ ...json, trustedDependencies: staleTrustedDependencies }), + }, + "a workspace's lifecycle script": { + root: json => ({ ...json, trustedDependencies: staleTrustedDependencies }), + member: json => ({ ...json, scripts: { postinstall: "echo changed" } }), + }, + "package.json key order and formatting": { + root: json => ({ + trustedDependencies: staleTrustedDependencies, + ...without(json, "trustedDependencies"), + dependencies: { "no-deps": "^1.0.0", "a-dep": "1.0.1" }, + }), + }, + // bun.lock only records the patchedDependencies entries that apply to a package in the tree. + "a patchedDependencies entry for a version that is not in the tree": { + root: json => ({ + ...json, + patchedDependencies: { ...json.patchedDependencies, "no-deps@2.0.0": "patches/no-deps@1.1.0.patch" }, + }), + }, +}; + +describe.concurrent("--frozen-lockfile still passes", () => { + test.each(Object.entries(notRecorded))("%s", async (_name, edit) => { + const { packageDir, lock } = await installed(); + if (edit.root) await writeRoot(packageDir, edit.root(root)); + if (edit.member) await writeMember(packageDir, edit.member(member)); + + const frozen = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(frozen.stderr).not.toContain("error:"); + expect(await lockText(packageDir)).toBe(lock); + expect(frozen.exitCode).toBe(0); + + const plain = await bun(packageDir, "install"); + + expect(plain.stderr).not.toContain("Saved lockfile"); + expect(await lockText(packageDir)).toBe(lock); + expect(plain.exitCode).toBe(0); + }); + + // The next four are edits a plain install does write to bun.lock, accepted on purpose. + + // bun.lock records workspace versions, but release tooling bumps them without an install (pnpm and yarn accept this + // too), also when the differ reports something else on the same run. + test("a workspace's version", async () => { + const { packageDir, lock } = await installed(); + await writeMember(packageDir, { ...member, version: "1.0.1" }); + await writeRoot(packageDir, { ...root, trustedDependencies: staleTrustedDependencies }); + + const frozen = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(frozen.stderr).not.toContain("error:"); + expect(await lockText(packageDir)).toBe(lock); + expect(frozen.exitCode).toBe(0); + }); + + // bun.lock records one trustedDependencies list for all workspaces, so a checkout with a workspace left out (a Docker + // context, `turbo prune`) declares fewer names than bun.lock lists. A removal therefore only counts without workspaces. + test("a pruned checkout without the workspace that declared a trustedDependencies name", async () => { + const { packageDir, lock } = await installed(without(root, "trustedDependencies"), { + ...member, + dependencies: { ...member.dependencies, "no-deps": "^1.0.0" }, + trustedDependencies: ["a-dep", "no-deps"], + }); + expect(lock).toContain('"trustedDependencies": ['); + await rm(join(packageDir, "packages", "member"), { recursive: true, force: true }); + await rm(join(packageDir, "node_modules"), { recursive: true, force: true }); + + const frozen = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(frozen.stderr).not.toContain("error:"); + expect(frozen.stderr).toContain('note: skipped 1 workspace listed in bun.lock but not on disk: "member"'); + expect(await lockText(packageDir)).toBe(lock); + expect(frozen.exitCode).toBe(0); + }); + + test("a trustedDependencies name removed in a workspace project", async () => { + const { packageDir, lock } = await installed(); + await writeRoot(packageDir, { ...root, trustedDependencies: [] }); + + const frozen = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(frozen.stderr).not.toContain("error:"); + expect(await lockText(packageDir)).toBe(lock); + expect(frozen.exitCode).toBe(0); + }); + + // `turbo prune` releases have dropped either section from bun.lock while copying the root package.json that declares + // it (vercel/turborepo#11027, vercel/turborepo#13740), so in a workspace project a list bun.lock never recorded is + // not compared. Without workspaces there is no pruned checkout, and the first list fails (see above). + test.each(["trustedDependencies", "patchedDependencies"])( + "a %s list that a workspace project's bun.lock never recorded", + async section => { + const { packageDir, lock } = await installed(without(root, section)); + expect(lock).not.toContain(section); + // The stale names make the differ report a change in the patchedDependencies case too. + await writeRoot(packageDir, { ...root, trustedDependencies: staleTrustedDependencies }); + + const frozen = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(frozen.stderr).not.toContain("error:"); + expect(await lockText(packageDir)).toBe(lock); + expect(frozen.exitCode).toBe(0); + }, + ); + + test("trustedDependencies declared by a workspace", async () => { + const { packageDir, lock } = await installed( + { ...root, trustedDependencies: staleTrustedDependencies }, + { ...member, trustedDependencies: ["a-dep"] }, + ); + + const frozen = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(frozen.stderr).not.toContain("error:"); + expect(await lockText(packageDir)).toBe(lock); + expect(frozen.exitCode).toBe(0); + }); + + // --production implies --frozen-lockfile and leaves devDependencies out of node_modules, not out of the comparison. + test("--production with trusted and patched devDependencies", async () => { + const { packageDir, lock } = await installed( + { + ...without(root, "dependencies"), + devDependencies: root.dependencies, + trustedDependencies: staleTrustedDependencies, + }, + { name: "member", version: "1.0.0" }, + ); + expect(lock).toContain('"trustedDependencies"'); + expect(lock).toContain('"patchedDependencies"'); + + const production = await bun(packageDir, "install", "--production"); + + expect(production.stderr).not.toContain("error:"); + expect(await lockText(packageDir)).toBe(lock); + expect(production.exitCode).toBe(0); + }); + + // An older bun, another tool or a CRLF checkout formats bun.lock differently; only what it records is compared. + test("a bun.lock that this version of bun would format differently", async () => { + const { packageDir, lock } = await installed(); + const reformatted = lock.replace(' "configVersion": 1,\n', "").replaceAll("\n", "\r\n"); + expect(reformatted).not.toBe(lock); + await write(join(packageDir, "bun.lock"), reformatted); + await writeRoot(packageDir, { ...root, trustedDependencies: ["a-dep", "not-installed"] }); + + const frozen = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(frozen.stderr).not.toContain("error:"); + expect(await lockText(packageDir)).toBe(reformatted); + expect(frozen.exitCode).toBe(0); + }); + + // The next two are lockfiles bun itself wrote for an unedited package.json. A plain install rewrites them, but a red + // `bun ci` on an untouched checkout would blame an edit nobody made. + + // bun records a name that is only in peerDependenciesMeta as a `*` optional peer. Older versions did not. + test("a bun.lock from before peerDependenciesMeta-only names were recorded", async () => { + const { packageDir, lock } = await installed(root, { + ...member, + peerDependenciesMeta: { "no-deps": { optional: true } }, + }); + const optionalPeerRows = + ',\n "peerDependencies": {\n "no-deps": "*",\n },\n "optionalPeers": [\n "no-deps",\n ]'; + expect(lock).toContain(optionalPeerRows); + const older = lock.replace(optionalPeerRows, ""); + await write(join(packageDir, "bun.lock"), older); + + const frozen = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(frozen.stderr).not.toContain("error:"); + expect(await lockText(packageDir)).toBe(older); + expect(frozen.exitCode).toBe(0); + }); + + // Migrating a pnpm-lock.yaml records the catalog's range where package.json says `catalog:`. + test("a bun.lock that records a catalog: dependency as the catalog's range", async () => { + const { packageDir, lock } = await installed({ + ...root, + workspaces: { packages: ["packages/*"], catalog: { "no-deps": "^1.0.0" } }, + dependencies: { ...root.dependencies, "no-deps": "catalog:" }, + }); + expect(lock).toContain('"no-deps": "catalog:"'); + const migrated = lock.replace('"no-deps": "catalog:"', '"no-deps": "^1.0.0"'); + await write(join(packageDir, "bun.lock"), migrated); + + const frozen = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(frozen.stderr).not.toContain("error:"); + expect(await lockText(packageDir)).toBe(migrated); + expect(frozen.exitCode).toBe(0); + }); +}); + +// Ways workspaces reach each other that bun.lock reloads through its own rules. The comparison sees the reloaded +// lockfile on one side and the reparsed package.json files on the other, so each has to come out the same. The stale +// trustedDependencies name makes the comparison run. +const monorepo = (members: Record, rootJson: PackageJson = {}) => ({ + "package.json": { name: "root", workspaces: ["packages/*"], trustedDependencies: ["not-installed"], ...rootJson }, + ...Object.fromEntries( + Object.entries(members).map(([name, json]) => [`packages/${name}/package.json`, { name, ...json }]), + ), +}); +const unchangedProjects: Record> = { + "a workspace: dependency on a sibling": monorepo({ + app: { version: "1.0.0", dependencies: { lib: "workspace:*", "no-deps": "^1.0.0" } }, + lib: { version: "1.0.0", dependencies: { "a-dep": "1.0.1" } }, + }), + "root dependencies on its own workspaces": monorepo( + { app: { version: "1.0.0" }, lib: { version: "1.0.0" } }, + { dependencies: { app: "workspace:*", "no-deps": "^1.0.0" }, devDependencies: { lib: "^1.0.0" } }, + ), + "a root range its workspace does not satisfy, sent there by an override": monorepo( + { lib: { version: "1.0.0" } }, + { dependencies: { lib: "^9.0.0", "no-deps": "^1.0.0" }, overrides: { lib: "workspace:*" } }, + ), + "a sibling in devDependencies and peerDependencies": monorepo({ + app: { version: "1.0.0", devDependencies: { lib: "workspace:*" }, peerDependencies: { lib: "*" } }, + lib: { version: "1.0.0" }, + }), + "a sibling range in two dependency groups": monorepo({ + app: { version: "1.0.0", devDependencies: { lib: "^1.0.0" }, peerDependencies: { lib: "^1.0.0" } }, + lib: { version: "1.0.0" }, + }), + "a star range on a sibling without a version": monorepo({ + app: { version: "1.0.0", dependencies: { lib: "*" } }, + lib: {}, + }), + "an npm: alias of a sibling": monorepo({ + app: { version: "1.0.0", dependencies: { renamed: "npm:lib@*" } }, + lib: { version: "1.0.0" }, + }), + "a catalog entry that points at a workspace": monorepo( + { app: { version: "1.0.0", dependencies: { lib: "catalog:", "no-deps": "catalog:" } }, lib: { version: "1.0.0" } }, + { workspaces: { packages: ["packages/*"], catalog: { lib: "workspace:*", "no-deps": "^1.0.0" } } }, + ), + "an override that sends an unsatisfied range to a workspace": monorepo( + { app: { version: "1.0.0", dependencies: { lib: "^5.0.0" } }, lib: { version: "1.0.0" } }, + { overrides: { lib: "workspace:*" } }, + ), + "an optional peer and a lifecycle script in a workspace": monorepo({ + app: { + version: "1.0.0", + scripts: { postinstall: "echo postinstall" }, + peerDependencies: { "no-deps": "^1.0.0", "a-dep": "^1.0.1" }, + peerDependenciesMeta: { "a-dep": { optional: true } }, + }, + }), + "a $name override": { + "package.json": { + name: "root", + dependencies: { "no-deps": "^1.0.0", "a-dep": "1.0.1" }, + overrides: { "a-dep": "$no-deps" }, + trustedDependencies: ["not-installed"], + }, + }, +}; + +describe.concurrent("--frozen-lockfile still passes on an unchanged project with", () => { + test.each(Object.entries(unchangedProjects))("%s", async (_name, files) => { + const { packageDir } = await registry.createTestDir({ + bunfigOpts: { linker: "hoisted" }, + files: Object.fromEntries(Object.entries(files).map(([path, json]) => [path, JSON.stringify(json)])), + }); + const first = await bun(packageDir, "install"); + expect(first.stderr).toContain("Saved lockfile"); + expect(first.exitCode).toBe(0); + const lock = await lockText(packageDir); + + const frozen = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(frozen.stderr).not.toContain("error:"); + expect(frozen.exitCode).toBe(0); + + // And from a clean checkout, as CI runs it. + await rm(join(packageDir, "node_modules"), { recursive: true, force: true }); + const ci = await bun(packageDir, "ci"); + + expect(ci.stderr).not.toContain("error:"); + expect(ci.exitCode).toBe(0); + + const plain = await bun(packageDir, "install"); + + expect(plain.stderr).not.toContain("Saved lockfile"); + expect(await lockText(packageDir)).toBe(lock); + expect(plain.exitCode).toBe(0); + }); +}); + +// `changeset version` and similar tools bump a workspace's version together with the ranges its dependents declare on +// it. The old and the new range both link the workspace, and bun.lock records the range as written, so the one +// `bun install` that follows has to record the new one for the committed lockfile to pass `bun ci`. +describe.concurrent("--frozen-lockfile passes after a workspace version bump and one install, with the range", () => { + test.each([ + ["1.0.0", "1.0.1"], + ["^1.0.0", "^1.0.1"], + ["workspace:*", "workspace:^"], + ])("%s rewritten to %s", async (before, after) => { + const files = (libVersion: string, range: string) => + monorepo({ app: { version: "1.0.0", dependencies: { lib: range } }, lib: { version: libVersion } }); + const writeAll = (dir: string, tree: Record) => + Promise.all(Object.entries(tree).map(([path, json]) => write(join(dir, path), JSON.stringify(json)))); + const appEntry = (lock: string) => lock.slice(lock.indexOf('"packages/app"'), lock.indexOf('"packages/lib"')); + + const { packageDir } = await registry.createTestDir({ bunfigOpts: { linker: "hoisted" }, files: {} }); + await writeAll(packageDir, files("1.0.0", before)); + const first = await bun(packageDir, "install"); + expect(first.stderr).toContain("Saved lockfile"); + expect(first.exitCode).toBe(0); + expect(appEntry(await lockText(packageDir))).toContain(`"lib": "${before}"`); + + await writeAll(packageDir, files("1.0.1", after)); + const early = await bun(packageDir, "install", "--frozen-lockfile"); + + expect(early.stderr).toContain(frozenError); + expect(early.stderr).toContain(sectionNote("dependencies", "packages/app/package.json")); + expect(early.exitCode).toBe(1); + + const plain = await bun(packageDir, "install"); + const lock = await lockText(packageDir); + + expect(plain.stderr).toContain("Saved lockfile"); + expect(appEntry(lock)).toContain(`"lib": "${after}"`); + expect(lock).toContain('"version": "1.0.1"'); + expect(plain.exitCode).toBe(0); + + await rm(join(packageDir, "node_modules"), { recursive: true, force: true }); + const ci = await bun(packageDir, "ci"); + + expect(ci.stderr).not.toContain("error:"); + expect(ci.exitCode).toBe(0); + + const again = await bun(packageDir, "install"); + + expect(again.stderr).not.toContain("Saved lockfile"); + expect(await lockText(packageDir)).toBe(lock); + expect(again.exitCode).toBe(0); + }); +}); diff --git a/test/cli/install/frozen-lockfile-pruned.test.ts b/test/cli/install/frozen-lockfile-pruned.test.ts index 1f9185079daa..11ca7248e50f 100644 --- a/test/cli/install/frozen-lockfile-pruned.test.ts +++ b/test/cli/install/frozen-lockfile-pruned.test.ts @@ -529,7 +529,8 @@ describe.each(["hoisted", "isolated"] as Linker[])("linker: %s", linker => { expect(await lockText(packageDir)).toBe(pruned); }); - // Like trustedDependencies above, patchedDependencies is not part of the frozen comparison (docs/pm/cli/install.mdx). + // Like trustedDependencies above, a patchedDependencies list bun.lock never recorded is not compared (turbo prune before + // vercel/turborepo#11027 dropped the section). test.concurrent("patchedDependencies added after bun.lock was written still passes --frozen-lockfile", async () => { const { packageDir, full } = await verbatimScenario(linker, monorepo, survivors); expect(full).not.toContain('"patchedDependencies"'); @@ -550,7 +551,8 @@ describe.each(["hoisted", "isolated"] as Linker[])("linker: %s", linker => { expect(await lockText(packageDir)).toContain(patchedLockLine); }); - test.concurrent("patchedDependencies removed after bun.lock was written still passes --frozen-lockfile", async () => { + // A recorded list is compared: turbo prune keeps the entries of packages it keeps, so a difference is a package.json edit. + test.concurrent("patchedDependencies removed after bun.lock was written fails --frozen-lockfile", async () => { const { fullDir, full } = await fullInstall(linker, patchedMonorepo); expect(full).toContain(patchedLockLine); expect(await exists(join(dirname(installedPath(fullDir, linker, "a-dep", "1.0.1")), "patched.txt"))).toBeTrue(); @@ -558,13 +560,11 @@ describe.each(["hoisted", "isolated"] as Linker[])("linker: %s", linker => { await writeTree(packageDir, monorepo, survivors); await write(join(packageDir, "bun.lock"), full); - const { stderr } = await frozen(packageDir, linker, 0); + const { stderr } = await frozen(packageDir, linker, 1); - expect(stderr).not.toContain("patchedDependencies"); + expect(stderr).toContain("note: bun.lock does not match patchedDependencies in package.json"); expect(await lockText(packageDir)).toBe(full); - const aDep = installedPath(packageDir, linker, "a-dep", "1.0.1"); - expect(await file(aDep).json()).toMatchObject({ name: "a-dep", version: "1.0.1" }); - expect(await exists(join(dirname(aDep), "patched.txt"))).toBeFalse(); + expect(await exists(join(packageDir, "node_modules"))).toBeFalse(); }); test.concurrent("overrides added after bun.lock was written still fail --frozen-lockfile", async () => { @@ -1301,8 +1301,10 @@ describe("hoisted", () => { expect(await lockText(packageDir)).toBe(full); }); + // Without workspaces there is no pruned checkout, so a stripped trustedDependencies section is a frozen failure there + // (frozen-lockfile-outdated.test.ts). The difference here is a name bun.lock does not record because it is not installed. test.concurrent( - "single-package project: trustedDependencies stripped from bun.lock does not drop a peer-held package under --frozen-lockfile", + "single-package project: a trustedDependencies-only difference does not drop a peer-held package under --frozen-lockfile", async () => { const single: Tree = { root: { @@ -1315,7 +1317,7 @@ describe("hoisted", () => { const { full } = await fullInstall("hoisted", single); expect(full).toContain('"trustedDependencies"'); // The 8-space row is the root's declared dependency; the package entry stays, held only by optional-peer-deps' peer slot. - const pruned = full.replace(/\n "no-deps": "1\.0\.0",/, "").replace(trustedDependenciesSection, ""); + const pruned = full.replace(/\n "no-deps": "1\.0\.0",/, ""); expect(pruned).not.toBe(full); expect(pruned).toContain('"no-deps": ["no-deps@1.0.0"'); const { packageDir } = await registry.createTestDir({ bunfigOpts: { linker: "hoisted" } }); @@ -1324,7 +1326,7 @@ describe("hoisted", () => { JSON.stringify({ name: "single", dependencies: { "optional-peer-deps": "1.0.0" }, - trustedDependencies: ["optional-peer-deps"], + trustedDependencies: ["optional-peer-deps", "not-installed"], }), ); await write(join(packageDir, "bun.lock"), pruned); diff --git a/test/cli/install/migration/__snapshots__/migrate.test.ts.snap b/test/cli/install/migration/__snapshots__/migrate.test.ts.snap index ba6aeab1da8c..6b83d448d907 100644 --- a/test/cli/install/migration/__snapshots__/migrate.test.ts.snap +++ b/test/cli/install/migration/__snapshots__/migrate.test.ts.snap @@ -3571,7 +3571,7 @@ bun install --frozen-lockfile exit code: 0 exports[`package-lock.json migration fixes arborist fixtures edit-package-json--changed 1`] = ` "migrated lockfile from package-lock.json bun pm migrate exit code: 0 -bun install --frozen-lockfile exit code: 0 +bun install --frozen-lockfile exit code: 1 { "lockfileVersion": 2,