From 353b3b8b96d1b39a25b1288c659ed8b52d9b9d60 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 05:02:07 +0000 Subject: [PATCH 1/7] Start pnpm-override-confirms-vendored Refs #2382. Empty commit that opens the draft pull request; the fix follows. Assisted-by: Claude Code From 3e80766ca979fd54c1fe83a75525b06bcad07dfd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 05:42:43 +0000 Subject: [PATCH 2/7] Test that pnpm reads a vendored override Two CLI tests for #2382 that fail on main. They vendor the pnpm fixture through the built binary and take the override out of the file the project's pnpm reads it from: both files with no pin, the workspace file under pnpm 11 and 12, package.json under pnpm 9. Real pnpm 8.15.9 to 12.23.0 then refuses a frozen install with ERR_PNPM_LOCKFILE_CONFIG_MISMATCH, and a plain install puts the registry release back. On main `vendor --check` exits 0 and `vex` attests not_affected for each of those trees: the tests see (0, 1) where (1, 0) is right. Refs #2382. Assisted-by: Claude Code --- .../tests/vendor_pnpm_override_e2e.rs | 176 ++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs diff --git a/crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs b/crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs new file mode 100644 index 000000000..bbe000925 --- /dev/null +++ b/crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs @@ -0,0 +1,176 @@ +//! pnpm installs a lock only when the lock's `overrides:` equal the ones +//! its settings declare, and each pnpm major reads those from its own +//! file: package.json `pnpm.overrides` for pnpm 9 and older, either file +//! for pnpm 10, pnpm-workspace.yaml `overrides:` alone for pnpm 11 and +//! newer. With a vendored override declared where the project's pnpm does +//! not read it, a frozen install fails (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH`) +//! and a plain `pnpm install` puts the registry release back (#2382; +//! measured on pnpm 8.15.9, 9.15.9, 10.28.0, 11.29.0 and 12.23.0). +//! +//! `vendor --check` and `vex` read the vendored reference from the lock +//! alone, so both called such a package patched. Each case vendors the pnpm +//! project of `vendor_ecosystem_fixtures` (`alpha`, `beta`) through the +//! built binary and takes the override out of one place. + +#[path = "common/mod.rs"] +mod common; + +#[path = "vendor_ecosystem_fixtures/mod.rs"] +mod fx; + +use fx::Fixture; + +const WORKSPACE: &str = "pnpm-workspace.yaml"; +const MANIFEST: &str = "package.json"; + +/// The pnpm fixture, with `pin` as its `packageManager` when given. +fn project(pin: Option<&str>) -> Fixture { + let f = Fixture::new("pnpm"); + if let Some(pin) = pin { + let text = std::fs::read_to_string(f.root.join(MANIFEST)).unwrap(); + let pinned = text.replacen('{', &format!(r#"{{"packageManager":"pnpm@{pin}","#), 1); + std::fs::write(f.root.join(MANIFEST), pinned).unwrap(); + } + f +} + +/// `vendor --check`: the exit code and what it printed. +fn check(f: &Fixture) -> (i32, String) { + let (code, stdout, stderr) = f.run(&["vendor", "--check"], &[]); + (code, format!("{stdout}{stderr}")) +} + +/// `vex`: the number of `not_affected` statements and the warnings. +fn vex(f: &Fixture) -> (usize, String) { + let (_, stdout, stderr) = f.run(&["vex", "--product", "pkg:npm/app@1.0.0"], &[]); + let attested = stdout.matches("\"status\": \"not_affected\"").count(); + (attested, stderr) +} + +/// Whether `rel` declares a vendored override. +fn declares(f: &Fixture, rel: &str) -> bool { + std::fs::read_to_string(f.root.join(rel)).is_ok_and(|text| text.contains(".socket/vendor/npm/")) +} + +/// Take the vendored overrides out of package.json: its bytes before the +/// vendored run, which are `before`. +fn drop_manifest_override(f: &Fixture, before: &[u8]) { + std::fs::write(f.root.join(MANIFEST), before).unwrap(); +} + +/// The issue's case: the override is declared in no file. The lock still +/// names the artifact, so both verifiers passed. +#[test] +fn a_lock_whose_override_no_file_declares_is_not_verified() { + let f = project(None); + let before = std::fs::read(f.root.join(MANIFEST)).unwrap(); + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(declares(&f, MANIFEST) && declares(&f, WORKSPACE)); + assert_eq!((check(&f).0, vex(&f).0), (0, 1), "as vendored"); + + drop_manifest_override(&f, &before); + std::fs::remove_file(f.root.join(WORKSPACE)).unwrap(); + assert!(declares(&f, "pnpm-lock.yaml")); + let tree = f.tree(); + + let (code, said) = check(&f); + let (attested, warned) = vex(&f); + assert_eq!( + (code, attested), + (1, 0), + "(vendor --check exit code, not_affected statements)\n{said}\n{warned}" + ); + for (name, uuid) in [("alpha", "000000000001"), ("beta", "000000000002")] { + let line = said + .lines() + .find(|l| l.starts_with(&format!("pkg:npm/{name}@1.0.0: wiring incomplete: "))) + .unwrap_or_else(|| panic!("{name}: {said}")); + assert!( + line.contains(&format!("the override `{name}@1.0.0`")) + && line.contains(&format!("-{uuid}/{name}-1.0.0.tgz")) + && line.contains("neither package.json `pnpm.overrides` nor pnpm-workspace.yaml") + && line.contains("ERR_PNPM_LOCKFILE_CONFIG_MISMATCH") + && line.ends_with("Re-run `socket-patch vendor` to declare it again, and commit the files it changes"), + "{line}" + ); + assert!(!line.contains("no lockfile or config references"), "{line}"); + // `vex` folds the second package into the first one's warning. + assert!(warned.contains(&format!("{name}@1.0.0")), "{warned}"); + } + assert!( + warned.contains("patched_ref_invalid: pnpm-lock.yaml: the lock records the override") + && warned.contains("(vendor_unwired)"), + "{warned}" + ); + assert_eq!(f.tree(), tree, "the two read-only commands wrote nothing"); + + // The remedy the message names puts both declarations back. + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(declares(&f, MANIFEST) && declares(&f, WORKSPACE)); + assert_eq!((check(&f).0, vex(&f).0), (0, 1), "after the re-run"); +} + +/// The override is read where the project's pnpm reads it, so a file left +/// out of a commit (or a pnpm upgrade) is caught as soon as the checkout +/// says which pnpm it uses. +#[test] +fn the_override_counts_only_where_the_projects_pnpm_reads_it() { + // (the pnpm the project pins, the file the override is taken out of, + // whether pnpm still installs the lock). + for (pin, dropped, installs) in [ + // No pin: either file. + (None, MANIFEST, true), + (None, WORKSPACE, true), + // pnpm 10 reads either file. + (Some("10.28.0"), MANIFEST, true), + (Some("10.28.0"), WORKSPACE, true), + // pnpm 11 and newer read the workspace file alone. + (Some("11.29.0"), MANIFEST, true), + (Some("11.29.0"), WORKSPACE, false), + (Some("12.23.0"), WORKSPACE, false), + // pnpm 9 reads package.json alone, and a pinned pnpm 9 project with + // no workspace file gets none. + (Some("9.15.9"), MANIFEST, false), + ] { + let case = format!("pnpm {pin:?} without the override in {dropped}"); + let f = project(pin); + let before = std::fs::read(f.root.join(MANIFEST)).unwrap(); + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{case}: {stdout}\n{stderr}"); + assert_eq!( + declares(&f, WORKSPACE), + pin != Some("9.15.9"), + "{case}: what vendor wrote" + ); + assert_eq!((check(&f).0, vex(&f).0), (0, 1), "{case}: as vendored"); + match dropped { + MANIFEST => drop_manifest_override(&f, &before), + _ => std::fs::remove_file(f.root.join(WORKSPACE)).unwrap(), + } + + let (code, said) = check(&f); + let (attested, warned) = vex(&f); + let expected = if installs { (0, 1) } else { (1, 0) }; + assert_eq!((code, attested), expected, "{case}\n{said}\n{warned}"); + if installs { + continue; + } + let (file, major) = match dropped { + MANIFEST => ("package.json `pnpm.overrides`", "9"), + _ => ("pnpm-workspace.yaml `overrides`", &pin.unwrap()[..2]), + }; + assert!( + said.contains(&format!( + "{file}, the only place pnpm {major} reads overrides from" + )), + "{case}: {said}" + ); + // Re-running vendor declares it where that pnpm reads it. + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{case}: {stdout}\n{stderr}"); + assert!(declares(&f, dropped), "{case}: the re-run wrote {dropped}"); + assert_eq!((check(&f).0, vex(&f).0), (0, 1), "{case}: after the re-run"); + } +} From c409285aaf7e35b520267b21491f2d523455f807 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 05:42:43 +0000 Subject: [PATCH 3/7] Ask pnpm's settings for a vendored override pnpm installs a lock only when the lock's `overrides:` equal the ones its settings declare. With a vendored override missing from the file pnpm reads, a frozen install fails and a plain install takes the package from the registry again. Discovery read the vendored reference from the lock alone, so `vendor --check` verified such a tree and `vex` attested it. A vendored entry of the root lock is now a reference only while each override the lock records for its artifact is declared where the project's pnpm reads it: package.json for pnpm 9 and older, either file for pnpm 10 or when no file states the pnpm, the workspace file for pnpm 11 and newer. Those are the readings real pnpm 8.15.9, 9.15.9, 10.28.0, 11.29.0 and 12.23.0 showed. The pnpm is the one every other pnpm setting is read for. An undeclared entry is diagnosed patched_ref_invalid with the file that lacks the override and the remedy, and stays wiring to the prune GC. `vendor --check` fails it as "wiring incomplete" with that sentence, where it used to say no lockfile references the artifact. An entry the lock records no override for, and a Rush lock, are not asked. The lock-off reader and the new one share one read of the two override maps. docs/ecosystems.md states the rule. Fixes #2382. Assisted-by: Claude Code --- .../socket-patch-cli/src/commands/vendor.rs | 11 + .../socket-patch-core/src/formats/pnpm/mod.rs | 15 + .../src/utils/pnpm_workspace.rs | 45 +- .../socket-patch-core/src/vendor/pnpm_lock.rs | 9 +- .../socket-patch-core/src/vex/discover/mod.rs | 20 +- .../socket-patch-core/src/vex/discover/npm.rs | 619 +++++++++++++++++- docs/ecosystems.md | 18 + 7 files changed, 711 insertions(+), 26 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 1c2af7c4f..e67946da3 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -583,6 +583,9 @@ pub(crate) async fn dispatch_revert_one_opts( /// * for PyPI, a project file still names the artifact although nothing /// installs from it (a half-unwound uv pair, #1374): name it, and /// re-lock before re-vendoring or reverting; +/// * a pnpm lock wires the artifact through an override the project's +/// settings do not declare, so pnpm does not install that lock (#2382): +/// the extractor's own diagnostic, which names the file and the remedy; /// * otherwise a relock dropped the reference while the package stayed. async fn unwired_check_failure( discovery: &socket_patch_core::vex::discover::Discovery, @@ -619,6 +622,14 @@ async fn unwired_check_failure( registry release there (or remove that copy) to have it patched" ); } + // A pnpm lock still wires the artifact, but pnpm installs that lock + // only with the override its settings no longer declare: say which + // file, and the remedy the diagnostic ends with (#2382). + if entry.ecosystem == "npm" { + if let Some(diag) = discovery.vendored_withheld(&entry.uuid) { + return format!("wiring incomplete: {}", diag.detail); + } + } // Only the npm-family and Python extractors record every lock entry // (`resolved_elsewhere`), so only there does "no lock resolves it" // prove the dependency is gone rather than unreadable. diff --git a/crates/socket-patch-core/src/formats/pnpm/mod.rs b/crates/socket-patch-core/src/formats/pnpm/mod.rs index fe6f0a343..104e0e6b5 100644 --- a/crates/socket-patch-core/src/formats/pnpm/mod.rs +++ b/crates/socket-patch-core/src/formats/pnpm/mod.rs @@ -528,6 +528,21 @@ impl<'t> PnpmLock<'t> { .any(|p| pnpm_registry_key(p.key) == Some((name, version))) } + /// The `(key, value)` entries of the project documents' `overrides:` + /// sections: the overrides the lock was resolved with, which pnpm + /// compares with the ones its settings declare before it installs the + /// lock. The env lockfile document resolves pnpm's own dependencies and + /// is not read. Empty for a lock that records none. + pub(crate) fn overrides(&self) -> Vec<(String, String)> { + grammar::documents(self.text) + .into_iter() + .filter(|(_, kind)| *kind == PnpmDocument::Project) + .flat_map(|(span, _)| { + crate::vendor::pnpm_lock::override_section_entries(&self.text[span]) + }) + .collect() + } + /// Every packages entry whose flat resolution names a `tarball:`, in /// lock order. pub(crate) fn wired_refs(&self) -> impl Iterator> { diff --git a/crates/socket-patch-core/src/utils/pnpm_workspace.rs b/crates/socket-patch-core/src/utils/pnpm_workspace.rs index bc3322949..de9d613dc 100644 --- a/crates/socket-patch-core/src/utils/pnpm_workspace.rs +++ b/crates/socket-patch-core/src/utils/pnpm_workspace.rs @@ -983,11 +983,54 @@ fn lockfile_off(setting: impl Fn(&str, &str) -> Option) -> Option) -> Option { +pub(crate) async fn pnpm_major(view: &ProjectView<'_>) -> Option { let texts = read_texts(view, &[MODULES_YAML, "package.json", PNPM_LOCK]).await; pnpm_major_from(|rel| texts.get(rel).cloned()) } +/// Which override map a pnpm major reads: package.json `pnpm.overrides`, +/// pnpm-workspace.yaml `overrides:`, or either. pnpm installs a lock only +/// when the lock's `overrides:` equal the ones this map declares +/// (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH` on a frozen install otherwise, and +/// a plain install resolves afresh), so it is where a vendored override has +/// to be declared. +/// +/// Measured with a vendored `left-pad` on pnpm 8.15.9, 9.15.9, 10.28.0, +/// 11.29.0 and 12.23.0: pnpm 9 and older install the lock only with the +/// override in package.json, pnpm 10 with it in either file, pnpm 11 and +/// newer only with it in the workspace file. A major nothing states reads +/// either, the side that withholds no working wiring. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum PnpmOverrideSource { + /// pnpm 9 and older. + Manifest, + /// pnpm 10, or a major the project's files do not state. + Either, + /// pnpm 11 and newer. + Workspace, +} + +impl PnpmOverrideSource { + /// The map the pnpm of `major` ([`pnpm_major`]) reads. + pub(crate) fn of(major: Option) -> Self { + match major { + Some(major) if major >= 11 => PnpmOverrideSource::Workspace, + Some(major) if major <= 9 => PnpmOverrideSource::Manifest, + _ => PnpmOverrideSource::Either, + } + } + + /// Whether an override that package.json declares (`manifest`) or the + /// workspace file declares (`workspace`) is one this pnpm reads. + pub(crate) fn reads(self, manifest: bool, workspace: bool) -> bool { + match self { + PnpmOverrideSource::Manifest => manifest, + PnpmOverrideSource::Either => manifest || workspace, + PnpmOverrideSource::Workspace => workspace, + } + } +} + /// The pnpm major the project at `view` pins ([`pinned_pnpm_major`]). pub(crate) async fn pinned_pnpm_major_in(view: &ProjectView<'_>) -> Option { let texts = read_texts(view, &[MODULES_YAML, "package.json"]).await; diff --git a/crates/socket-patch-core/src/vendor/pnpm_lock.rs b/crates/socket-patch-core/src/vendor/pnpm_lock.rs index 7e0cd8461..cf72f1c34 100644 --- a/crates/socket-patch-core/src/vendor/pnpm_lock.rs +++ b/crates/socket-patch-core/src/vendor/pnpm_lock.rs @@ -2375,13 +2375,14 @@ fn ws_overrides_section(lines: &[String]) -> Option<(usize, usize, usize)> { Some((start, end, indent)) } -/// The `(key, value)` entries of a pnpm-workspace.yaml's block-style -/// `overrides:` section, values as YAML reads them ([`ws_override_value`]). +/// The `(key, value)` entries of the block-style top-level `overrides:` +/// section of a pnpm-workspace.yaml, or of one document of a pnpm lock +/// (the same shape), values as YAML reads them ([`ws_override_value`]). /// Empty for a missing or flow-style section: VEX discovery asks which /// packages the map routes, and a shape the surgery cannot read routes none /// it can vouch for. -pub(crate) fn workspace_override_entries(ws_text: &str) -> Vec<(String, String)> { - let lines = split_lines(ws_text); +pub(crate) fn override_section_entries(text: &str) -> Vec<(String, String)> { + let lines = split_lines(text); let Some((start, end, indent)) = ws_overrides_section(&lines) else { return Vec::new(); }; diff --git a/crates/socket-patch-core/src/vex/discover/mod.rs b/crates/socket-patch-core/src/vex/discover/mod.rs index 87d8b835d..2ceaa4763 100644 --- a/crates/socket-patch-core/src/vex/discover/mod.rs +++ b/crates/socket-patch-core/src/vex/discover/mod.rs @@ -985,7 +985,9 @@ pub struct Discovery { /// Vendored wiring an extractor rejects as [`DIAG_REF_INVALID`] although /// the next relock consumes it: cargo's `[patch]` at this copy while /// `Cargo.lock` builds another generation's copy (tagged for another - /// uuid, or untagged). Not attested, but still wiring: the prune GC must + /// uuid, or untagged), or although a rewire completes it: a pnpm lock + /// entry whose override the project's settings no longer declare. Not + /// attested, but still wiring: the prune GC must /// keep such an entry ([`Discovery::vendor_entry_in_use`]). Wiring /// dropped as [`DIAG_REF_UNATTRIBUTABLE`] needs no record here: the GC /// keeps it through the diagnostic itself. Sorted, deduped. @@ -1801,6 +1803,22 @@ impl Discovery { Some((shadowed, diag)) } + /// Why an extractor withheld the vendored wiring of patch `uuid` + /// although the files still wire it ([`Discovery::withheld`]): the + /// [`DIAG_REF_INVALID`] diagnostic of the withholding file that names + /// the patch. Lets a reader of a dead claim say what is missing instead + /// of saying nothing wires the artifact. + pub fn vendored_withheld(&self, uuid: &str) -> Option<&Diag> { + self.withheld + .iter() + .filter(|w| w.uuid == uuid && w.mode == WiringMode::Vendored) + .find_map(|w| { + self.diagnostics.iter().find(|d| { + d.code == DIAG_REF_INVALID && d.file == w.file && d.detail.contains(uuid) + }) + }) + } + /// Whether any lock discovery read resolves `purl` (any spelling) at /// all: wired to a Socket patch, contested, or from elsewhere /// ([`Discovery::resolved_elsewhere`]). diff --git a/crates/socket-patch-core/src/vex/discover/npm.rs b/crates/socket-patch-core/src/vex/discover/npm.rs index 2cb0d2432..ad56fae8c 100644 --- a/crates/socket-patch-core/src/vex/discover/npm.rs +++ b/crates/socket-patch-core/src/vex/discover/npm.rs @@ -61,7 +61,7 @@ use serde_json::Value; use super::{ npm_purl, npm_vendored_tarball_names, parse_json, vendor_ref, CopyTarget, DiscoverCtx, Discovery, LocateOpts, Located, PatchedRef, TreePart, UnattestedKind, UnwiredCopy, VendorRef, - DIAG_LOCKFILE_UNPARSEABLE, DIAG_REF_INVALID, DIAG_REF_UNATTRIBUTABLE, + WiringMode, DIAG_LOCKFILE_UNPARSEABLE, DIAG_REF_INVALID, DIAG_REF_UNATTRIBUTABLE, }; use crate::constants::npm_family::{NPM_LOCKS, PNPM_LOCK, PNPM_SHRINKWRAP_LEGACY}; use crate::formats::pnpm::plan::governing_pnpm_lock; @@ -72,6 +72,7 @@ use crate::formats::pnpm::{ use crate::formats::text::strip_bom; use crate::patch::redirect::NpmUserPatches; use crate::utils::digest::is_sri_pin; +use crate::utils::pnpm_workspace::{PnpmOverrideSource, PNPM_WORKSPACE}; use crate::vendor::lock_inventory::pnpm::{is_rush, rush_lock_rels}; use crate::vendor::lock_inventory::{ npm_lock_bundled_nodes, npm_lock_legacy_mirror_nodes, npm_lock_located_nodes, LockIntegrity, @@ -82,6 +83,9 @@ use crate::vendor::npm_origin::{ npm_shrinkwrapped_entries, NpmOverrides, }; +/// The manifest a pnpm project declares `pnpm.overrides` in. +const PNPM_MANIFEST: &str = "package.json"; + pub(crate) async fn extract(ctx: &DiscoverCtx<'_>, out: &mut Discovery) { let mut locks: Vec = Vec::new(); let mut twin_present = false; @@ -996,7 +1000,9 @@ fn unattest_git_branch_lock(file: &str, branch_locks: &[String], out: &mut Disco /// them. A vendored ref stands only while the override map pnpm reads /// without a lock routes its package to the same artifact /// ([`PnpmLockOff::routes`]); otherwise it is marked -/// [`UnattestedKind::LockNotRead`]. +/// [`UnattestedKind::LockNotRead`]. With the lock on, a vendored ref of +/// the root lock stands only while the project's settings declare the +/// override the lock records for it ([`confirm_pnpm_overrides`]). async fn extract_pnpm_lock( ctx: &DiscoverCtx<'_>, file: &str, @@ -1040,8 +1046,133 @@ async fn extract_pnpm_lock( let tree = PnpmTree::of(file, document); extract_pnpm_document(ctx, &tree, &lock, document, disabled, out).await; } - if let Some(off) = off { - out.unattest_vendored_not_read(file, &off.unrouted(), |r| off.routes(r)); + match off { + Some(off) => out.unattest_vendored_not_read(file, &off.unrouted(), |r| off.routes(r)), + None => confirm_pnpm_overrides(ctx, file, &lock, out).await, + } +} + +/// Drop each vendored ref of the pnpm lock `file` whose override the lock +/// records while the project's settings do not declare it (#2382). +/// +/// pnpm installs a lock only when the lock's `overrides:` equal the ones +/// its settings declare: otherwise a frozen install stops with +/// `ERR_PNPM_LOCKFILE_CONFIG_MISMATCH`, and a plain `pnpm install` resolves +/// again, takes the package from the registry and rewrites the lock +/// without the vendored entry. Which file holds those settings depends on +/// the pnpm major ([`PnpmOverrideSource`]). So an entry whose override is +/// declared nowhere pnpm reads is the yarn berry orphan: it is diagnosed +/// ([`DIAG_REF_INVALID`], with the remedy) and is no ref. The lock still +/// wires the artifact and a rewire restores the declaration, so the entry +/// is still wiring to the prune GC ([`Discovery::withheld`]). +/// +/// Only an override the lock itself records is asked for: an entry wired +/// with none (a `file:` dependency of the project's own, a hand-pointed +/// tarball) has nothing for pnpm to compare. A Rush lock is installed with +/// Rush's own settings, and a member's lock holds no vendored ref. +async fn confirm_pnpm_overrides( + ctx: &DiscoverCtx<'_>, + file: &str, + lock: &PnpmLock<'_>, + out: &mut Discovery, +) { + if crate::vendor::pnpm_lock::rush::is_lock_rel(file) { + return; + } + // `(override key, artifact)` of the lock's own `overrides:` section. + let recorded: Vec<(String, VendorRef)> = lock + .overrides() + .into_iter() + .filter_map(|(key, value)| Some((key, vendor_ref(&value)?))) + .collect(); + let recorded_for = |r: &PatchedRef| -> Vec<&(String, VendorRef)> { + let governed = r.mode == WiringMode::Vendored + && r.source_file == Path::new(file) + && r.part == TreePart::File; + recorded + .iter() + .filter(|(_, v)| governed && Some(v.artifact_rel.as_str()) == r.artifact_rel.as_deref()) + .collect() + }; + if out.refs.iter().all(|r| recorded_for(r).is_empty()) { + return; + } + let maps = PnpmOverrideMaps::read(ctx).await; + let major = crate::utils::pnpm_workspace::pnpm_major(&ctx.view).await; + let source = PnpmOverrideSource::of(major); + let undeclared = |r: &PatchedRef| -> Vec<&(String, VendorRef)> { + recorded_for(r) + .into_iter() + .filter(|(key, v)| !maps.declare(source, key, &v.artifact_rel)) + .collect() + }; + let (kept, dropped): (Vec, Vec) = std::mem::take(&mut out.refs) + .into_iter() + .partition(|r| undeclared(r).is_empty()); + out.refs = kept; + for r in dropped { + let missing = undeclared(&r); + let keys: Vec = missing.iter().map(|(key, _)| format!("`{key}`")).collect(); + let artifact = r.artifact_rel.as_deref().unwrap_or_default(); + // The pnpm whose reading decides, as `pnpm_major` finds it. + let pnpm = major.map_or_else(String::new, |major| { + format!( + ", the only place pnpm {major} reads overrides from (the project's pnpm by \ + node_modules/.modules.yaml, `packageManager` or the lock's format)," + ) + }); + let undeclared_in = match source { + PnpmOverrideSource::Manifest => { + format!("{PNPM_MANIFEST} `pnpm.overrides`{pnpm} does not declare it") + } + PnpmOverrideSource::Workspace => { + format!("{PNPM_WORKSPACE} `overrides`{pnpm} does not declare it") + } + PnpmOverrideSource::Either => format!( + "neither {PNPM_MANIFEST} `pnpm.overrides` nor {PNPM_WORKSPACE} `overrides` \ + declares it" + ), + }; + // `vendor` writes no `pnpm.overrides` table into a package.json + // that has none while the workspace file carries an override the + // lock records, whatever pnpm reads (`workspace_overrides_govern`). + let in_workspace = missing + .iter() + .all(|(key, v)| maps.declare(PnpmOverrideSource::Workspace, key, &v.artifact_rel)); + let by_hand = + source == PnpmOverrideSource::Manifest && in_workspace && !maps.manifest_table; + let remedy = if by_hand { + let entries: Vec = missing + .iter() + .map(|(key, v)| format!("`\"{key}\": \"file:{}\"`", v.artifact_rel)) + .collect(); + format!( + "Add {} to {PNPM_MANIFEST} `pnpm.overrides`: `socket-patch vendor` leaves it \ + out while {PNPM_WORKSPACE} declares the override", + entries.join(", ") + ) + } else { + "Re-run `socket-patch vendor` to declare it again, and commit the files it changes" + .to_string() + }; + out.diag( + DIAG_REF_INVALID, + file, + format!( + "{file}: the lock records the override {} for {} ({artifact}), but \ + {undeclared_in}. pnpm installs a lock only when its `overrides:` equal the \ + declared ones: a frozen install fails (ERR_PNPM_LOCKFILE_CONFIG_MISMATCH) and a \ + plain `pnpm install` takes the package from the registry again; not counted. \ + {remedy}", + keys.join(", "), + r.purl, + ), + ); + out.withheld.push(super::Recognized { + uuid: r.uuid, + mode: WiringMode::Vendored, + file: PathBuf::from(file), + }); } } @@ -1057,10 +1188,7 @@ async fn extract_pnpm_lock( /// `pnpm.overrides`). struct PnpmLockOff { source: String, - /// `(override key, artifact)` of package.json `pnpm.overrides`. - manifest: Vec<(String, VendorRef)>, - /// `(override key, artifact)` of pnpm-workspace.yaml `overrides:`. - workspace: Vec<(String, VendorRef)>, + maps: PnpmOverrideMaps, /// The lock is off for pnpm 11+, which reads the workspace map alone. needs_workspace: bool, /// The lock is off for pnpm 10 and older, which read `pnpm.overrides`. @@ -1069,36 +1197,70 @@ struct PnpmLockOff { pnpm10: bool, } -impl PnpmLockOff { - async fn read(ctx: &DiscoverCtx<'_>, source: String) -> Self { +/// The vendored artifacts the two override maps of a pnpm project route +/// packages to: the declarations pnpm resolves with, with or without a +/// lock. +struct PnpmOverrideMaps { + /// `(override key, artifact)` of package.json `pnpm.overrides`. + manifest: Vec<(String, VendorRef)>, + /// Whether package.json has a `pnpm.overrides` table at all. + manifest_table: bool, + /// `(override key, artifact)` of pnpm-workspace.yaml `overrides:`. + workspace: Vec<(String, VendorRef)>, +} + +impl PnpmOverrideMaps { + async fn read(ctx: &DiscoverCtx<'_>) -> Self { let vendored = |entries: Vec<(String, String)>| -> Vec<(String, VendorRef)> { entries .into_iter() .filter_map(|(key, value)| Some((key, vendor_ref(&value)?))) .collect() }; - let manifest = ctx - .read_advisory_text("package.json") + let table = ctx + .read_advisory_text(PNPM_MANIFEST) .await .and_then(|text| serde_json::from_str::(strip_bom(&text)).ok()) - .and_then(|doc| doc.pointer("/pnpm/overrides")?.as_object().cloned()) + .and_then(|doc| doc.pointer("/pnpm/overrides").cloned()); + let manifest = table + .as_ref() + .and_then(Value::as_object) .map(|map| { - map.into_iter() - .filter_map(|(key, value)| Some((key, value.as_str()?.to_string()))) + map.iter() + .filter_map(|(key, value)| Some((key.clone(), value.as_str()?.to_string()))) .collect() }) .unwrap_or_default(); let workspace = ctx - .read_advisory_text(crate::utils::pnpm_workspace::PNPM_WORKSPACE) + .read_advisory_text(PNPM_WORKSPACE) .await - .map(|text| crate::vendor::pnpm_lock::workspace_override_entries(&text)) + .map(|text| crate::vendor::pnpm_lock::override_section_entries(&text)) .unwrap_or_default(); + PnpmOverrideMaps { + manifest: vendored(manifest), + manifest_table: table.is_some(), + workspace: vendored(workspace), + } + } + + /// Whether the map a pnpm of `source` reads declares the override + /// `key` onto the artifact at `artifact_rel`, as a lock records it. + fn declare(&self, source: PnpmOverrideSource, key: &str, artifact_rel: &str) -> bool { + let declared = |map: &[(String, VendorRef)]| { + map.iter() + .any(|(k, artifact)| k == key && artifact.artifact_rel == artifact_rel) + }; + source.reads(declared(&self.manifest), declared(&self.workspace)) + } +} + +impl PnpmLockOff { + async fn read(ctx: &DiscoverCtx<'_>, source: String) -> Self { let (needs_workspace, needs_manifest, major) = crate::utils::pnpm_workspace::lockfile_off_sources(&ctx.view).await; PnpmLockOff { source, - manifest: vendored(manifest), - workspace: vendored(workspace), + maps: PnpmOverrideMaps::read(ctx).await, needs_workspace, needs_manifest, pnpm10: major == Some(10), @@ -1121,7 +1283,7 @@ impl PnpmLockOff { && Some(artifact.artifact_rel.as_str()) == r.artifact_rel.as_deref() }) }; - let (manifest, workspace) = (routed(&self.manifest), routed(&self.workspace)); + let (manifest, workspace) = (routed(&self.maps.manifest), routed(&self.maps.workspace)); (!self.needs_workspace || workspace) && (!self.needs_manifest || manifest || (self.pnpm10 && workspace)) } @@ -4580,6 +4742,412 @@ mod tests { assert!(attested(&run(&p).await), "pnpm 10, workspace override"); } + /// The vendored lock `vendor` writes for `left-pad@1.3.0` under + /// [`UUID_B`]: the override it records, the importer and the rekeyed + /// entry. `head` goes ahead of it (an env lockfile document). + fn pnpm_vendored_lock(head: &str) -> String { + let rel = format!(".socket/vendor/npm/{UUID_B}/left-pad-1.3.0.tgz"); + format!( + "{head}lockfileVersion: '9.0'\n\noverrides:\n left-pad@1.3.0: file:{rel}\n\n\ + importers:\n\n .:\n dependencies:\n left-pad:\n \ + specifier: file:{rel}\n version: file:{rel}\n\npackages:\n\n \ + left-pad@file:{rel}:\n resolution: {{integrity: {SRI}, tarball: file:{rel}}}\n \ + version: 1.3.0\n\nsnapshots:\n\n left-pad@file:{rel}: {{}}\n" + ) + } + + /// REGRESSION (#2382): pnpm installs a lock only when the lock's + /// `overrides:` equal the ones its settings declare, and each major + /// reads them from its own file. Measured with a vendored `left-pad` + /// on pnpm 8.15.9, 9.15.9, 10.28.0, 11.29.0 and 12.23.0: with the + /// override declared where that pnpm does not read it, a frozen install + /// stops with `ERR_PNPM_LOCKFILE_CONFIG_MISMATCH` and a plain one + /// installs the registry release and rewrites the lock. Such an entry + /// was a ref, so `vex` attested it and `vendor --check` verified it. + #[tokio::test] + async fn pnpm_vendored_ref_needs_its_recorded_override_declared() { + let rel = format!(".socket/vendor/npm/{UUID_B}/left-pad-1.3.0.tgz"); + const PURL: &str = "pkg:npm/left-pad@1.3.0"; + let project = |pin: Option<&str>, manifest: bool, workspace: bool| { + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + let pin = pin.map_or(String::new(), |v| { + format!(r#""packageManager":"pnpm@{v}","#) + }); + let overrides = match manifest { + true => format!(r#","pnpm":{{"overrides":{{"left-pad@1.3.0":"file:{rel}"}}}}"#), + false => String::new(), + }; + p.write( + "package.json", + format!( + r#"{{"name":"app",{pin}"dependencies":{{"left-pad":"1.3.0"}}{overrides}}}"# + ), + ); + if workspace { + p.write( + "pnpm-workspace.yaml", + format!("packages:\n - '.'\noverrides:\n left-pad@1.3.0: file:{rel}\n"), + ); + } + p + }; + // (the pnpm the project pins, package.json declares, the workspace + // file declares, pnpm installs the lock). + for (pin, manifest, workspace, installs) in [ + // No file states the pnpm: either map. + (None, false, false, false), + (None, true, false, true), + (None, false, true, true), + (None, true, true, true), + // pnpm 9 and older: package.json alone. + (Some("8.15.9"), true, false, true), + (Some("8.15.9"), false, true, false), + (Some("9.15.9"), true, false, true), + (Some("9.15.9"), true, true, true), + (Some("9.15.9"), false, true, false), + (Some("9.15.9"), false, false, false), + // pnpm 10: either map. + (Some("10.28.0"), true, false, true), + (Some("10.28.0"), false, true, true), + (Some("10.28.0"), false, false, false), + // pnpm 11 and newer: the workspace file alone. + (Some("11.29.0"), false, true, true), + (Some("11.29.0"), true, true, true), + (Some("11.29.0"), true, false, false), + (Some("12.23.0"), false, true, true), + (Some("12.23.0"), true, false, false), + (Some("12.23.0"), false, false, false), + ] { + let case = format!("pnpm {pin:?}, package.json {manifest}, workspace {workspace}"); + let out = run(&project(pin, manifest, workspace)).await; + let invalid: Vec<&str> = out + .diagnostics + .iter() + .filter(|d| d.code == DIAG_REF_INVALID) + .map(|d| d.detail.as_str()) + .collect(); + if installs { + assert_refs(&out, &[(PURL, UUID_B, WiringMode::Vendored)]); + assert!( + invalid.is_empty() && out.withheld.is_empty(), + "{case}: {invalid:#?}" + ); + continue; + } + assert_refs(&out, &[]); + assert!( + out.shadowed.is_empty() && out.unattested.is_empty(), + "{case}" + ); + // Still wiring: the prune GC keeps the ledger entry, and the + // reason names the patch, the file pnpm reads and the remedy. + assert_eq!(out.withheld.len(), 1, "{case}"); + assert_eq!(out.withheld[0].uuid, UUID_B, "{case}"); + let [detail] = invalid.as_slice() else { + panic!("{case}: {invalid:#?}"); + }; + assert_eq!( + out.vendored_withheld(UUID_B).map(|d| d.detail.as_str()), + Some(*detail) + ); + assert!( + detail.contains(PURL) + && detail.contains(&rel) + && detail.contains("`left-pad@1.3.0`") + && detail.contains("ERR_PNPM_LOCKFILE_CONFIG_MISMATCH"), + "{case}: {detail}" + ); + let major = pin.and_then(|v| v.split('.').next()); + let (place, other) = match major { + Some("8" | "9") => ("package.json `pnpm.overrides`, the only place", "neither"), + Some("11" | "12") => ("pnpm-workspace.yaml `overrides`, the only place", "neither"), + _ => ( + "neither package.json `pnpm.overrides` nor", + "the only place", + ), + }; + assert!( + detail.contains(place) && !detail.contains(other), + "{case}: {detail}" + ); + // `vendor` writes no `pnpm.overrides` table while the workspace + // file carries the override, so there the remedy is the entry. + let by_hand = matches!(major, Some("8" | "9")) && workspace; + let remedy = match by_hand { + true => format!(r#"Add `"left-pad@1.3.0": "file:{rel}"` to package.json"#), + false => "Re-run `socket-patch vendor`".to_string(), + }; + assert!(detail.contains(&remedy), "{case}: {detail}"); + assert_eq!(by_hand, !detail.contains("Re-run"), "{case}: {detail}"); + } + } + + /// A lock entry whose override is undeclared is dead to the liveness + /// gate (`vendor --check`, `vex`) but still wiring to the prune GC, + /// whose mistake would be a revert: re-running `vendor` completes it + /// (#2382). + #[tokio::test] + async fn pnpm_undeclared_override_is_dead_but_kept_by_the_prune_gc() { + let rel = format!(".socket/vendor/npm/{UUID_B}/left-pad-1.3.0.tgz"); + let entry: crate::vendor::state::VendorEntry = serde_json::from_value(serde_json::json!({ + "ecosystem": "npm", + "basePurl": "pkg:npm/left-pad@1.3.0", + "uuid": UUID_B, + "artifact": { "path": rel, "sha256": "" }, + "wiring": [{ "file": "pnpm-lock.yaml", "kind": "lock", "action": "added" }], + })) + .unwrap(); + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("package.json", r#"{"name":"app"}"#); + let dead = p.discover().await; + assert!(!dead.vendor_entry_live(p.root(), &entry).await); + assert_eq!( + dead.vendor_entry_liveness(p.root(), &entry).await, + Some(false) + ); + assert_eq!(dead.vendor_entry_in_use(p.root(), &entry).await, Some(true)); + + p.write( + "package.json", + format!(r#"{{"name":"app","pnpm":{{"overrides":{{"left-pad@1.3.0":"file:{rel}"}}}}}}"#), + ); + let live = p.discover().await; + assert!(live.vendor_entry_live(p.root(), &entry).await); + assert_eq!(live.vendor_entry_in_use(p.root(), &entry).await, Some(true)); + } + + /// The pnpm whose reading decides is the one every pnpm setting is read + /// for: the install record first, then the `packageManager` pin, then + /// what the lock's own format implies (#2382). + #[tokio::test] + async fn pnpm_recorded_override_is_read_for_the_projects_pnpm() { + let rel = format!(".socket/vendor/npm/{UUID_B}/left-pad-1.3.0.tgz"); + const PURL: &str = "pkg:npm/left-pad@1.3.0"; + let wired = [(PURL, UUID_B, WiringMode::Vendored)]; + let manifest = |pin: &str| { + format!( + r#"{{"name":"app",{pin}"dependencies":{{"left-pad":"1.3.0"}},"pnpm":{{"overrides":{{"left-pad@1.3.0":"file:{rel}"}}}}}}"# + ) + }; + let workspace = format!("packages:\n - '.'\noverrides:\n left-pad@1.3.0: file:{rel}\n"); + + // The install record outranks the pin: pnpm 11 installed the tree. + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write( + "package.json", + manifest(r#""packageManager":"pnpm@9.15.9","#), + ); + assert_refs(&run(&p).await, &wired); + p.write( + "node_modules/.modules.yaml", + r#"{"layoutVersion":5,"packageManager":"pnpm@11.29.0"}"#, + ); + let out = run(&p).await; + assert_refs(&out, &[]); + assert!( + out.diagnostics[0].detail.contains("pnpm 11 reads"), + "{:#?}", + out.diagnostics + ); + p.write("pnpm-workspace.yaml", &workspace); + assert_refs(&run(&p).await, &wired); + + // A pre-10 install record is a YAML scalar. + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("package.json", r#"{"name":"app"}"#); + p.write("pnpm-workspace.yaml", &workspace); + assert_refs(&run(&p).await, &wired); + p.write( + "node_modules/.modules.yaml", + "layoutVersion: 5\npackageManager: pnpm@9.15.9\n", + ); + assert_refs(&run(&p).await, &[]); + + // No pin: an env lockfile document is pnpm 11's. + let env = + "---\nlockfileVersion: '9.0'\n\nimporters:\n\n .:\n configDependencies:\n \ + cfg:\n specifier: 1.0.0\n version: 1.0.0\n\npackages:\n\n \ + cfg@1.0.0:\n resolution: {integrity: sha512-CFG==}\n\n---\n"; + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock(env)); + p.write("package.json", manifest("")); + assert_refs(&run(&p).await, &[]); + p.write("pnpm-workspace.yaml", &workspace); + assert_refs(&run(&p).await, &wired); + + // No pin: a lockfileVersion 6 lock is pnpm 8's, which reads + // package.json alone (the legacy backend writes no workspace file). + let legacy = format!( + "lockfileVersion: '6.0'\n\noverrides:\n left-pad@1.3.0: file:{rel}\n\ndependencies:\n \ + left-pad:\n specifier: file:/abs/app/{rel}\n version: file:{rel}\n\npackages:\n\n \ + file:{rel}:\n resolution: {{integrity: {SRI}, tarball: file:{rel}}}\n \ + name: left-pad\n version: 1.3.0\n dev: false\n" + ); + let p = Project::new(); + p.write("pnpm-lock.yaml", &legacy); + p.write("package.json", manifest("")); + assert_refs(&run(&p).await, &wired); + p.write("package.json", r#"{"name":"app"}"#); + p.write("pnpm-workspace.yaml", &workspace); + let out = run(&p).await; + assert_refs(&out, &[]); + assert!( + out.diagnostics[0].detail.contains("pnpm 8 reads"), + "{:#?}", + out.diagnostics + ); + } + + /// Only what pnpm compares is asked for (#2382): the override keys the + /// lock records, spelled as the lock spells them. An entry wired with no + /// recorded override has nothing to confirm, and a Rush lock is + /// installed with Rush's own settings. + #[tokio::test] + async fn pnpm_recorded_override_is_compared_as_pnpm_compares_it() { + let rel = format!(".socket/vendor/npm/{UUID_B}/left-pad-1.3.0.tgz"); + const PURL: &str = "pkg:npm/left-pad@1.3.0"; + let wired = [(PURL, UUID_B, WiringMode::Vendored)]; + let manifest = |key: &str, value: &str| { + format!(r#"{{"name":"app","pnpm":{{"overrides":{{"{key}":"{value}"}}}}}}"#) + }; + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + // Another key, another artifact, a registry version: not the + // lock's override. + for (key, value) in [ + ("left-pad", format!("file:{rel}")), + ("left-pad@1", format!("file:{rel}")), + ( + "left-pad@1.3.0", + format!("file:.socket/vendor/npm/{UUID_A}/left-pad-1.3.0.tgz"), + ), + ("left-pad@1.3.0", "1.3.0".to_string()), + ("right-pad@1.3.0", format!("file:{rel}")), + ] { + p.write("package.json", manifest(key, &value)); + assert_refs(&run(&p).await, &[]); + } + p.write( + "package.json", + manifest("left-pad@1.3.0", &format!("file:{rel}")), + ); + assert_refs(&run(&p).await, &wired); + // A BOM, and a quoted key in the workspace file, read as pnpm reads + // them. + p.write( + "package.json", + format!( + "\u{feff}{}", + manifest("left-pad@1.3.0", &format!("file:{rel}")) + ), + ); + assert_refs(&run(&p).await, &wired); + p.write("package.json", r#"{"name":"app"}"#); + p.write( + "pnpm-workspace.yaml", + format!( + "packages:\n - '.'\noverrides:\n 'left-pad@1.3.0': \"file:{rel}\" # socket\n" + ), + ); + assert_refs(&run(&p).await, &wired); + // A flow mapping is a shape the reader cannot vouch for. + p.write( + "pnpm-workspace.yaml", + format!("packages: ['.']\noverrides: {{'left-pad@1.3.0': 'file:{rel}'}}\n"), + ); + assert_refs(&run(&p).await, &[]); + + // pnpm 9, the override in the workspace file alone: `vendor` adds + // it to a `pnpm.overrides` table that exists, so re-running is the + // remedy there; with no table the entry has to be added by hand. + for (table, by_hand) in [ + ("", true), + (r#","pnpm":{"overrides":{"ms@2.0.0":"2.1.3"}}"#, false), + ] { + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write( + "package.json", + format!(r#"{{"name":"app","packageManager":"pnpm@9.15.9"{table}}}"#), + ); + p.write( + "pnpm-workspace.yaml", + format!("packages:\n - '.'\noverrides:\n left-pad@1.3.0: file:{rel}\n"), + ); + let out = run(&p).await; + assert_refs(&out, &[]); + let detail = &out.diagnostics[0].detail; + assert_eq!( + detail.contains("Add `\"left-pad@1.3.0\""), + by_hand, + "{detail}" + ); + assert_eq!( + detail.contains("Re-run `socket-patch vendor`"), + !by_hand, + "{detail}" + ); + } + + // A CRLF checkout and a BOM read like their plain twins: the + // recorded override is still found, and still has to be declared. + for text in [ + pnpm_vendored_lock("").replace('\n', "\r\n"), + format!("\u{feff}{}", pnpm_vendored_lock("")), + ] { + let p = Project::new(); + p.write("pnpm-lock.yaml", &text); + p.write("package.json", r#"{"name":"app"}"#); + assert_refs(&run(&p).await, &[]); + p.write( + "pnpm-workspace.yaml", + format!("packages:\r\n - '.'\r\noverrides:\r\n left-pad@1.3.0: file:{rel}\r\n"), + ); + assert_refs(&run(&p).await, &wired); + } + + // The lock records no override for the artifact (a `file:` + // dependency of the project's own): pnpm compares nothing. + let unrecorded = pnpm_vendored_lock("") + .replace(&format!("overrides:\n left-pad@1.3.0: file:{rel}\n\n"), ""); + let p = Project::new(); + p.write("pnpm-lock.yaml", &unrecorded); + p.write( + "package.json", + r#"{"name":"app","packageManager":"pnpm@11.29.0"}"#, + ); + let out = run(&p).await; + assert_refs(&out, &wired); + assert!(out.diagnostics.is_empty(), "{:#?}", out.diagnostics); + // An override for another package does not ask for this one's. + let other = unrecorded.replace("importers:", "overrides:\n ms@2.0.0: 2.1.3\n\nimporters:"); + p.write("pnpm-lock.yaml", &other); + assert_refs(&run(&p).await, &wired); + + // Two keys for one artifact: each must be declared. + let two = pnpm_vendored_lock("").replace( + &format!(" left-pad@1.3.0: file:{rel}\n"), + &format!(" left-pad: file:{rel}\n left-pad@1.3.0: file:{rel}\n"), + ); + let p = Project::new(); + p.write("pnpm-lock.yaml", &two); + p.write( + "package.json", + manifest("left-pad@1.3.0", &format!("file:{rel}")), + ); + let out = run(&p).await; + assert_refs(&out, &[]); + let detail = &out.diagnostics[0].detail; + assert!( + detail.contains("the override `left-pad` for") && !detail.contains("`left-pad@1.3.0`"), + "{detail}" + ); + } + /// npm's `package-lock=false` (or its `shrinkwrap=false` alias) in the /// project `.npmrc` makes `npm install` ignore both npm locks and /// resolve from the registry, while `npm ci` still installs from them @@ -5275,6 +5843,15 @@ packages: dev: false "; + /// The package.json a vendored golden's project carries: the override + /// the backend writes beside the lock, without which pnpm does not + /// install that lock (#2382). + fn golden_manifest(uuid: &str) -> String { + format!( + r#"{{"name":"app","pnpm":{{"overrides":{{"left-pad@1.3.0":"file:.socket/vendor/npm/{uuid}/left-pad-1.3.0.tgz"}}}}}}"# + ) + } + /// Every vendored golden (v9 single + workspace, v5.4 direct + /// transitive-only, v6.0), LF and CRLF (a Windows autocrlf checkout), /// yields exactly the vendored left-pad with its artifact path and the @@ -5302,6 +5879,7 @@ packages: text = text.replace('\n', "\r\n"); } p.write("pnpm-lock.yaml", &text); + p.write("package.json", golden_manifest(uuid)); let out = run(&p).await; assert_refs( &out, @@ -5500,6 +6078,7 @@ packages: async fn pnpm_and_npm_locks_are_both_discovered() { let p = Project::new(); p.write("pnpm-lock.yaml", P1_AFTER_LOCK); + p.write("package.json", golden_manifest(V_UUID)); let url = hosted_url("npm", "ms", "2.1.3", UUID_A, "ms-2.1.3.tgz"); p.write( "package-lock.json", diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 843aa0cc3..f2a24c571 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -238,6 +238,24 @@ Each Legacy format has an upgrade path and an undo path. Both work in v5: which pnpm applies through `overrides` without a lock; `vex` attests such a vendored pin only while the override map that pnpm reads still routes the package to its artifact, and omits it otherwise (`vex_lock_not_read`). + **A vendored override has to stay declared.** pnpm installs a lock only + when the lock's `overrides:` equal the ones its settings declare: with a + vendored override missing from the file pnpm reads, a frozen install fails + (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH`) and a plain `pnpm install` takes the + package from the registry again. pnpm 9 and older read `pnpm.overrides` in + `package.json`, pnpm 10 reads either file, pnpm 11 and newer read + `overrides:` in `pnpm-workspace.yaml` alone; the pnpm is the one + `node_modules/.modules.yaml` records, else the `packageManager` pin, else + what the lock's format implies, and when none says, either file counts. + So a `pnpm-workspace.yaml` left out of the commit, a `package.json` put + back by a merge, or a move from pnpm 9 to 11 leaves the lock wired and + the patch uninstallable. `vendor --check` then fails the package (`wiring + incomplete`, naming the file) and `vex` omits it (`patched_ref_invalid`, + `vendor_unwired`). Re-running `socket-patch vendor` declares the override + again; on pnpm 9 and older it leaves `package.json` alone while + `pnpm-workspace.yaml` already carries the override, and the message then + gives the entry to add. A Rush lock, and a lock entry that records no + override, are not checked this way. **One mode for a package and its dependency.** pnpm 12.23 and newer refuse a lock in which a package fetched from a hosted patch depends on a local file (`ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED`), on every install, frozen or From e6a04c93fbd6d4e3f12ac628461eee514b0d2a34 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 06:14:30 +0000 Subject: [PATCH 4/7] Read overrides as each pnpm release does A review of the last commit, run against real pnpm, showed trees it still verified although pnpm does not install them, and messages that were wrong: - pnpm 10.2.0, 10.4.1 and 10.5.0 read package.json alone; the workspace file is read from 10.5.1 on. The rule went by major and let every pnpm 10 read either file. - pnpm 10.28.0 reads a `pnpm.overrides` table of package.json in place of the workspace file's, so a table without the vendored entry hides the workspace declaration. - The install record outranked the committed pin, so a stale node_modules failed a tree a fresh checkout verified. The rule now lives beside the other pnpm pin readers, at release precision. A pin counts when every release it admits reads the same place; pins that disagree leave either file, as no pin does. A pre-9 lock and an env lockfile document still say which pnpm wrote them. A declaration the reader cannot follow (an inline `overrides:` mapping, a package.json that is not JSON) may hold the override, so the reference stands there as it did on main. The by-hand remedy is given only for a version 9 lock, where `vendor` skips package.json; the legacy backend always writes it. `vendor --check` finds its reason by the override wording, not by the first diagnostic that names the patch. Refs #2382. Assisted-by: Claude Code --- .../socket-patch-cli/src/commands/vendor.rs | 6 +- .../tests/vendor_pnpm_override_e2e.rs | 85 ++- .../socket-patch-core/src/formats/pnpm/mod.rs | 4 +- .../src/formats/pnpm/version.rs | 94 +++- .../src/utils/pnpm_workspace.rs | 45 +- .../socket-patch-core/src/vendor/pnpm_lock.rs | 25 +- .../socket-patch-core/src/vex/discover/mod.rs | 18 +- .../socket-patch-core/src/vex/discover/npm.rs | 500 +++++++++++++----- docs/ecosystems.md | 26 +- 9 files changed, 580 insertions(+), 223 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index e67946da3..d2bfbddbe 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -625,10 +625,8 @@ async fn unwired_check_failure( // A pnpm lock still wires the artifact, but pnpm installs that lock // only with the override its settings no longer declare: say which // file, and the remedy the diagnostic ends with (#2382). - if entry.ecosystem == "npm" { - if let Some(diag) = discovery.vendored_withheld(&entry.uuid) { - return format!("wiring incomplete: {}", diag.detail); - } + if let Some(diag) = discovery.pnpm_override_undeclared(&entry.uuid) { + return format!("wiring incomplete: {}", diag.detail); } // Only the npm-family and Python extractors record every lock entry // (`resolved_elsewhere`), so only there does "no lock resolves it" diff --git a/crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs b/crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs index bbe000925..768718ced 100644 --- a/crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs +++ b/crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs @@ -1,11 +1,12 @@ //! pnpm installs a lock only when the lock's `overrides:` equal the ones -//! its settings declare, and each pnpm major reads those from its own -//! file: package.json `pnpm.overrides` for pnpm 9 and older, either file -//! for pnpm 10, pnpm-workspace.yaml `overrides:` alone for pnpm 11 and -//! newer. With a vendored override declared where the project's pnpm does -//! not read it, a frozen install fails (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH`) -//! and a plain `pnpm install` puts the registry release back (#2382; -//! measured on pnpm 8.15.9, 9.15.9, 10.28.0, 11.29.0 and 12.23.0). +//! its settings declare, and each pnpm release reads those from its own +//! place: package.json `pnpm.overrides` before pnpm 10.5.1, that table or +//! else pnpm-workspace.yaml `overrides:` from 10.5.1 through 10.x, the +//! workspace file alone from pnpm 11 on. With a vendored override declared +//! where the project's pnpm does not read it, a frozen install fails +//! (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH`) and a plain `pnpm install` puts +//! the registry release back (#2382; measured on pnpm 8.15.9, 9.15.9, +//! 10.2.0, 10.4.1, 10.5.0, 10.5.1, 10.28.0, 11.29.0 and 12.23.0). //! //! `vendor --check` and `vex` read the vendored reference from the lock //! alone, so both called such a package patched. Each case vendors the pnpm @@ -123,16 +124,18 @@ fn the_override_counts_only_where_the_projects_pnpm_reads_it() { // No pin: either file. (None, MANIFEST, true), (None, WORKSPACE, true), - // pnpm 10 reads either file. + // pnpm 10.5.1 and newer 10.x read the workspace file when + // package.json has no table, and the table when it has one. (Some("10.28.0"), MANIFEST, true), (Some("10.28.0"), WORKSPACE, true), // pnpm 11 and newer read the workspace file alone. (Some("11.29.0"), MANIFEST, true), (Some("11.29.0"), WORKSPACE, false), (Some("12.23.0"), WORKSPACE, false), - // pnpm 9 reads package.json alone, and a pinned pnpm 9 project with - // no workspace file gets none. + // pnpm older than 10.5.1 reads package.json alone, and a project + // pinned to one with no workspace file gets none. (Some("9.15.9"), MANIFEST, false), + (Some("10.4.1"), MANIFEST, false), ] { let case = format!("pnpm {pin:?} without the override in {dropped}"); let f = project(pin); @@ -141,7 +144,7 @@ fn the_override_counts_only_where_the_projects_pnpm_reads_it() { assert_eq!(code, 0, "{case}: {stdout}\n{stderr}"); assert_eq!( declares(&f, WORKSPACE), - pin != Some("9.15.9"), + !matches!(pin, Some("9.15.9" | "10.4.1")), "{case}: what vendor wrote" ); assert_eq!((check(&f).0, vex(&f).0), (0, 1), "{case}: as vendored"); @@ -157,13 +160,15 @@ fn the_override_counts_only_where_the_projects_pnpm_reads_it() { if installs { continue; } - let (file, major) = match dropped { - MANIFEST => ("package.json `pnpm.overrides`", "9"), - _ => ("pnpm-workspace.yaml `overrides`", &pin.unwrap()[..2]), + let file = match dropped { + MANIFEST => "package.json `pnpm.overrides`", + _ => "pnpm-workspace.yaml `overrides`", }; assert!( said.contains(&format!( - "{file}, the only place pnpm {major} reads overrides from" + "{file} does not declare it, and that is the only place this project's pnpm \ + (pnpm@{} (package.json packageManager)) reads overrides from", + pin.unwrap() )), "{case}: {said}" ); @@ -174,3 +179,53 @@ fn the_override_counts_only_where_the_projects_pnpm_reads_it() { assert_eq!((check(&f).0, vex(&f).0), (0, 1), "{case}: after the re-run"); } } + +/// pnpm 10.5.1 to 10.x read a `pnpm.overrides` table of package.json in +/// place of the workspace file's `overrides:` (measured on 10.28.0). A +/// project with a table of its own whose package.json loses the vendored +/// entries (a merge that took the other side) keeps them in the workspace +/// file, where that pnpm no longer looks. +#[test] +fn a_package_json_table_hides_the_workspace_override_on_pnpm_10() { + for (pin, installs) in [ + (Some("10.28.0"), false), + // pnpm 11 ignores the table, and with no pin either map counts. + (Some("11.29.0"), true), + (None, true), + ] { + let case = format!("pnpm {pin:?}"); + let f = project(pin); + let text = std::fs::read_to_string(f.root.join(MANIFEST)).unwrap(); + let own = text.replacen('{', r#"{"pnpm":{"overrides":{"gamma@1.0.0":"1.0.1"}},"#, 1); + std::fs::write(f.root.join(MANIFEST), &own).unwrap(); + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{case}: {stdout}\n{stderr}"); + assert!(declares(&f, MANIFEST) && declares(&f, WORKSPACE), "{case}"); + assert_eq!((check(&f).0, vex(&f).0), (0, 1), "{case}: as vendored"); + + drop_manifest_override(&f, own.as_bytes()); + let (code, said) = check(&f); + let expected = if installs { (0, 1) } else { (1, 0) }; + assert_eq!((code, vex(&f).0), expected, "{case}\n{said}"); + if installs { + continue; + } + assert!( + said.contains( + "package.json `pnpm.overrides` does not declare it, and this project's pnpm \ + (pnpm@10.28.0 (package.json packageManager)) reads that table in place of \ + pnpm-workspace.yaml `overrides`" + ), + "{said}" + ); + // The re-run adds the entries to the table that exists. + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{case}: {stdout}\n{stderr}"); + let after = std::fs::read_to_string(f.root.join(MANIFEST)).unwrap(); + assert!( + after.contains("gamma@1.0.0") && declares(&f, MANIFEST), + "{after}" + ); + assert_eq!((check(&f).0, vex(&f).0), (0, 1), "{case}: after the re-run"); + } +} diff --git a/crates/socket-patch-core/src/formats/pnpm/mod.rs b/crates/socket-patch-core/src/formats/pnpm/mod.rs index 104e0e6b5..9ca3ad42d 100644 --- a/crates/socket-patch-core/src/formats/pnpm/mod.rs +++ b/crates/socket-patch-core/src/formats/pnpm/mod.rs @@ -36,8 +36,8 @@ pub(crate) mod workspace; pub(crate) use version::range_admits; pub use version::{ - matches_file_id_build_keys, registry_route_pins, root_only_workspace_breaks_add, - RegistryRoutePins, REGISTRY_ROUTE_FLOOR, + matches_file_id_build_keys, pinned_override_source, registry_route_pins, + root_only_workspace_breaks_add, OverrideSource, RegistryRoutePins, REGISTRY_ROUTE_FLOOR, }; pub use grammar::PnpmDocument; diff --git a/crates/socket-patch-core/src/formats/pnpm/version.rs b/crates/socket-patch-core/src/formats/pnpm/version.rs index 2ea1f2b28..8067505f2 100644 --- a/crates/socket-patch-core/src/formats/pnpm/version.rs +++ b/crates/socket-patch-core/src/formats/pnpm/version.rs @@ -9,7 +9,8 @@ //! 9.0.0, 9.7.1, 9.15.9, 10.0.0–10.4.1 failing and 10.5.0+ passing). Those //! versions also read nothing the modes would write there: `trustLockfile` //! is a pnpm >= 11 setting, and `overrides:` in pnpm-workspace.yaml is read -//! from 10.5 on (older ones read package.json `pnpm.overrides`). +//! from 10.5.1 on (older ones read package.json `pnpm.overrides`, see +//! [`OverrideSource`]). //! //! The evidence is read conservatively, because a wrong "skip" loses a //! setting pnpm >= 11 needs: every present source must pin pnpm inside @@ -167,6 +168,97 @@ pub fn root_only_workspace_breaks_add( }) } +/// Where a pnpm release reads the overrides it resolves with. pnpm +/// installs a lock only when the lock's `overrides:` equal the ones it +/// reads here (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH` on a frozen install +/// otherwise, and a plain install resolves afresh and takes the registry +/// release), so this is where a vendored override has to be declared. +/// +/// Measured with a vendored `left-pad` (#2382). pnpm 8.15.9, 9.15.9, +/// 10.2.0, 10.4.1 and 10.5.0 install the lock only with the override in +/// package.json `pnpm.overrides`. pnpm 10.5.1, 10.5.2, 10.6.0, 10.9.0, +/// 10.13.1, 10.20.0 and 10.28.0 also install it with the override in +/// pnpm-workspace.yaml `overrides:` alone, but 10.28.0 does not while +/// package.json has a `pnpm.overrides` table that lacks it: that table is +/// read in place of the workspace file's. pnpm 11.29.0 and 12.23.0 install +/// it only with the override in the workspace file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OverrideSource { + /// pnpm older than 10.5.1: package.json `pnpm.overrides` alone. + Manifest, + /// pnpm 10.5.1 through 10.x: package.json's `pnpm.overrides` table + /// when it has one, else pnpm-workspace.yaml `overrides:`. + ManifestElseWorkspace, + /// pnpm 11 and newer: pnpm-workspace.yaml `overrides:` alone. + Workspace, + /// The project's files do not say which of those its pnpm is: either + /// map counts, the side that withholds no working wiring. + Unstated, +} + +impl OverrideSource { + /// The source every release in `lo..=hi` reads; `None` when the span + /// crosses a boundary. + fn of((lo, hi): (Release, Release)) -> Option { + const WORKSPACE_READ: Release = (10, 5, 1); + const MANIFEST_IGNORED: Release = (11, 0, 0); + if hi < WORKSPACE_READ { + Some(OverrideSource::Manifest) + } else if lo >= MANIFEST_IGNORED { + Some(OverrideSource::Workspace) + } else if lo >= WORKSPACE_READ && hi < MANIFEST_IGNORED { + Some(OverrideSource::ManifestElseWorkspace) + } else { + None + } + } + + /// Whether this pnpm reads an override that package.json declares + /// (`manifest`) or the workspace file declares (`workspace`); + /// `manifest_table` says package.json has a `pnpm.overrides` table at + /// all. + pub fn reads(self, manifest: bool, workspace: bool, manifest_table: bool) -> bool { + match self { + OverrideSource::Manifest => manifest, + OverrideSource::ManifestElseWorkspace if manifest_table => manifest, + OverrideSource::ManifestElseWorkspace | OverrideSource::Workspace => workspace, + OverrideSource::Unstated => manifest || workspace, + } + } +} + +/// The [`OverrideSource`] the project's pnpm pins state, with those pins +/// as prose (``pnpm@9.15.9 (node_modules/.modules.yaml)``); `None` when no +/// pin states one. +/// +/// The evidence is every pin [`root_only_workspace_breaks_add`] reads. A +/// pin states a source when every release it admits reads the same one +/// (an exact version, `~11.29.0`, `9.x`); a range that reaches across a +/// boundary (`>=9`, `^10.4.0`) or does not parse states none and is left +/// out. Pins that state different sources (an install record left by +/// another pnpm than the one package.json names) are +/// [`OverrideSource::Unstated`]: which of them installs next is not in the +/// files. +pub fn pinned_override_source( + package_json: Option<&str>, + modules_yaml: Option<&str>, +) -> Option<(OverrideSource, String)> { + let stated: Vec<(OverrideSource, String)> = pnpm_pins(package_json, modules_yaml) + .into_iter() + .filter_map(|(source, spec)| { + let reads = version_bounds(&spec).and_then(OverrideSource::of)?; + Some((reads, format!("pnpm@{spec} ({source})"))) + }) + .collect(); + let (first, _) = stated.first()?; + let source = match stated.iter().all(|(reads, _)| reads == first) { + true => *first, + false => OverrideSource::Unstated, + }; + let pins: Vec<&str> = stated.iter().map(|(_, pin)| pin.as_str()).collect(); + Some((source, pins.join(", "))) +} + /// The oldest pnpm hosted mode routes a patched package through a named /// registry for ([`registry_route_pins`]). pub const REGISTRY_ROUTE_FLOOR: (u64, u64) = (11, 20); diff --git a/crates/socket-patch-core/src/utils/pnpm_workspace.rs b/crates/socket-patch-core/src/utils/pnpm_workspace.rs index de9d613dc..bc3322949 100644 --- a/crates/socket-patch-core/src/utils/pnpm_workspace.rs +++ b/crates/socket-patch-core/src/utils/pnpm_workspace.rs @@ -983,54 +983,11 @@ fn lockfile_off(setting: impl Fn(&str, &str) -> Option) -> Option) -> Option { +async fn pnpm_major(view: &ProjectView<'_>) -> Option { let texts = read_texts(view, &[MODULES_YAML, "package.json", PNPM_LOCK]).await; pnpm_major_from(|rel| texts.get(rel).cloned()) } -/// Which override map a pnpm major reads: package.json `pnpm.overrides`, -/// pnpm-workspace.yaml `overrides:`, or either. pnpm installs a lock only -/// when the lock's `overrides:` equal the ones this map declares -/// (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH` on a frozen install otherwise, and -/// a plain install resolves afresh), so it is where a vendored override has -/// to be declared. -/// -/// Measured with a vendored `left-pad` on pnpm 8.15.9, 9.15.9, 10.28.0, -/// 11.29.0 and 12.23.0: pnpm 9 and older install the lock only with the -/// override in package.json, pnpm 10 with it in either file, pnpm 11 and -/// newer only with it in the workspace file. A major nothing states reads -/// either, the side that withholds no working wiring. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum PnpmOverrideSource { - /// pnpm 9 and older. - Manifest, - /// pnpm 10, or a major the project's files do not state. - Either, - /// pnpm 11 and newer. - Workspace, -} - -impl PnpmOverrideSource { - /// The map the pnpm of `major` ([`pnpm_major`]) reads. - pub(crate) fn of(major: Option) -> Self { - match major { - Some(major) if major >= 11 => PnpmOverrideSource::Workspace, - Some(major) if major <= 9 => PnpmOverrideSource::Manifest, - _ => PnpmOverrideSource::Either, - } - } - - /// Whether an override that package.json declares (`manifest`) or the - /// workspace file declares (`workspace`) is one this pnpm reads. - pub(crate) fn reads(self, manifest: bool, workspace: bool) -> bool { - match self { - PnpmOverrideSource::Manifest => manifest, - PnpmOverrideSource::Either => manifest || workspace, - PnpmOverrideSource::Workspace => workspace, - } - } -} - /// The pnpm major the project at `view` pins ([`pinned_pnpm_major`]). pub(crate) async fn pinned_pnpm_major_in(view: &ProjectView<'_>) -> Option { let texts = read_texts(view, &[MODULES_YAML, "package.json"]).await; diff --git a/crates/socket-patch-core/src/vendor/pnpm_lock.rs b/crates/socket-patch-core/src/vendor/pnpm_lock.rs index cf72f1c34..582c31847 100644 --- a/crates/socket-patch-core/src/vendor/pnpm_lock.rs +++ b/crates/socket-patch-core/src/vendor/pnpm_lock.rs @@ -2393,6 +2393,26 @@ pub(crate) fn override_section_entries(text: &str) -> Vec<(String, String)> { .collect() } +/// Whether a top-level `overrides:` key carries an inline value (a flow +/// mapping, an alias): a shape the line reader does not follow. +fn has_inline_overrides(lines: &[String]) -> bool { + lines.iter().any(|l| { + workspace::top_level_key(l) + .is_some_and(|(key, value)| key == "overrides" && !value.is_empty()) + }) +} + +/// Whether a pnpm-workspace.yaml may declare overrides that +/// [`override_section_entries`] cannot read: the shapes +/// [`check_workspace_override`] refuses to edit (a document that is not a +/// single block mapping, an inline `overrides:` value). pnpm reads them +/// all the same, so a reader that finds no entry there cannot say the file +/// declares none. +pub(crate) fn override_section_unreadable(text: &str) -> bool { + let lines = split_lines(text); + workspace::block_insert_point(&lines).is_err() || has_inline_overrides(&lines) +} + /// Pre-flight mirror check for pnpm-workspace.yaml (analogous to /// [`check_lock_override`]): a block-style `overrides:` section may only /// carry a same-name key equal to `effective_key` with an ownable value. @@ -2416,10 +2436,7 @@ fn check_workspace_override( corrupting it — rewrite it as a single block mapping and re-run" )); } - if lines.iter().any(|l| { - workspace::top_level_key(l) - .is_some_and(|(key, value)| key == "overrides" && !value.is_empty()) - }) { + if has_inline_overrides(&lines) { return Err(format!( "{PNPM_WORKSPACE} has an inline `overrides:` mapping the pair surgery cannot \ edit — rewrite it as a block mapping (`overrides:` then indented entries) \ diff --git a/crates/socket-patch-core/src/vex/discover/mod.rs b/crates/socket-patch-core/src/vex/discover/mod.rs index 2ceaa4763..d383181ce 100644 --- a/crates/socket-patch-core/src/vex/discover/mod.rs +++ b/crates/socket-patch-core/src/vex/discover/mod.rs @@ -1803,18 +1803,22 @@ impl Discovery { Some((shadowed, diag)) } - /// Why an extractor withheld the vendored wiring of patch `uuid` - /// although the files still wire it ([`Discovery::withheld`]): the - /// [`DIAG_REF_INVALID`] diagnostic of the withholding file that names - /// the patch. Lets a reader of a dead claim say what is missing instead - /// of saying nothing wires the artifact. - pub fn vendored_withheld(&self, uuid: &str) -> Option<&Diag> { + /// The diagnostic of a vendored pnpm lock entry of patch `uuid` that + /// was withheld because the project does not declare the override the + /// lock records for it (`npm::confirm_pnpm_overrides`): it names the + /// file that lacks the declaration and the remedy. Lets a reader of + /// the dead claim say what is missing instead of saying nothing wires + /// the artifact. + pub fn pnpm_override_undeclared(&self, uuid: &str) -> Option<&Diag> { self.withheld .iter() .filter(|w| w.uuid == uuid && w.mode == WiringMode::Vendored) .find_map(|w| { self.diagnostics.iter().find(|d| { - d.code == DIAG_REF_INVALID && d.file == w.file && d.detail.contains(uuid) + d.code == DIAG_REF_INVALID + && d.file == w.file + && d.detail.contains(npm::PNPM_OVERRIDE_UNDECLARED) + && d.detail.contains(uuid) }) }) } diff --git a/crates/socket-patch-core/src/vex/discover/npm.rs b/crates/socket-patch-core/src/vex/discover/npm.rs index ad56fae8c..7d57d52d9 100644 --- a/crates/socket-patch-core/src/vex/discover/npm.rs +++ b/crates/socket-patch-core/src/vex/discover/npm.rs @@ -66,13 +66,13 @@ use super::{ use crate::constants::npm_family::{NPM_LOCKS, PNPM_LOCK, PNPM_SHRINKWRAP_LEGACY}; use crate::formats::pnpm::plan::governing_pnpm_lock; use crate::formats::pnpm::{ - classify_pnpm_key, entry_bundled, entry_field, pnpm_registry_key, Bundled, PnpmDocument, - PnpmKey, PnpmLock, PnpmPackage, + classify_pnpm_key, entry_bundled, entry_field, pnpm_registry_key, Bundled, OverrideSource, + PnpmDocument, PnpmKey, PnpmLock, PnpmPackage, }; use crate::formats::text::strip_bom; use crate::patch::redirect::NpmUserPatches; use crate::utils::digest::is_sri_pin; -use crate::utils::pnpm_workspace::{PnpmOverrideSource, PNPM_WORKSPACE}; +use crate::utils::pnpm_workspace::{MODULES_YAML, PNPM_WORKSPACE}; use crate::vendor::lock_inventory::pnpm::{is_rush, rush_lock_rels}; use crate::vendor::lock_inventory::{ npm_lock_bundled_nodes, npm_lock_legacy_mirror_nodes, npm_lock_located_nodes, LockIntegrity, @@ -86,6 +86,12 @@ use crate::vendor::npm_origin::{ /// The manifest a pnpm project declares `pnpm.overrides` in. const PNPM_MANIFEST: &str = "package.json"; +/// How the diagnostic of a vendored pnpm entry whose override the project +/// does not declare starts, after the lock's name +/// ([`confirm_pnpm_overrides`]); [`Discovery::pnpm_override_undeclared`] +/// finds the diagnostic by it. +pub(crate) const PNPM_OVERRIDE_UNDECLARED: &str = "the lock records the override"; + pub(crate) async fn extract(ctx: &DiscoverCtx<'_>, out: &mut Discovery) { let mut locks: Vec = Vec::new(); let mut twin_present = false; @@ -1060,7 +1066,7 @@ async fn extract_pnpm_lock( /// `ERR_PNPM_LOCKFILE_CONFIG_MISMATCH`, and a plain `pnpm install` resolves /// again, takes the package from the registry and rewrites the lock /// without the vendored entry. Which file holds those settings depends on -/// the pnpm major ([`PnpmOverrideSource`]). So an entry whose override is +/// the pnpm release ([`OverrideSource`]). So an entry whose override is /// declared nowhere pnpm reads is the yarn berry orphan: it is diagnosed /// ([`DIAG_REF_INVALID`], with the remedy) and is no ref. The lock still /// wires the artifact and a rewire restores the declaration, so the entry @@ -1068,8 +1074,11 @@ async fn extract_pnpm_lock( /// /// Only an override the lock itself records is asked for: an entry wired /// with none (a `file:` dependency of the project's own, a hand-pointed -/// tarball) has nothing for pnpm to compare. A Rush lock is installed with -/// Rush's own settings, and a member's lock holds no vendored ref. +/// tarball) has nothing for pnpm to compare. A declaration in a shape the +/// reader cannot follow (an inline `overrides:` mapping, a package.json +/// that does not parse) may hold the override, so the ref then stands, as +/// it did before this check. A Rush lock is installed with Rush's own +/// settings, and a member's lock holds no vendored ref. async fn confirm_pnpm_overrides( ctx: &DiscoverCtx<'_>, file: &str, @@ -1098,57 +1107,61 @@ async fn confirm_pnpm_overrides( return; } let maps = PnpmOverrideMaps::read(ctx).await; - let major = crate::utils::pnpm_workspace::pnpm_major(&ctx.view).await; - let source = PnpmOverrideSource::of(major); + let pnpm = PnpmOverrideReader::of(ctx, lock, maps.manifest_text.as_deref()).await; + if maps.unreadable(pnpm.source) { + return; + } let undeclared = |r: &PatchedRef| -> Vec<&(String, VendorRef)> { recorded_for(r) .into_iter() - .filter(|(key, v)| !maps.declare(source, key, &v.artifact_rel)) + .filter(|(key, v)| !maps.declare(pnpm.source, key, &v.artifact_rel)) .collect() }; let (kept, dropped): (Vec, Vec) = std::mem::take(&mut out.refs) .into_iter() .partition(|r| undeclared(r).is_empty()); out.refs = kept; + // `vendor` writes no `pnpm.overrides` table into the package.json of a + // lockfileVersion 9 project that has none while the workspace file + // carries an override the lock records, whatever pnpm reads + // (`workspace_overrides_govern`). + let v9 = crate::formats::pnpm::lock_version_major(lock.text()).is_some_and(|v| v >= 9); for r in dropped { let missing = undeclared(&r); let keys: Vec = missing.iter().map(|(key, _)| format!("`{key}`")).collect(); let artifact = r.artifact_rel.as_deref().unwrap_or_default(); - // The pnpm whose reading decides, as `pnpm_major` finds it. - let pnpm = major.map_or_else(String::new, |major| { - format!( - ", the only place pnpm {major} reads overrides from (the project's pnpm by \ - node_modules/.modules.yaml, `packageManager` or the lock's format)," - ) - }); - let undeclared_in = match source { - PnpmOverrideSource::Manifest => { - format!("{PNPM_MANIFEST} `pnpm.overrides`{pnpm} does not declare it") - } - PnpmOverrideSource::Workspace => { - format!("{PNPM_WORKSPACE} `overrides`{pnpm} does not declare it") - } - PnpmOverrideSource::Either => format!( - "neither {PNPM_MANIFEST} `pnpm.overrides` nor {PNPM_WORKSPACE} `overrides` \ - declares it" + let who = &pnpm.who; + let table = format!("{PNPM_MANIFEST} `pnpm.overrides`"); + let block = format!("{PNPM_WORKSPACE} `overrides`"); + let undeclared_in = match pnpm.source { + OverrideSource::Manifest => format!( + "{table} does not declare it, and that is the only place {who} reads overrides \ + from" + ), + OverrideSource::Workspace => format!( + "{block} does not declare it, and that is the only place {who} reads overrides \ + from" ), + OverrideSource::ManifestElseWorkspace if maps.manifest_table => format!( + "{table} does not declare it, and {who} reads that table in place of {block}" + ), + OverrideSource::ManifestElseWorkspace | OverrideSource::Unstated => { + format!("neither {table} nor {block} declares it") + } }; - // `vendor` writes no `pnpm.overrides` table into a package.json - // that has none while the workspace file carries an override the - // lock records, whatever pnpm reads (`workspace_overrides_govern`). let in_workspace = missing .iter() - .all(|(key, v)| maps.declare(PnpmOverrideSource::Workspace, key, &v.artifact_rel)); + .all(|(key, v)| maps.declare(OverrideSource::Workspace, key, &v.artifact_rel)); let by_hand = - source == PnpmOverrideSource::Manifest && in_workspace && !maps.manifest_table; + pnpm.source == OverrideSource::Manifest && in_workspace && !maps.manifest_table && v9; let remedy = if by_hand { let entries: Vec = missing .iter() .map(|(key, v)| format!("`\"{key}\": \"file:{}\"`", v.artifact_rel)) .collect(); format!( - "Add {} to {PNPM_MANIFEST} `pnpm.overrides`: `socket-patch vendor` leaves it \ - out while {PNPM_WORKSPACE} declares the override", + "Add {} to {table}: `socket-patch vendor` leaves it out while {PNPM_WORKSPACE} \ + declares the override", entries.join(", ") ) } else { @@ -1159,7 +1172,7 @@ async fn confirm_pnpm_overrides( DIAG_REF_INVALID, file, format!( - "{file}: the lock records the override {} for {} ({artifact}), but \ + "{file}: {PNPM_OVERRIDE_UNDECLARED} {} for {} ({artifact}), but \ {undeclared_in}. pnpm installs a lock only when its `overrides:` equal the \ declared ones: a frozen install fails (ERR_PNPM_LOCKFILE_CONFIG_MISMATCH) and a \ plain `pnpm install` takes the package from the registry again; not counted. \ @@ -1176,6 +1189,50 @@ async fn confirm_pnpm_overrides( } } +/// Where the pnpm of a project reads its overrides from, and how a +/// diagnostic names that pnpm. +struct PnpmOverrideReader { + source: OverrideSource, + /// `this project's pnpm (pnpm@9.15.9 (node_modules/.modules.yaml))`. + who: String, +} + +impl PnpmOverrideReader { + /// From the project's pnpm pins ([`pinned_override_source`]), else from + /// what only one generation of pnpm writes into a lock: a pre-9 + /// lockfileVersion (pnpm 8 and older) or an env lockfile document + /// (pnpm 11 and newer). + /// + /// [`pinned_override_source`]: crate::formats::pnpm::pinned_override_source + async fn of(ctx: &DiscoverCtx<'_>, lock: &PnpmLock<'_>, manifest: Option<&str>) -> Self { + let modules = ctx.read_advisory_text(MODULES_YAML).await; + if let Some((source, pins)) = + crate::formats::pnpm::pinned_override_source(manifest, modules.as_deref()) + { + return PnpmOverrideReader { + source, + who: format!("this project's pnpm ({pins})"), + }; + } + let implied = crate::patch::redirect::upstream::npm::pnpm_settings_major(lock.text(), None); + let (source, who) = match implied { + Some(major) if major >= 11 => ( + OverrideSource::Workspace, + "the pnpm 11 or newer that wrote the lock's env document", + ), + Some(_) => ( + OverrideSource::Manifest, + "the pnpm 8 or older that wrote this lockfileVersion", + ), + None => (OverrideSource::Unstated, "pnpm"), + }; + PnpmOverrideReader { + source, + who: who.to_string(), + } + } +} + /// A pnpm project whose `lockfile` setting is off: where /// ([`crate::utils::pnpm_workspace::lockfile_disabled`]'s source), and the /// vendored artifacts its override maps route packages to. pnpm applies @@ -1205,8 +1262,18 @@ struct PnpmOverrideMaps { manifest: Vec<(String, VendorRef)>, /// Whether package.json has a `pnpm.overrides` table at all. manifest_table: bool, + /// package.json holds text that is not JSON, or a `pnpm.overrides` + /// that is not a table: what it declares cannot be read. + manifest_unreadable: bool, + /// package.json's text, for the readers of its pnpm pins. + manifest_text: Option, /// `(override key, artifact)` of pnpm-workspace.yaml `overrides:`. workspace: Vec<(String, VendorRef)>, + /// The workspace file may declare overrides in a shape the line reader + /// does not follow ([`override_section_unreadable`]). + /// + /// [`override_section_unreadable`]: crate::vendor::pnpm_lock::override_section_unreadable + workspace_unreadable: bool, } impl PnpmOverrideMaps { @@ -1217,13 +1284,15 @@ impl PnpmOverrideMaps { .filter_map(|(key, value)| Some((key, vendor_ref(&value)?))) .collect() }; - let table = ctx - .read_advisory_text(PNPM_MANIFEST) - .await - .and_then(|text| serde_json::from_str::(strip_bom(&text)).ok()) - .and_then(|doc| doc.pointer("/pnpm/overrides").cloned()); + let manifest_text = ctx.read_advisory_text(PNPM_MANIFEST).await; + let doc = manifest_text + .as_deref() + .map(|text| serde_json::from_str::(strip_bom(text))); + let table = match &doc { + Some(Ok(doc)) => doc.pointer("/pnpm/overrides"), + _ => None, + }; let manifest = table - .as_ref() .and_then(Value::as_object) .map(|map| { map.iter() @@ -1231,26 +1300,46 @@ impl PnpmOverrideMaps { .collect() }) .unwrap_or_default(); - let workspace = ctx - .read_advisory_text(PNPM_WORKSPACE) - .await - .map(|text| crate::vendor::pnpm_lock::override_section_entries(&text)) + let workspace_text = ctx.read_advisory_text(PNPM_WORKSPACE).await; + let workspace = workspace_text + .as_deref() + .map(crate::vendor::pnpm_lock::override_section_entries) .unwrap_or_default(); PnpmOverrideMaps { manifest: vendored(manifest), manifest_table: table.is_some(), + manifest_unreadable: matches!(doc, Some(Err(_))) + || table.is_some_and(|table| !table.is_object()), workspace: vendored(workspace), + workspace_unreadable: workspace_text + .as_deref() + .is_some_and(crate::vendor::pnpm_lock::override_section_unreadable), + manifest_text, } } /// Whether the map a pnpm of `source` reads declares the override /// `key` onto the artifact at `artifact_rel`, as a lock records it. - fn declare(&self, source: PnpmOverrideSource, key: &str, artifact_rel: &str) -> bool { + fn declare(&self, source: OverrideSource, key: &str, artifact_rel: &str) -> bool { let declared = |map: &[(String, VendorRef)]| { map.iter() .any(|(k, artifact)| k == key && artifact.artifact_rel == artifact_rel) }; - source.reads(declared(&self.manifest), declared(&self.workspace)) + source.reads( + declared(&self.manifest), + declared(&self.workspace), + self.manifest_table, + ) + } + + /// Whether a map a pnpm of `source` reads is in a shape this reader + /// cannot follow, so that what it declares cannot be told. + fn unreadable(&self, source: OverrideSource) -> bool { + source.reads( + self.manifest_unreadable, + self.workspace_unreadable, + self.manifest_table || self.manifest_unreadable, + ) } } @@ -4757,13 +4846,13 @@ mod tests { } /// REGRESSION (#2382): pnpm installs a lock only when the lock's - /// `overrides:` equal the ones its settings declare, and each major - /// reads them from its own file. Measured with a vendored `left-pad` - /// on pnpm 8.15.9, 9.15.9, 10.28.0, 11.29.0 and 12.23.0: with the - /// override declared where that pnpm does not read it, a frozen install - /// stops with `ERR_PNPM_LOCKFILE_CONFIG_MISMATCH` and a plain one - /// installs the registry release and rewrites the lock. Such an entry - /// was a ref, so `vex` attested it and `vendor --check` verified it. + /// `overrides:` equal the ones its settings declare, and each release + /// reads them from its own place ([`OverrideSource`], with the pnpm + /// releases each row was measured on). With the override declared + /// where that pnpm does not read it, a frozen install stops with + /// `ERR_PNPM_LOCKFILE_CONFIG_MISMATCH` and a plain one installs the + /// registry release and rewrites the lock. Such an entry was a ref, so + /// `vex` attested it and `vendor --check` verified it. #[tokio::test] async fn pnpm_vendored_ref_needs_its_recorded_override_declared() { let rel = format!(".socket/vendor/npm/{UUID_B}/left-pad-1.3.0.tgz"); @@ -4792,32 +4881,48 @@ mod tests { } p }; + // What an undeclared entry's diagnostic says of the place. + #[derive(Debug, Clone, Copy, PartialEq)] + enum Place { + Manifest, + Workspace, + Neither, + } + use Place::*; // (the pnpm the project pins, package.json declares, the workspace - // file declares, pnpm installs the lock). + // file declares, `Err(place)` when pnpm does not install the lock). for (pin, manifest, workspace, installs) in [ // No file states the pnpm: either map. - (None, false, false, false), - (None, true, false, true), - (None, false, true, true), - (None, true, true, true), - // pnpm 9 and older: package.json alone. - (Some("8.15.9"), true, false, true), - (Some("8.15.9"), false, true, false), - (Some("9.15.9"), true, false, true), - (Some("9.15.9"), true, true, true), - (Some("9.15.9"), false, true, false), - (Some("9.15.9"), false, false, false), - // pnpm 10: either map. - (Some("10.28.0"), true, false, true), - (Some("10.28.0"), false, true, true), - (Some("10.28.0"), false, false, false), + (None, false, false, Err(Neither)), + (None, true, false, Ok(())), + (None, false, true, Ok(())), + (None, true, true, Ok(())), + // pnpm older than 10.5.1: package.json alone. + (Some("8.15.9"), true, false, Ok(())), + (Some("8.15.9"), false, true, Err(Manifest)), + (Some("9.15.9"), true, false, Ok(())), + (Some("9.15.9"), true, true, Ok(())), + (Some("9.15.9"), false, true, Err(Manifest)), + (Some("9.15.9"), false, false, Err(Manifest)), + (Some("10.4.1"), true, false, Ok(())), + (Some("10.4.1"), false, true, Err(Manifest)), + (Some("10.5.0"), false, true, Err(Manifest)), + // pnpm 10.5.1 to 10.x: the workspace file when package.json + // has no table. + (Some("10.5.1"), false, true, Ok(())), + (Some("10.5.1"), true, false, Ok(())), + (Some("10.5.1"), false, false, Err(Neither)), + (Some("10.28.0"), true, false, Ok(())), + (Some("10.28.0"), false, true, Ok(())), + (Some("10.28.0"), true, true, Ok(())), + (Some("10.28.0"), false, false, Err(Neither)), // pnpm 11 and newer: the workspace file alone. - (Some("11.29.0"), false, true, true), - (Some("11.29.0"), true, true, true), - (Some("11.29.0"), true, false, false), - (Some("12.23.0"), false, true, true), - (Some("12.23.0"), true, false, false), - (Some("12.23.0"), false, false, false), + (Some("11.29.0"), false, true, Ok(())), + (Some("11.29.0"), true, true, Ok(())), + (Some("11.29.0"), true, false, Err(Workspace)), + (Some("12.23.0"), false, true, Ok(())), + (Some("12.23.0"), true, false, Err(Workspace)), + (Some("12.23.0"), false, false, Err(Workspace)), ] { let case = format!("pnpm {pin:?}, package.json {manifest}, workspace {workspace}"); let out = run(&project(pin, manifest, workspace)).await; @@ -4827,14 +4932,14 @@ mod tests { .filter(|d| d.code == DIAG_REF_INVALID) .map(|d| d.detail.as_str()) .collect(); - if installs { + let Err(place) = installs else { assert_refs(&out, &[(PURL, UUID_B, WiringMode::Vendored)]); assert!( invalid.is_empty() && out.withheld.is_empty(), "{case}: {invalid:#?}" ); continue; - } + }; assert_refs(&out, &[]); assert!( out.shadowed.is_empty() && out.unattested.is_empty(), @@ -4848,32 +4953,38 @@ mod tests { panic!("{case}: {invalid:#?}"); }; assert_eq!( - out.vendored_withheld(UUID_B).map(|d| d.detail.as_str()), + out.pnpm_override_undeclared(UUID_B) + .map(|d| d.detail.as_str()), Some(*detail) ); assert!( detail.contains(PURL) && detail.contains(&rel) - && detail.contains("`left-pad@1.3.0`") + && detail.contains("the lock records the override `left-pad@1.3.0`") && detail.contains("ERR_PNPM_LOCKFILE_CONFIG_MISMATCH"), "{case}: {detail}" ); - let major = pin.and_then(|v| v.split('.').next()); - let (place, other) = match major { - Some("8" | "9") => ("package.json `pnpm.overrides`, the only place", "neither"), - Some("11" | "12") => ("pnpm-workspace.yaml `overrides`, the only place", "neither"), - _ => ( - "neither package.json `pnpm.overrides` nor", - "the only place", + let who = format!( + "this project's pnpm (pnpm@{} (package.json packageManager))", + pin.unwrap_or_default() + ); + let said = match place { + Manifest => format!( + "package.json `pnpm.overrides` does not declare it, and that is the only \ + place {who} reads overrides from" ), + Workspace => format!( + "pnpm-workspace.yaml `overrides` does not declare it, and that is the only \ + place {who} reads overrides from" + ), + Neither => "neither package.json `pnpm.overrides` nor pnpm-workspace.yaml \ + `overrides` declares it" + .to_string(), }; - assert!( - detail.contains(place) && !detail.contains(other), - "{case}: {detail}" - ); + assert!(detail.contains(&said), "{case}: {detail}"); // `vendor` writes no `pnpm.overrides` table while the workspace // file carries the override, so there the remedy is the entry. - let by_hand = matches!(major, Some("8" | "9")) && workspace; + let by_hand = place == Manifest && workspace; let remedy = match by_hand { true => format!(r#"Add `"left-pad@1.3.0": "file:{rel}"` to package.json"#), false => "Re-run `socket-patch vendor`".to_string(), @@ -4918,29 +5029,26 @@ mod tests { assert_eq!(live.vendor_entry_in_use(p.root(), &entry).await, Some(true)); } - /// The pnpm whose reading decides is the one every pnpm setting is read - /// for: the install record first, then the `packageManager` pin, then - /// what the lock's own format implies (#2382). + /// Which pnpm reads the overrides comes from the project's pins, read + /// conservatively, then from what only one generation of pnpm writes + /// into a lock (#2382). #[tokio::test] async fn pnpm_recorded_override_is_read_for_the_projects_pnpm() { let rel = format!(".socket/vendor/npm/{UUID_B}/left-pad-1.3.0.tgz"); const PURL: &str = "pkg:npm/left-pad@1.3.0"; let wired = [(PURL, UUID_B, WiringMode::Vendored)]; - let manifest = |pin: &str| { + let manifest = |pins: &str| { format!( - r#"{{"name":"app",{pin}"dependencies":{{"left-pad":"1.3.0"}},"pnpm":{{"overrides":{{"left-pad@1.3.0":"file:{rel}"}}}}}}"# + r#"{{"name":"app",{pins}"dependencies":{{"left-pad":"1.3.0"}},"pnpm":{{"overrides":{{"left-pad@1.3.0":"file:{rel}"}}}}}}"# ) }; let workspace = format!("packages:\n - '.'\noverrides:\n left-pad@1.3.0: file:{rel}\n"); + let detail = |out: &Discovery| out.diagnostics[0].detail.clone(); - // The install record outranks the pin: pnpm 11 installed the tree. + // The install record alone: pnpm 11 installed the tree. let p = Project::new(); p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); - p.write( - "package.json", - manifest(r#""packageManager":"pnpm@9.15.9","#), - ); - assert_refs(&run(&p).await, &wired); + p.write("package.json", manifest("")); p.write( "node_modules/.modules.yaml", r#"{"layoutVersion":5,"packageManager":"pnpm@11.29.0"}"#, @@ -4948,10 +5056,27 @@ mod tests { let out = run(&p).await; assert_refs(&out, &[]); assert!( - out.diagnostics[0].detail.contains("pnpm 11 reads"), - "{:#?}", - out.diagnostics + detail(&out).contains( + "the only place this project's pnpm (pnpm@11.29.0 (node_modules/.modules.yaml)) \ + reads" + ), + "{}", + detail(&out) + ); + // An install record another pnpm left, beside the pin package.json + // commits: which of the two installs next is not in the files, so + // either map counts. A stale `node_modules` fails no checkout. + p.write( + "package.json", + manifest(r#""packageManager":"pnpm@9.15.9","#), + ); + assert_refs(&run(&p).await, &wired); + // Two pins that read the same place. + p.write( + "package.json", + manifest(r#""packageManager":"pnpm@12.23.0","#), ); + assert_refs(&run(&p).await, &[]); p.write("pnpm-workspace.yaml", &workspace); assert_refs(&run(&p).await, &wired); @@ -4967,6 +5092,29 @@ mod tests { ); assert_refs(&run(&p).await, &[]); + // A range that reaches across a boundary states nothing: beside an + // exact pin the pin decides, alone it leaves either map. + for (pins, attested) in [ + ( + r#""packageManager":"pnpm@11.29.0","engines":{"pnpm":">=9"},"#, + false, + ), + (r#""engines":{"pnpm":">=9"},"#, true), + (r#""engines":{"pnpm":"^10.4.0"},"#, true), + (r#""engines":{"pnpm":"11.x"},"#, false), + (r#""engines":{"pnpm":"~10.4.0"},"#, true), + ( + r#""devEngines":{"packageManager":{"name":"pnpm","version":"12.23.0"}},"#, + false, + ), + ] { + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("package.json", manifest(pins)); + let expected: &[_] = if attested { &wired } else { &[] }; + assert_refs(&run(&p).await, expected); + } + // No pin: an env lockfile document is pnpm 11's. let env = "---\nlockfileVersion: '9.0'\n\nimporters:\n\n .:\n configDependencies:\n \ @@ -4975,12 +5123,19 @@ mod tests { let p = Project::new(); p.write("pnpm-lock.yaml", pnpm_vendored_lock(env)); p.write("package.json", manifest("")); - assert_refs(&run(&p).await, &[]); + let out = run(&p).await; + assert_refs(&out, &[]); + assert!( + detail(&out).contains("the pnpm 11 or newer that wrote the lock's env document"), + "{}", + detail(&out) + ); p.write("pnpm-workspace.yaml", &workspace); assert_refs(&run(&p).await, &wired); // No pin: a lockfileVersion 6 lock is pnpm 8's, which reads - // package.json alone (the legacy backend writes no workspace file). + // package.json alone. The legacy backend always writes the + // package.json override, so re-running `vendor` is the remedy. let legacy = format!( "lockfileVersion: '6.0'\n\noverrides:\n left-pad@1.3.0: file:{rel}\n\ndependencies:\n \ left-pad:\n specifier: file:/abs/app/{rel}\n version: file:{rel}\n\npackages:\n\n \ @@ -4996,16 +5151,18 @@ mod tests { let out = run(&p).await; assert_refs(&out, &[]); assert!( - out.diagnostics[0].detail.contains("pnpm 8 reads"), - "{:#?}", - out.diagnostics + detail(&out).contains("the pnpm 8 or older that wrote this lockfileVersion") + && detail(&out).contains("Re-run `socket-patch vendor`"), + "{}", + detail(&out) ); } /// Only what pnpm compares is asked for (#2382): the override keys the - /// lock records, spelled as the lock spells them. An entry wired with no - /// recorded override has nothing to confirm, and a Rush lock is - /// installed with Rush's own settings. + /// lock records, spelled as the lock spells them, in the map that pnpm + /// reads. An entry wired with no recorded override has nothing to + /// confirm, and a declaration in a shape the reader cannot follow + /// leaves the ref as it was. #[tokio::test] async fn pnpm_recorded_override_is_compared_as_pnpm_compares_it() { let rel = format!(".socket/vendor/npm/{UUID_B}/left-pad-1.3.0.tgz"); @@ -5014,6 +5171,7 @@ mod tests { let manifest = |key: &str, value: &str| { format!(r#"{{"name":"app","pnpm":{{"overrides":{{"{key}":"{value}"}}}}}}"#) }; + let block = format!("packages:\n - '.'\noverrides:\n left-pad@1.3.0: file:{rel}\n"); let p = Project::new(); p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); // Another key, another artifact, a registry version: not the @@ -5054,30 +5212,43 @@ mod tests { ), ); assert_refs(&run(&p).await, &wired); - // A flow mapping is a shape the reader cannot vouch for. - p.write( - "pnpm-workspace.yaml", - format!("packages: ['.']\noverrides: {{'left-pad@1.3.0': 'file:{rel}'}}\n"), + + // pnpm 10.5.1 to 10.x read a `pnpm.overrides` table in place of + // the workspace file's (measured on 10.28.0): a table without the + // override hides the workspace declaration, and `vendor` adds the + // override to a table that exists. + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("pnpm-workspace.yaml", &block); + let pinned = |pin: &str, table: &str| { + format!(r#"{{"name":"app","packageManager":"pnpm@{pin}"{table}}}"#) + }; + let own_table = r#","pnpm":{"overrides":{"ms@2.0.0":"2.1.3"}}"#; + p.write("package.json", pinned("10.28.0", "")); + assert_refs(&run(&p).await, &wired); + p.write("package.json", pinned("10.28.0", own_table)); + let out = run(&p).await; + assert_refs(&out, &[]); + let detail = &out.diagnostics[0].detail; + assert!( + detail.contains( + "package.json `pnpm.overrides` does not declare it, and this project's pnpm \ + (pnpm@10.28.0 (package.json packageManager)) reads that table in place of \ + pnpm-workspace.yaml `overrides`" + ) && detail.contains("Re-run `socket-patch vendor`"), + "{detail}" ); - assert_refs(&run(&p).await, &[]); + // pnpm 11 ignores the table, and with no pin either map counts. + p.write("package.json", pinned("11.29.0", own_table)); + assert_refs(&run(&p).await, &wired); + p.write("package.json", format!(r#"{{"name":"app"{own_table}}}"#)); + assert_refs(&run(&p).await, &wired); // pnpm 9, the override in the workspace file alone: `vendor` adds // it to a `pnpm.overrides` table that exists, so re-running is the // remedy there; with no table the entry has to be added by hand. - for (table, by_hand) in [ - ("", true), - (r#","pnpm":{"overrides":{"ms@2.0.0":"2.1.3"}}"#, false), - ] { - let p = Project::new(); - p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); - p.write( - "package.json", - format!(r#"{{"name":"app","packageManager":"pnpm@9.15.9"{table}}}"#), - ); - p.write( - "pnpm-workspace.yaml", - format!("packages:\n - '.'\noverrides:\n left-pad@1.3.0: file:{rel}\n"), - ); + for (table, by_hand) in [("", true), (own_table, false)] { + p.write("package.json", pinned("9.15.9", table)); let out = run(&p).await; assert_refs(&out, &[]); let detail = &out.diagnostics[0].detail; @@ -5093,6 +5264,38 @@ mod tests { ); } + // A declaration the line reader cannot follow may hold the + // override (pnpm reads it all the same), so the ref stands as it + // did before: an inline mapping, a second YAML document, a + // package.json that is not JSON. + for (pin, file, text) in [ + ( + "11.29.0", + "pnpm-workspace.yaml", + format!("packages: ['.']\noverrides: {{'left-pad@1.3.0': 'file:{rel}'}}\n"), + ), + ( + "11.29.0", + "pnpm-workspace.yaml", + "packages:\n - '.'\n---\noverrides:\n a: b\n".to_string(), + ), + ("9.15.9", "package.json", "{ not json".to_string()), + ] { + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("package.json", pinned(pin, "")); + if pin == "9.15.9" { + p.write( + "node_modules/.modules.yaml", + "packageManager: pnpm@9.15.9\n", + ); + } + p.write(file, &text); + let out = run(&p).await; + assert_refs(&out, &wired); + assert!(out.diagnostics.is_empty(), "{file}: {:#?}", out.diagnostics); + } + // A CRLF checkout and a BOM read like their plain twins: the // recorded override is still found, and still has to be declared. for text in [ @@ -5116,10 +5319,7 @@ mod tests { .replace(&format!("overrides:\n left-pad@1.3.0: file:{rel}\n\n"), ""); let p = Project::new(); p.write("pnpm-lock.yaml", &unrecorded); - p.write( - "package.json", - r#"{"name":"app","packageManager":"pnpm@11.29.0"}"#, - ); + p.write("package.json", pinned("11.29.0", "")); let out = run(&p).await; assert_refs(&out, &wired); assert!(out.diagnostics.is_empty(), "{:#?}", out.diagnostics); @@ -5146,6 +5346,34 @@ mod tests { detail.contains("the override `left-pad` for") && !detail.contains("`left-pad@1.3.0`"), "{detail}" ); + + // Another rejected entry of the same artifact does not stand in + // for the reason `vendor --check` prints. + let twin = pnpm_vendored_lock("").replace( + "\nsnapshots:", + &format!( + "\n left-pad@file:.socket/vendor/npm/{UUID_B}/other-1.3.0.tgz:\n \ + resolution: {{integrity: {SRI}, tarball: file:{rel}}}\n version: 1.3.0\n\nsnapshots:" + ), + ); + let p = Project::new(); + p.write("pnpm-lock.yaml", &twin); + p.write("package.json", r#"{"name":"app"}"#); + let out = run(&p).await; + assert_refs(&out, &[]); + let invalid: Vec<&str> = out + .diagnostics + .iter() + .filter(|d| d.code == DIAG_REF_INVALID && d.detail.contains(UUID_B)) + .map(|d| d.detail.as_str()) + .collect(); + assert_eq!(invalid.len(), 2, "{invalid:#?}"); + let named = out.pnpm_override_undeclared(UUID_B).unwrap(); + assert!( + named.detail.contains("the lock records the override"), + "{}", + named.detail + ); } /// npm's `package-lock=false` (or its `shrinkwrap=false` alias) in the diff --git a/docs/ecosystems.md b/docs/ecosystems.md index f2a24c571..a28ae23b0 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -240,22 +240,28 @@ Each Legacy format has an upgrade path and an undo path. Both work in v5: package to its artifact, and omits it otherwise (`vex_lock_not_read`). **A vendored override has to stay declared.** pnpm installs a lock only when the lock's `overrides:` equal the ones its settings declare: with a - vendored override missing from the file pnpm reads, a frozen install fails - (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH`) and a plain `pnpm install` takes the - package from the registry again. pnpm 9 and older read `pnpm.overrides` in - `package.json`, pnpm 10 reads either file, pnpm 11 and newer read - `overrides:` in `pnpm-workspace.yaml` alone; the pnpm is the one - `node_modules/.modules.yaml` records, else the `packageManager` pin, else - what the lock's format implies, and when none says, either file counts. + vendored override missing from the place pnpm reads, a frozen install + fails (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH`) and a plain `pnpm install` + takes the package from the registry again. pnpm older than 10.5.1 reads + `pnpm.overrides` in `package.json`; pnpm 10.5.1 through 10.x reads that + table when `package.json` has one, and `overrides:` in + `pnpm-workspace.yaml` when it has none; pnpm 11 and newer read the + workspace file alone. Which pnpm that is comes from the project's pins + (`node_modules/.modules.yaml`, `packageManager`, `devEngines`, + `engines.pnpm`), each counted when every release it admits reads the + same place, and else from the lock (a pnpm 7 or 8 lock, or pnpm 11's + env document). When nothing says, or the pins disagree (an install + record another pnpm left), either file counts. So a `pnpm-workspace.yaml` left out of the commit, a `package.json` put back by a merge, or a move from pnpm 9 to 11 leaves the lock wired and the patch uninstallable. `vendor --check` then fails the package (`wiring incomplete`, naming the file) and `vex` omits it (`patched_ref_invalid`, `vendor_unwired`). Re-running `socket-patch vendor` declares the override - again; on pnpm 9 and older it leaves `package.json` alone while + again; before pnpm 10.5.1 it writes no `pnpm.overrides` table while `pnpm-workspace.yaml` already carries the override, and the message then - gives the entry to add. A Rush lock, and a lock entry that records no - override, are not checked this way. + gives the entry to add. Not checked this way: a Rush lock, a lock entry + that records no override, and a declaration `socket-patch` cannot read + (an inline `overrides:` mapping, a `package.json` that is not JSON). **One mode for a package and its dependency.** pnpm 12.23 and newer refuse a lock in which a package fetched from a hosted patch depends on a local file (`ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED`), on every install, frozen or From d4d0fed1d153aff419b072628014c07d0ba4ec7c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 06:42:09 +0000 Subject: [PATCH 5/7] Read pnpm's committed pins and resolutions A second review, run against real pnpm, showed where the last commit still disagreed with what pnpm installs: - An install record in node_modules decided alone. It is not committed, so one checkout failed a tree that CI verified. Only the pins package.json commits are read now, then the lock's own format. - Pins naming releases that read different places left either file, even where neither release reads it. Each stated source is kept, and a declaration counts when one of them reads it. - pnpm 9.15.9 and 10.28.0 read the top-level `resolutions` as overrides (11.29.0 does not), and 10.5.1 and 10.28.0 read the workspace file beside an empty `pnpm.overrides` table. package.json now declares what `pnpm.overrides` over `resolutions` holds, and declares nothing when that is empty. The by-hand remedy asks the backend's own predicate for when a re-run writes no package.json table, so the message says "re-run" only where a re-run helps. Refs #2382. Assisted-by: Claude Code --- .../tests/vendor_pnpm_override_e2e.rs | 10 +- .../socket-patch-core/src/formats/pnpm/mod.rs | 2 +- .../src/formats/pnpm/version.rs | 77 ++--- .../socket-patch-core/src/vendor/pnpm_lock.rs | 6 +- .../socket-patch-core/src/vex/discover/npm.rs | 275 +++++++++++------- docs/ecosystems.md | 28 +- 6 files changed, 240 insertions(+), 158 deletions(-) diff --git a/crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs b/crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs index 768718ced..50ff2855b 100644 --- a/crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs +++ b/crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs @@ -1,8 +1,8 @@ //! pnpm installs a lock only when the lock's `overrides:` equal the ones //! its settings declare, and each pnpm release reads those from its own -//! place: package.json `pnpm.overrides` before pnpm 10.5.1, that table or -//! else pnpm-workspace.yaml `overrides:` from 10.5.1 through 10.x, the -//! workspace file alone from pnpm 11 on. With a vendored override declared +//! place: package.json before pnpm 10.5.1, package.json when it declares +//! overrides or else pnpm-workspace.yaml `overrides:` from 10.5.1 through +//! 10.x, the workspace file alone from pnpm 11 on. With a vendored override declared //! where the project's pnpm does not read it, a frozen install fails //! (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH`) and a plain `pnpm install` puts //! the registry release back (#2382; measured on pnpm 8.15.9, 9.15.9, @@ -212,8 +212,8 @@ fn a_package_json_table_hides_the_workspace_override_on_pnpm_10() { } assert!( said.contains( - "package.json `pnpm.overrides` does not declare it, and this project's pnpm \ - (pnpm@10.28.0 (package.json packageManager)) reads that table in place of \ + "package.json declares overrides without it, and this project's pnpm \ + (pnpm@10.28.0 (package.json packageManager)) reads those in place of \ pnpm-workspace.yaml `overrides`" ), "{said}" diff --git a/crates/socket-patch-core/src/formats/pnpm/mod.rs b/crates/socket-patch-core/src/formats/pnpm/mod.rs index 9ca3ad42d..3d7efc732 100644 --- a/crates/socket-patch-core/src/formats/pnpm/mod.rs +++ b/crates/socket-patch-core/src/formats/pnpm/mod.rs @@ -36,7 +36,7 @@ pub(crate) mod workspace; pub(crate) use version::range_admits; pub use version::{ - matches_file_id_build_keys, pinned_override_source, registry_route_pins, + matches_file_id_build_keys, pinned_override_sources, registry_route_pins, root_only_workspace_breaks_add, OverrideSource, RegistryRoutePins, REGISTRY_ROUTE_FLOOR, }; diff --git a/crates/socket-patch-core/src/formats/pnpm/version.rs b/crates/socket-patch-core/src/formats/pnpm/version.rs index 8067505f2..0c96322fe 100644 --- a/crates/socket-patch-core/src/formats/pnpm/version.rs +++ b/crates/socket-patch-core/src/formats/pnpm/version.rs @@ -176,18 +176,25 @@ pub fn root_only_workspace_breaks_add( /// /// Measured with a vendored `left-pad` (#2382). pnpm 8.15.9, 9.15.9, /// 10.2.0, 10.4.1 and 10.5.0 install the lock only with the override in -/// package.json `pnpm.overrides`. pnpm 10.5.1, 10.5.2, 10.6.0, 10.9.0, -/// 10.13.1, 10.20.0 and 10.28.0 also install it with the override in -/// pnpm-workspace.yaml `overrides:` alone, but 10.28.0 does not while -/// package.json has a `pnpm.overrides` table that lacks it: that table is -/// read in place of the workspace file's. pnpm 11.29.0 and 12.23.0 install -/// it only with the override in the workspace file. +/// package.json. pnpm 10.5.1, 10.5.2, 10.6.0, 10.9.0, 10.13.1, 10.20.0 and +/// 10.28.0 also install it with the override in pnpm-workspace.yaml +/// `overrides:` alone, but 10.28.0 does not while package.json declares +/// overrides that lack it: those are read in place of the workspace +/// file's. pnpm 11.29.0 and 12.23.0 install it only with the override in +/// the workspace file. +/// +/// package.json's overrides are `pnpm.overrides` over the top-level +/// `resolutions` (9.15.9 and 10.28.0 install the lock with the override +/// in `resolutions` alone, 11.29.0 does not), and declaring none is the +/// same as an empty table (10.5.1 and 10.28.0 read the workspace file +/// beside `"overrides": {}`, 10.28.0 does not beside a `resolutions` +/// entry of the project's own). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OverrideSource { - /// pnpm older than 10.5.1: package.json `pnpm.overrides` alone. + /// pnpm older than 10.5.1: package.json alone. Manifest, - /// pnpm 10.5.1 through 10.x: package.json's `pnpm.overrides` table - /// when it has one, else pnpm-workspace.yaml `overrides:`. + /// pnpm 10.5.1 through 10.x: package.json's overrides when it declares + /// any, else pnpm-workspace.yaml `overrides:`. ManifestElseWorkspace, /// pnpm 11 and newer: pnpm-workspace.yaml `overrides:` alone. Workspace, @@ -215,8 +222,7 @@ impl OverrideSource { /// Whether this pnpm reads an override that package.json declares /// (`manifest`) or the workspace file declares (`workspace`); - /// `manifest_table` says package.json has a `pnpm.overrides` table at - /// all. + /// `manifest_table` says package.json declares any override at all. pub fn reads(self, manifest: bool, workspace: bool, manifest_table: bool) -> bool { match self { OverrideSource::Manifest => manifest, @@ -227,36 +233,31 @@ impl OverrideSource { } } -/// The [`OverrideSource`] the project's pnpm pins state, with those pins -/// as prose (``pnpm@9.15.9 (node_modules/.modules.yaml)``); `None` when no -/// pin states one. +/// The [`OverrideSource`]s the pnpm pins package.json commits state +/// (`packageManager`, `devEngines.packageManager`, `engines.pnpm`), each +/// with its pin as prose (``pnpm@9.15.9 (package.json packageManager)``), +/// one entry per source; empty when no pin states one. /// -/// The evidence is every pin [`root_only_workspace_breaks_add`] reads. A -/// pin states a source when every release it admits reads the same one +/// A pin states a source when every release it admits reads the same one /// (an exact version, `~11.29.0`, `9.x`); a range that reaches across a /// boundary (`>=9`, `^10.4.0`) or does not parse states none and is left -/// out. Pins that state different sources (an install record left by -/// another pnpm than the one package.json names) are -/// [`OverrideSource::Unstated`]: which of them installs next is not in the -/// files. -pub fn pinned_override_source( - package_json: Option<&str>, - modules_yaml: Option<&str>, -) -> Option<(OverrideSource, String)> { - let stated: Vec<(OverrideSource, String)> = pnpm_pins(package_json, modules_yaml) - .into_iter() - .filter_map(|(source, spec)| { - let reads = version_bounds(&spec).and_then(OverrideSource::of)?; - Some((reads, format!("pnpm@{spec} ({source})"))) - }) - .collect(); - let (first, _) = stated.first()?; - let source = match stated.iter().all(|(reads, _)| reads == first) { - true => *first, - false => OverrideSource::Unstated, - }; - let pins: Vec<&str> = stated.iter().map(|(_, pin)| pin.as_str()).collect(); - Some((source, pins.join(", "))) +/// out. Pins that state different sources are all returned: a declaration +/// counts when a pnpm the project names reads it. +/// +/// The install record (`node_modules/.modules.yaml`) is not read here. It +/// is not committed, so the same commit would verify on one machine and +/// fail on another, by whichever pnpm last installed there. +pub fn pinned_override_sources(package_json: Option<&str>) -> Vec<(OverrideSource, String)> { + let mut stated: Vec<(OverrideSource, String)> = Vec::new(); + for (source, spec) in pnpm_pins(package_json, None) { + let Some(reads) = version_bounds(&spec).and_then(OverrideSource::of) else { + continue; + }; + if stated.iter().all(|(known, _)| *known != reads) { + stated.push((reads, format!("pnpm@{spec} ({source})"))); + } + } + stated } /// The oldest pnpm hosted mode routes a patched package through a named diff --git a/crates/socket-patch-core/src/vendor/pnpm_lock.rs b/crates/socket-patch-core/src/vendor/pnpm_lock.rs index 582c31847..0cb2eed6b 100644 --- a/crates/socket-patch-core/src/vendor/pnpm_lock.rs +++ b/crates/socket-patch-core/src/vendor/pnpm_lock.rs @@ -2273,7 +2273,11 @@ pub(super) fn apply_pkg_override( /// vendored value counts too: after a workspace-only takeover (#854) or /// an earlier skipped copy, the lock recording it still shows the /// workspace file governs, and a copy now would shadow it. -fn workspace_overrides_govern(pkg: &Value, ws_text: Option<&str>, lock: &[String]) -> bool { +pub(crate) fn workspace_overrides_govern( + pkg: &Value, + ws_text: Option<&str>, + lock: &[String], +) -> bool { if pkg.get("pnpm").and_then(|p| p.get("overrides")).is_some() { return false; } diff --git a/crates/socket-patch-core/src/vex/discover/npm.rs b/crates/socket-patch-core/src/vex/discover/npm.rs index 7d57d52d9..c54ac4280 100644 --- a/crates/socket-patch-core/src/vex/discover/npm.rs +++ b/crates/socket-patch-core/src/vex/discover/npm.rs @@ -72,7 +72,7 @@ use crate::formats::pnpm::{ use crate::formats::text::strip_bom; use crate::patch::redirect::NpmUserPatches; use crate::utils::digest::is_sri_pin; -use crate::utils::pnpm_workspace::{MODULES_YAML, PNPM_WORKSPACE}; +use crate::utils::pnpm_workspace::PNPM_WORKSPACE; use crate::vendor::lock_inventory::pnpm::{is_rush, rush_lock_rels}; use crate::vendor::lock_inventory::{ npm_lock_bundled_nodes, npm_lock_legacy_mirror_nodes, npm_lock_located_nodes, LockIntegrity, @@ -1107,25 +1107,31 @@ async fn confirm_pnpm_overrides( return; } let maps = PnpmOverrideMaps::read(ctx).await; - let pnpm = PnpmOverrideReader::of(ctx, lock, maps.manifest_text.as_deref()).await; - if maps.unreadable(pnpm.source) { + let pnpm = PnpmOverrideReader::of(lock, maps.manifest_text.as_deref()); + if pnpm.sources.iter().any(|source| maps.unreadable(*source)) { return; } let undeclared = |r: &PatchedRef| -> Vec<&(String, VendorRef)> { recorded_for(r) .into_iter() - .filter(|(key, v)| !maps.declare(pnpm.source, key, &v.artifact_rel)) + .filter(|(key, v)| !pnpm.reads(&maps, key, &v.artifact_rel)) .collect() }; let (kept, dropped): (Vec, Vec) = std::mem::take(&mut out.refs) .into_iter() .partition(|r| undeclared(r).is_empty()); out.refs = kept; - // `vendor` writes no `pnpm.overrides` table into the package.json of a - // lockfileVersion 9 project that has none while the workspace file - // carries an override the lock records, whatever pnpm reads - // (`workspace_overrides_govern`). - let v9 = crate::formats::pnpm::lock_version_major(lock.text()).is_some_and(|v| v >= 9); + // Where `vendor` writes no `pnpm.overrides` table on a re-run: a + // lockfileVersion 9 project whose package.json has none while the + // workspace file carries an override the lock records, whatever pnpm + // reads (the backend's own predicate). + let vendor_skips_manifest = crate::formats::pnpm::lock_version_major(lock.text()) + .is_some_and(|v| v >= 9) + && crate::vendor::pnpm_lock::workspace_overrides_govern( + maps.manifest_doc.as_ref().unwrap_or(&Value::Null), + maps.workspace_text.as_deref(), + &crate::formats::pnpm::lines::split_lines(&lock.text().replace("\r\n", "\n")), + ); for r in dropped { let missing = undeclared(&r); let keys: Vec = missing.iter().map(|(key, _)| format!("`{key}`")).collect(); @@ -1133,35 +1139,33 @@ async fn confirm_pnpm_overrides( let who = &pnpm.who; let table = format!("{PNPM_MANIFEST} `pnpm.overrides`"); let block = format!("{PNPM_WORKSPACE} `overrides`"); - let undeclared_in = match pnpm.source { - OverrideSource::Manifest => format!( + let undeclared_in = match pnpm.sources.as_slice() { + [OverrideSource::Manifest] => format!( "{table} does not declare it, and that is the only place {who} reads overrides \ from" ), - OverrideSource::Workspace => format!( + [OverrideSource::Workspace] => format!( "{block} does not declare it, and that is the only place {who} reads overrides \ from" ), - OverrideSource::ManifestElseWorkspace if maps.manifest_table => format!( - "{table} does not declare it, and {who} reads that table in place of {block}" + [OverrideSource::ManifestElseWorkspace] if maps.manifest_table => format!( + "{PNPM_MANIFEST} declares overrides without it, and {who} reads those in place \ + of {block}" ), - OverrideSource::ManifestElseWorkspace | OverrideSource::Unstated => { + [OverrideSource::ManifestElseWorkspace | OverrideSource::Unstated] => { format!("neither {table} nor {block} declares it") } + _ => format!("it is not declared where any of {who} reads overrides from"), }; - let in_workspace = missing - .iter() - .all(|(key, v)| maps.declare(OverrideSource::Workspace, key, &v.artifact_rel)); - let by_hand = - pnpm.source == OverrideSource::Manifest && in_workspace && !maps.manifest_table && v9; + let by_hand = pnpm.sources == [OverrideSource::Manifest] && vendor_skips_manifest; let remedy = if by_hand { let entries: Vec = missing .iter() .map(|(key, v)| format!("`\"{key}\": \"file:{}\"`", v.artifact_rel)) .collect(); format!( - "Add {} to {table}: `socket-patch vendor` leaves it out while {PNPM_WORKSPACE} \ - declares the override", + "Add {} to {table}: `socket-patch vendor` writes no such table while \ + {PNPM_WORKSPACE} carries overrides the lock records", entries.join(", ") ) } else { @@ -1192,26 +1196,31 @@ async fn confirm_pnpm_overrides( /// Where the pnpm of a project reads its overrides from, and how a /// diagnostic names that pnpm. struct PnpmOverrideReader { - source: OverrideSource, - /// `this project's pnpm (pnpm@9.15.9 (node_modules/.modules.yaml))`. + /// One source, or the several that the project's pins state. + sources: Vec, + /// `this project's pnpm (pnpm@9.15.9 (package.json packageManager))`. who: String, } impl PnpmOverrideReader { - /// From the project's pnpm pins ([`pinned_override_source`]), else from - /// what only one generation of pnpm writes into a lock: a pre-9 - /// lockfileVersion (pnpm 8 and older) or an env lockfile document - /// (pnpm 11 and newer). + /// From the pnpm pins package.json commits + /// ([`pinned_override_sources`]), else from what only one generation + /// of pnpm writes into a lock: a pre-9 lockfileVersion (pnpm 8 and + /// older) or an env lockfile document (pnpm 11 and newer). Committed + /// files only, so every checkout of a commit reads the same pnpm. /// - /// [`pinned_override_source`]: crate::formats::pnpm::pinned_override_source - async fn of(ctx: &DiscoverCtx<'_>, lock: &PnpmLock<'_>, manifest: Option<&str>) -> Self { - let modules = ctx.read_advisory_text(MODULES_YAML).await; - if let Some((source, pins)) = - crate::formats::pnpm::pinned_override_source(manifest, modules.as_deref()) - { + /// [`pinned_override_sources`]: crate::formats::pnpm::pinned_override_sources + fn of(lock: &PnpmLock<'_>, manifest: Option<&str>) -> Self { + let stated = crate::formats::pnpm::pinned_override_sources(manifest); + if !stated.is_empty() { + let pins: Vec<&str> = stated.iter().map(|(_, pin)| pin.as_str()).collect(); + let who = match pins.as_slice() { + [pin] => format!("this project's pnpm ({pin})"), + pins => format!("the pnpm releases this project names ({})", pins.join(", ")), + }; return PnpmOverrideReader { - source, - who: format!("this project's pnpm ({pins})"), + sources: stated.iter().map(|(source, _)| *source).collect(), + who, }; } let implied = crate::patch::redirect::upstream::npm::pnpm_settings_major(lock.text(), None); @@ -1227,10 +1236,18 @@ impl PnpmOverrideReader { None => (OverrideSource::Unstated, "pnpm"), }; PnpmOverrideReader { - source, + sources: vec![source], who: who.to_string(), } } + + /// Whether a pnpm the project names reads the override `key` onto the + /// artifact at `artifact_rel` from where `maps` declare it. + fn reads(&self, maps: &PnpmOverrideMaps, key: &str, artifact_rel: &str) -> bool { + self.sources + .iter() + .any(|source| maps.declare(*source, key, artifact_rel)) + } } /// A pnpm project whose `lockfile` setting is off: where @@ -1258,15 +1275,20 @@ struct PnpmLockOff { /// packages to: the declarations pnpm resolves with, with or without a /// lock. struct PnpmOverrideMaps { - /// `(override key, artifact)` of package.json `pnpm.overrides`. + /// `(override key, artifact)` of package.json: `pnpm.overrides` over + /// the top-level `resolutions`, which pnpm 10 and older read as + /// overrides too. manifest: Vec<(String, VendorRef)>, - /// Whether package.json has a `pnpm.overrides` table at all. + /// Whether package.json declares any override at all (an empty table + /// is none). manifest_table: bool, - /// package.json holds text that is not JSON, or a `pnpm.overrides` - /// that is not a table: what it declares cannot be read. + /// package.json holds text that is not JSON, or overrides that are not + /// a table: what it declares cannot be read. manifest_unreadable: bool, - /// package.json's text, for the readers of its pnpm pins. + /// package.json's text and document, for the readers of its pnpm pins + /// and of what `vendor` would write. manifest_text: Option, + manifest_doc: Option, /// `(override key, artifact)` of pnpm-workspace.yaml `overrides:`. workspace: Vec<(String, VendorRef)>, /// The workspace file may declare overrides in a shape the line reader @@ -1274,6 +1296,7 @@ struct PnpmOverrideMaps { /// /// [`override_section_unreadable`]: crate::vendor::pnpm_lock::override_section_unreadable workspace_unreadable: bool, + workspace_text: Option, } impl PnpmOverrideMaps { @@ -1288,33 +1311,38 @@ impl PnpmOverrideMaps { let doc = manifest_text .as_deref() .map(|text| serde_json::from_str::(strip_bom(text))); - let table = match &doc { - Some(Ok(doc)) => doc.pointer("/pnpm/overrides"), + let manifest_doc = match &doc { + Some(Ok(doc)) => Some(doc.clone()), _ => None, }; - let manifest = table - .and_then(Value::as_object) - .map(|map| { - map.iter() - .filter_map(|(key, value)| Some((key.clone(), value.as_str()?.to_string()))) - .collect() - }) - .unwrap_or_default(); + // `pnpm.overrides` wins over a `resolutions` entry of the same key. + let tables: Vec<&Value> = ["/resolutions", "/pnpm/overrides"] + .iter() + .filter_map(|pointer| manifest_doc.as_ref()?.pointer(pointer)) + .collect(); + let mut merged: BTreeMap = BTreeMap::new(); + for (key, value) in tables.iter().filter_map(|t| t.as_object()).flatten() { + // A value that is not a string is no vendored override, but it + // still makes the table one that declares something. + merged.insert(key.clone(), value.as_str().unwrap_or_default().to_string()); + } let workspace_text = ctx.read_advisory_text(PNPM_WORKSPACE).await; let workspace = workspace_text .as_deref() .map(crate::vendor::pnpm_lock::override_section_entries) .unwrap_or_default(); PnpmOverrideMaps { - manifest: vendored(manifest), - manifest_table: table.is_some(), + manifest_table: !merged.is_empty(), + manifest: vendored(merged.into_iter().collect()), manifest_unreadable: matches!(doc, Some(Err(_))) - || table.is_some_and(|table| !table.is_object()), + || tables.iter().any(|table| !table.is_object()), workspace: vendored(workspace), workspace_unreadable: workspace_text .as_deref() .is_some_and(crate::vendor::pnpm_lock::override_section_unreadable), manifest_text, + manifest_doc, + workspace_text, } } @@ -5029,9 +5057,10 @@ mod tests { assert_eq!(live.vendor_entry_in_use(p.root(), &entry).await, Some(true)); } - /// Which pnpm reads the overrides comes from the project's pins, read - /// conservatively, then from what only one generation of pnpm writes - /// into a lock (#2382). + /// Which pnpm reads the overrides comes from the pins package.json + /// commits, read conservatively, then from what only one generation of + /// pnpm writes into a lock (#2382). Committed files only: the same + /// commit reads the same on every machine. #[tokio::test] async fn pnpm_recorded_override_is_read_for_the_projects_pnpm() { let rel = format!(".socket/vendor/npm/{UUID_B}/left-pad-1.3.0.tgz"); @@ -5042,54 +5071,51 @@ mod tests { r#"{{"name":"app",{pins}"dependencies":{{"left-pad":"1.3.0"}},"pnpm":{{"overrides":{{"left-pad@1.3.0":"file:{rel}"}}}}}}"# ) }; + let bare = |pins: &str| format!(r#"{{"name":"app",{pins}"private":true}}"#); let workspace = format!("packages:\n - '.'\noverrides:\n left-pad@1.3.0: file:{rel}\n"); let detail = |out: &Discovery| out.diagnostics[0].detail.clone(); - // The install record alone: pnpm 11 installed the tree. + // The install record is machine-local: whichever pnpm installed + // this checkout last decides nothing. + for record in [ + r#"{"layoutVersion":5,"packageManager":"pnpm@11.29.0"}"#, + "layoutVersion: 5\npackageManager: pnpm@9.15.9\n", + ] { + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("node_modules/.modules.yaml", record); + p.write("package.json", manifest("")); + assert_refs(&run(&p).await, &wired); + p.write("package.json", bare("")); + p.write("pnpm-workspace.yaml", &workspace); + assert_refs(&run(&p).await, &wired); + } + + // Pins that name pnpm releases reading different places: a + // declaration counts when one of them reads it. + let two = r#""packageManager":"pnpm@9.15.9","engines":{"pnpm":"11.x"},"#; let p = Project::new(); p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); - p.write("package.json", manifest("")); - p.write( - "node_modules/.modules.yaml", - r#"{"layoutVersion":5,"packageManager":"pnpm@11.29.0"}"#, - ); + p.write("package.json", manifest(two)); + assert_refs(&run(&p).await, &wired); + p.write("package.json", bare(two)); let out = run(&p).await; assert_refs(&out, &[]); assert!( detail(&out).contains( - "the only place this project's pnpm (pnpm@11.29.0 (node_modules/.modules.yaml)) \ - reads" - ), + "it is not declared where any of the pnpm releases this project names \ + (pnpm@9.15.9 (package.json packageManager), pnpm@11.x (package.json \ + engines.pnpm)) reads overrides from" + ) && detail(&out).contains("Re-run `socket-patch vendor`"), "{}", detail(&out) ); - // An install record another pnpm left, beside the pin package.json - // commits: which of the two installs next is not in the files, so - // either map counts. A stale `node_modules` fails no checkout. - p.write( - "package.json", - manifest(r#""packageManager":"pnpm@9.15.9","#), - ); - assert_refs(&run(&p).await, &wired); - // Two pins that read the same place. - p.write( - "package.json", - manifest(r#""packageManager":"pnpm@12.23.0","#), - ); - assert_refs(&run(&p).await, &[]); p.write("pnpm-workspace.yaml", &workspace); assert_refs(&run(&p).await, &wired); - - // A pre-10 install record is a YAML scalar. - let p = Project::new(); - p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); - p.write("package.json", r#"{"name":"app"}"#); - p.write("pnpm-workspace.yaml", &workspace); - assert_refs(&run(&p).await, &wired); - p.write( - "node_modules/.modules.yaml", - "layoutVersion: 5\npackageManager: pnpm@9.15.9\n", - ); + // Neither of two pinned releases reads the workspace file beside a + // table of the project's own: either file alone is not enough. + let both10 = r#""packageManager":"pnpm@10.28.0","devEngines":{"packageManager":{"name":"pnpm","version":"10.4.1"}},"pnpm":{"overrides":{"ms@2.0.0":"2.1.3"}},"#; + p.write("package.json", bare(both10)); assert_refs(&run(&p).await, &[]); // A range that reaches across a boundary states nothing: beside an @@ -5232,8 +5258,8 @@ mod tests { let detail = &out.diagnostics[0].detail; assert!( detail.contains( - "package.json `pnpm.overrides` does not declare it, and this project's pnpm \ - (pnpm@10.28.0 (package.json packageManager)) reads that table in place of \ + "package.json declares overrides without it, and this project's pnpm \ + (pnpm@10.28.0 (package.json packageManager)) reads those in place of \ pnpm-workspace.yaml `overrides`" ) && detail.contains("Re-run `socket-patch vendor`"), "{detail}" @@ -5243,6 +5269,39 @@ mod tests { assert_refs(&run(&p).await, &wired); p.write("package.json", format!(r#"{{"name":"app"{own_table}}}"#)); assert_refs(&run(&p).await, &wired); + // An empty table declares nothing (measured on 10.5.1 and 10.28.0), + // and a top-level `resolutions` is a table like `pnpm.overrides` + // (10.28.0). + p.write( + "package.json", + pinned("10.28.0", r#","pnpm":{"overrides":{}}"#), + ); + assert_refs(&run(&p).await, &wired); + p.write( + "package.json", + pinned("10.28.0", r#","resolutions":{"ms@2.0.0":"2.1.3"}"#), + ); + assert_refs(&run(&p).await, &[]); + + // pnpm 10 and older read `resolutions` as overrides (measured on + // 9.15.9 and 10.28.0); pnpm 11 does not (11.29.0). + let resolved = format!(r#","resolutions":{{"left-pad@1.3.0":"file:{rel}"}}"#); + for (pin, installs) in [("9.15.9", true), ("10.28.0", true), ("11.29.0", false)] { + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("package.json", pinned(pin, &resolved)); + let expected: &[_] = if installs { &wired } else { &[] }; + assert_refs(&run(&p).await, expected); + } + // `pnpm.overrides` wins over `resolutions` for the same key. + let shadowed = format!( + r#","resolutions":{{"left-pad@1.3.0":"file:{rel}"}},"pnpm":{{"overrides":{{"left-pad@1.3.0":"1.3.0"}}}}"# + ); + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("pnpm-workspace.yaml", &block); + p.write("package.json", pinned("9.15.9", &shadowed)); + assert_refs(&run(&p).await, &[]); // pnpm 9, the override in the workspace file alone: `vendor` adds // it to a `pnpm.overrides` table that exists, so re-running is the @@ -5264,6 +5323,28 @@ mod tests { ); } + // The same holds when the workspace file carries another override + // the lock records and this one is in neither file: the re-run + // would write the workspace entry alone. + let two_recorded = + pnpm_vendored_lock("").replace("overrides:\n", "overrides:\n ms@2.0.0: 2.1.3\n"); + let q = Project::new(); + q.write("pnpm-lock.yaml", &two_recorded); + q.write("package.json", pinned("9.15.9", "")); + q.write( + "pnpm-workspace.yaml", + "packages:\n - '.'\noverrides:\n ms@2.0.0: 2.1.3\n", + ); + let out = run(&q).await; + assert_refs(&out, &[]); + assert!( + out.diagnostics[0] + .detail + .contains("Add `\"left-pad@1.3.0\""), + "{}", + out.diagnostics[0].detail + ); + // A declaration the line reader cannot follow may hold the // override (pnpm reads it all the same), so the ref stands as it // did before: an inline mapping, a second YAML document, a @@ -5284,12 +5365,6 @@ mod tests { let p = Project::new(); p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); p.write("package.json", pinned(pin, "")); - if pin == "9.15.9" { - p.write( - "node_modules/.modules.yaml", - "packageManager: pnpm@9.15.9\n", - ); - } p.write(file, &text); let out = run(&p).await; assert_refs(&out, &wired); diff --git a/docs/ecosystems.md b/docs/ecosystems.md index a28ae23b0..61bb7fd0b 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -243,25 +243,27 @@ Each Legacy format has an upgrade path and an undo path. Both work in v5: vendored override missing from the place pnpm reads, a frozen install fails (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH`) and a plain `pnpm install` takes the package from the registry again. pnpm older than 10.5.1 reads - `pnpm.overrides` in `package.json`; pnpm 10.5.1 through 10.x reads that - table when `package.json` has one, and `overrides:` in - `pnpm-workspace.yaml` when it has none; pnpm 11 and newer read the - workspace file alone. Which pnpm that is comes from the project's pins - (`node_modules/.modules.yaml`, `packageManager`, `devEngines`, - `engines.pnpm`), each counted when every release it admits reads the - same place, and else from the lock (a pnpm 7 or 8 lock, or pnpm 11's - env document). When nothing says, or the pins disagree (an install - record another pnpm left), either file counts. + `package.json` alone (`pnpm.overrides`, over the top-level + `resolutions`); pnpm 10.5.1 through 10.x reads `package.json` when it + declares any override, and `overrides:` in `pnpm-workspace.yaml` when it + declares none; pnpm 11 and newer read the workspace file alone. Which + pnpm that is comes from the pins `package.json` commits + (`packageManager`, `devEngines`, `engines.pnpm`), each counted when + every release it admits reads the same place, and else from the lock (a + pnpm 7 or 8 lock, or pnpm 11's env document). The install record in + `node_modules` is not read, so a commit reads the same on every machine. + With no pin either file counts, and with pins that name different + releases the override counts when one of them reads it. So a `pnpm-workspace.yaml` left out of the commit, a `package.json` put back by a merge, or a move from pnpm 9 to 11 leaves the lock wired and the patch uninstallable. `vendor --check` then fails the package (`wiring incomplete`, naming the file) and `vex` omits it (`patched_ref_invalid`, `vendor_unwired`). Re-running `socket-patch vendor` declares the override again; before pnpm 10.5.1 it writes no `pnpm.overrides` table while - `pnpm-workspace.yaml` already carries the override, and the message then - gives the entry to add. Not checked this way: a Rush lock, a lock entry - that records no override, and a declaration `socket-patch` cannot read - (an inline `overrides:` mapping, a `package.json` that is not JSON). + `pnpm-workspace.yaml` carries overrides the lock records, and the message + then gives the entry to add. Not checked this way: a Rush lock, a lock + entry that records no override, and a declaration `socket-patch` cannot + read (an inline `overrides:` mapping, a `package.json` that is not JSON). **One mode for a package and its dependency.** pnpm 12.23 and newer refuse a lock in which a package fetched from a hosted patch depends on a local file (`ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED`), on every install, frozen or From d303c0b1b09b8d5e3f91d3a96be1c107148298b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 07:04:32 +0000 Subject: [PATCH 6/7] Give the by-hand entry where a re-run is idle A third review pass found three more gaps, each checked before it was fixed: - With overrides declared through `resolutions` alone, pnpm 10.28.0 reads package.json, and a re-run of `vendor` writes nothing there (it looks for a `pnpm.overrides` table). The message said to re-run. It now gives the entry to add whenever the re-run would declare the override only where no pnpm the project names reads it. Checked on real pnpm 10.28.0: the re-run is idle, and after the entry is added the frozen install is patched. - An empty inline `overrides: {}` (or a null) in the workspace file switched the check off as unreadable. It declares nothing. - A package.json or workspace file that is there and cannot be read was taken for one that declares nothing. The reference stands there, as for one that does not parse. Refs #2382. Assisted-by: Claude Code --- .../socket-patch-core/src/vendor/pnpm_lock.rs | 17 ++++- .../socket-patch-core/src/vex/discover/mod.rs | 15 ++++ .../socket-patch-core/src/vex/discover/npm.rs | 75 ++++++++++++++++--- 3 files changed, 92 insertions(+), 15 deletions(-) diff --git a/crates/socket-patch-core/src/vendor/pnpm_lock.rs b/crates/socket-patch-core/src/vendor/pnpm_lock.rs index 0cb2eed6b..e2971a7ca 100644 --- a/crates/socket-patch-core/src/vendor/pnpm_lock.rs +++ b/crates/socket-patch-core/src/vendor/pnpm_lock.rs @@ -2409,12 +2409,21 @@ fn has_inline_overrides(lines: &[String]) -> bool { /// Whether a pnpm-workspace.yaml may declare overrides that /// [`override_section_entries`] cannot read: the shapes /// [`check_workspace_override`] refuses to edit (a document that is not a -/// single block mapping, an inline `overrides:` value). pnpm reads them -/// all the same, so a reader that finds no entry there cannot say the file -/// declares none. +/// single block mapping, an inline `overrides:` value that holds +/// entries). pnpm reads them all the same, so a reader that finds no entry +/// there cannot say the file declares none. pub(crate) fn override_section_unreadable(text: &str) -> bool { let lines = split_lines(text); - workspace::block_insert_point(&lines).is_err() || has_inline_overrides(&lines) + // An empty mapping or a null declares nothing, inline or not. + let holds_entries = |value: &str| { + let value: String = value.split_whitespace().collect(); + !matches!(value.as_str(), "" | "{}" | "~" | "null") + }; + workspace::block_insert_point(&lines).is_err() + || lines.iter().any(|l| { + workspace::top_level_key(l) + .is_some_and(|(key, value)| key == "overrides" && holds_entries(value)) + }) } /// Pre-flight mirror check for pnpm-workspace.yaml (analogous to diff --git a/crates/socket-patch-core/src/vex/discover/mod.rs b/crates/socket-patch-core/src/vex/discover/mod.rs index d383181ce..87cd922d5 100644 --- a/crates/socket-patch-core/src/vex/discover/mod.rs +++ b/crates/socket-patch-core/src/vex/discover/mod.rs @@ -2442,6 +2442,21 @@ impl<'a> DiscoverCtx<'a> { self.view.read_text(rel).await.ok() } + /// [`DiscoverCtx::read_advisory_text`] that tells a file that is not + /// there (`Ok(None)`) from one that is there and cannot be read + /// (`Err`), for a reader that must not take the second for "declares + /// nothing". + pub(crate) async fn read_advisory_text_if_present( + &self, + rel: &str, + ) -> Result, ()> { + match self.view.read_text(rel).await { + Ok(text) => Ok(Some(text)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(_) => Err(()), + } + } + /// Bytes twin of [`DiscoverCtx::read_advisory_text`] (a user's `file:` /// tarball, read only to name the package it holds). pub(crate) async fn read_advisory_bytes(&self, rel: &str) -> Option> { diff --git a/crates/socket-patch-core/src/vex/discover/npm.rs b/crates/socket-patch-core/src/vex/discover/npm.rs index c54ac4280..7433f982b 100644 --- a/crates/socket-patch-core/src/vex/discover/npm.rs +++ b/crates/socket-patch-core/src/vex/discover/npm.rs @@ -1074,10 +1074,10 @@ async fn extract_pnpm_lock( /// /// Only an override the lock itself records is asked for: an entry wired /// with none (a `file:` dependency of the project's own, a hand-pointed -/// tarball) has nothing for pnpm to compare. A declaration in a shape the -/// reader cannot follow (an inline `overrides:` mapping, a package.json -/// that does not parse) may hold the override, so the ref then stands, as -/// it did before this check. A Rush lock is installed with Rush's own +/// tarball) has nothing for pnpm to compare. A declaration the reader +/// cannot follow (an inline `overrides:` mapping that holds entries, a +/// package.json that does not parse, a file that cannot be read) may hold +/// the override, so the ref then stands, as it did before this check. A Rush lock is installed with Rush's own /// settings, and a member's lock holds no vendored ref. async fn confirm_pnpm_overrides( ctx: &DiscoverCtx<'_>, @@ -1157,7 +1157,14 @@ async fn confirm_pnpm_overrides( } _ => format!("it is not declared where any of {who} reads overrides from"), }; - let by_hand = pnpm.sources == [OverrideSource::Manifest] && vendor_skips_manifest; + // A re-run that skips package.json declares the override in the + // workspace file alone: by hand, unless a pnpm the project names + // reads it there. + let by_hand = vendor_skips_manifest + && !pnpm + .sources + .iter() + .any(|source| source.reads(false, true, maps.manifest_table)); let remedy = if by_hand { let entries: Vec = missing .iter() @@ -1307,7 +1314,10 @@ impl PnpmOverrideMaps { .filter_map(|(key, value)| Some((key, vendor_ref(&value)?))) .collect() }; - let manifest_text = ctx.read_advisory_text(PNPM_MANIFEST).await; + // A file that is there and cannot be read may declare anything. + let manifest_read = ctx.read_advisory_text_if_present(PNPM_MANIFEST).await; + let workspace_read = ctx.read_advisory_text_if_present(PNPM_WORKSPACE).await; + let manifest_text = manifest_read.clone().ok().flatten(); let doc = manifest_text .as_deref() .map(|text| serde_json::from_str::(strip_bom(text))); @@ -1326,7 +1336,7 @@ impl PnpmOverrideMaps { // still makes the table one that declares something. merged.insert(key.clone(), value.as_str().unwrap_or_default().to_string()); } - let workspace_text = ctx.read_advisory_text(PNPM_WORKSPACE).await; + let workspace_text = workspace_read.clone().ok().flatten(); let workspace = workspace_text .as_deref() .map(crate::vendor::pnpm_lock::override_section_entries) @@ -1334,12 +1344,14 @@ impl PnpmOverrideMaps { PnpmOverrideMaps { manifest_table: !merged.is_empty(), manifest: vendored(merged.into_iter().collect()), - manifest_unreadable: matches!(doc, Some(Err(_))) + manifest_unreadable: manifest_read.is_err() + || matches!(doc, Some(Err(_))) || tables.iter().any(|table| !table.is_object()), workspace: vendored(workspace), - workspace_unreadable: workspace_text - .as_deref() - .is_some_and(crate::vendor::pnpm_lock::override_section_unreadable), + workspace_unreadable: workspace_read.is_err() + || workspace_text + .as_deref() + .is_some_and(crate::vendor::pnpm_lock::override_section_unreadable), manifest_text, manifest_doc, workspace_text, @@ -5323,6 +5335,25 @@ mod tests { ); } + // pnpm 10.28.0 beside a `resolutions` entry of the project's own: + // it reads package.json, where a re-run writes nothing (the + // backend looks for a `pnpm.overrides` table), so the entry is + // given there too. + p.write( + "package.json", + pinned("10.28.0", r#","resolutions":{"ms@2.0.0":"2.1.3"}"#), + ); + let out = run(&p).await; + assert_refs(&out, &[]); + assert!( + out.diagnostics[0] + .detail + .contains("Add `\"left-pad@1.3.0\"") + && !out.diagnostics[0].detail.contains("Re-run"), + "{}", + out.diagnostics[0].detail + ); + // The same holds when the workspace file carries another override // the lock records and this one is in neither file: the re-run // would write the workspace entry alone. @@ -5371,6 +5402,28 @@ mod tests { assert!(out.diagnostics.is_empty(), "{file}: {:#?}", out.diagnostics); } + // A file that is there and cannot be read may declare anything. + let q = Project::new(); + q.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + q.write("package.json/not-a-file", ""); + assert_refs(&run(&q).await, &wired); + // An empty inline mapping or a null declares nothing, though. + for empty in [ + "overrides: {}", + "overrides: { } # none", + "overrides: ~", + "overrides: null", + ] { + let q = Project::new(); + q.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + q.write("package.json", pinned("11.29.0", "")); + q.write( + "pnpm-workspace.yaml", + format!("packages:\n - '.'\n{empty}\n"), + ); + assert_refs(&run(&q).await, &[]); + } + // A CRLF checkout and a BOM read like their plain twins: the // recorded override is still found, and still has to be declared. for text in [ From 82814cb3e18fa2ad864681f02fa35e26f2115e97 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 07:20:20 +0000 Subject: [PATCH 7/7] Name an empty inline overrides mapping Cursor Bugbot's finding, reproduced with the binary: with an empty inline `overrides: {}` (or a null) in pnpm-workspace.yaml, the message said to re-run `vendor`, and the re-run refuses to edit an inline mapping. The user learned what to do only from that second error. The remedy now says to take the empty inline `overrides:` out first. Checked on real pnpm 11.29.0: after that the re-run declares the override, `vendor --check` passes and the frozen install is patched. Refs #2382. Assisted-by: Claude Code --- .../socket-patch-core/src/vendor/pnpm_lock.rs | 6 +++++ .../socket-patch-core/src/vex/discover/npm.rs | 24 ++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/socket-patch-core/src/vendor/pnpm_lock.rs b/crates/socket-patch-core/src/vendor/pnpm_lock.rs index e2971a7ca..e7c1eef55 100644 --- a/crates/socket-patch-core/src/vendor/pnpm_lock.rs +++ b/crates/socket-patch-core/src/vendor/pnpm_lock.rs @@ -2406,6 +2406,12 @@ fn has_inline_overrides(lines: &[String]) -> bool { }) } +/// Whether a pnpm-workspace.yaml carries an inline `overrides:` value, +/// which [`check_workspace_override`] refuses to edit, whatever it holds. +pub(crate) fn override_section_inline(text: &str) -> bool { + has_inline_overrides(&split_lines(text)) +} + /// Whether a pnpm-workspace.yaml may declare overrides that /// [`override_section_entries`] cannot read: the shapes /// [`check_workspace_override`] refuses to edit (a document that is not a diff --git a/crates/socket-patch-core/src/vex/discover/npm.rs b/crates/socket-patch-core/src/vex/discover/npm.rs index 7433f982b..0f3df4097 100644 --- a/crates/socket-patch-core/src/vex/discover/npm.rs +++ b/crates/socket-patch-core/src/vex/discover/npm.rs @@ -1175,6 +1175,18 @@ async fn confirm_pnpm_overrides( {PNPM_WORKSPACE} carries overrides the lock records", entries.join(", ") ) + } else if maps + .workspace_text + .as_deref() + .is_some_and(crate::vendor::pnpm_lock::override_section_inline) + { + // An empty inline mapping (one with entries is unreadable and + // never gets here): the re-run refuses to edit it. + format!( + "Take the empty inline `overrides:` out of {PNPM_WORKSPACE} (`socket-patch \ + vendor` does not edit an inline mapping), then re-run `socket-patch vendor` \ + and commit the files it changes" + ) } else { "Re-run `socket-patch vendor` to declare it again, and commit the files it changes" .to_string() @@ -5421,7 +5433,17 @@ mod tests { "pnpm-workspace.yaml", format!("packages:\n - '.'\n{empty}\n"), ); - assert_refs(&run(&q).await, &[]); + let out = run(&q).await; + assert_refs(&out, &[]); + // `vendor` refuses to edit an inline mapping, so the remedy + // says to take it out first. + assert!( + out.diagnostics[0] + .detail + .contains("Take the empty inline `overrides:` out of pnpm-workspace.yaml"), + "{empty}: {}", + out.diagnostics[0].detail + ); } // A CRLF checkout and a BOM read like their plain twins: the