aube_lockfile/lib.rs
1pub mod bun;
2pub mod dep_path_filename;
3pub mod graph_hash;
4pub mod merge;
5pub mod npm;
6mod override_match;
7pub mod pnpm;
8pub mod yarn;
9
10pub use merge::{MergeReport, merge_branch_lockfiles};
11
12use smallvec::SmallVec;
13use std::collections::{BTreeMap, BTreeSet};
14use std::path::{Path, PathBuf};
15
16/// Most npm packages declare zero or one entry in `os`, `cpu`,
17/// `libc`. Two inline `SmallVec` slots cover empty on construction
18/// (zero heap alloc) and one-entry push (still zero heap) for ~99%
19/// of lockfile entries.
20pub type PlatformList = SmallVec<[String; 2]>;
21
22/// Represents a resolved dependency graph from any lockfile format.
23#[derive(Debug, Clone, Default)]
24pub struct LockfileGraph {
25 /// Direct dependencies of the root project (and workspace packages).
26 /// Key: importer path (e.g., "." for root), Value: list of (name, version) pairs.
27 pub importers: BTreeMap<String, Vec<DirectDep>>,
28 /// All resolved packages.
29 pub packages: BTreeMap<String, LockedPackage>,
30 /// Per-graph settings that round-trip through the lockfile header
31 /// (pnpm v9's `settings:` block). Don't affect graph structure;
32 /// stamped into the YAML when writing and read back when parsing,
33 /// so subsequent installs see the same resolution-mode state.
34 pub settings: LockfileSettings,
35 /// Dependency overrides recorded in pnpm-lock.yaml's top-level
36 /// `overrides:` block. Map of raw selector key → version specifier
37 /// (or `npm:` alias). Keys are the user's verbatim selector
38 /// strings — bare name, `foo>bar`, `foo@<2`, `**/foo`, or any
39 /// combination. Round-tripped so subsequent installs can detect
40 /// override drift on a string-compare of the key+value without
41 /// re-running the resolver. The resolver parses these into
42 /// `override_rule::OverrideRule`s at the start of each resolve
43 /// pass.
44 pub overrides: BTreeMap<String, String>,
45 /// Names listed in the root manifest's `pnpm.ignoredOptionalDependencies`.
46 /// The resolver drops entries in this set from every `optionalDependencies`
47 /// map before enqueueing, matching pnpm's read-package hook. Round-tripped
48 /// through pnpm-lock.yaml's top-level `ignoredOptionalDependencies:` list
49 /// so drift detection can notice when the user edits the field.
50 pub ignored_optional_dependencies: BTreeSet<String>,
51 /// Per-package publish timestamps, keyed by canonical `name@version`
52 /// (no peer suffix). Round-trips through pnpm-lock.yaml's top-level
53 /// `time:` block so `--resolution-mode=time-based` can compute a
54 /// `publishedBy` cutoff from packages already in the lockfile
55 /// without re-fetching packuments.
56 pub times: BTreeMap<String, String>,
57 /// Optional dependencies the resolver intentionally skipped on the
58 /// platform that wrote this lockfile (either filtered by
59 /// `os`/`cpu`/`libc`, or named in
60 /// `pnpm.ignoredOptionalDependencies`). Keyed by importer path,
61 /// inner map is name → specifier captured from `package.json` at
62 /// resolve time.
63 ///
64 /// Drift detection uses this to distinguish "user just added a new
65 /// optional dep" (which is real drift) from "this optional was
66 /// already considered and consciously dropped on this platform"
67 /// (which is *not* drift). Without it, every `--frozen-lockfile`
68 /// install on a platform that skipped a fixture would hard-fail.
69 pub skipped_optional_dependencies: BTreeMap<String, BTreeMap<String, String>>,
70 /// Resolved catalog entries, mirroring pnpm v9's top-level
71 /// `catalogs:` block. Outer key is the catalog name (`default` for
72 /// the unnamed `catalog:` field in `pnpm-workspace.yaml`); inner key
73 /// is the package name. Each entry pairs the original specifier
74 /// from the workspace catalog with the version the resolver chose
75 /// for it. Round-tripped through the lockfile so drift detection
76 /// can fire when a catalog spec changes without re-resolving.
77 pub catalogs: BTreeMap<String, BTreeMap<String, CatalogEntry>>,
78 /// bun's top-level `configVersion` — a second format counter bun
79 /// added alongside `lockfileVersion` to track its own config-
80 /// schema changes. Only the bun parser/writer ever touches this;
81 /// other formats leave it `None`. Round-tripping the parsed
82 /// value keeps the writer from silently downgrading the field
83 /// (e.g. from `2` back to `1`) when bun bumps it in a future
84 /// release.
85 pub bun_config_version: Option<u32>,
86 /// Top-level `patchedDependencies:` block mirrored by bun 1.1+ and
87 /// pnpm 9+. Key: selector (`lodash@4.17.21`), value: relative patch
88 /// file path (`patches/lodash@4.17.21.patch`). Round-tripped
89 /// verbatim so a parse/write cycle doesn't silently drop user
90 /// patches from the lockfile.
91 pub patched_dependencies: BTreeMap<String, String>,
92 /// Top-level `trustedDependencies:` block (bun) — a package-name
93 /// allowlist for lifecycle script execution. Preserved so
94 /// re-emitting a bun.lock doesn't strip the allowlist and cause
95 /// subsequent installs to skip scripts the user explicitly
96 /// approved.
97 ///
98 /// Kept as a `Vec` (not a set) so bun's original order round-trips
99 /// byte-identically; bun emits the list in insertion order. The
100 /// parser is responsible for deduping if the source lockfile
101 /// carried a duplicate.
102 pub trusted_dependencies: Vec<String>,
103 /// Top-level lockfile fields that aren't explicitly modeled on
104 /// `LockfileGraph`. Populated by per-format parsers on best-effort
105 /// basis so the writer can re-emit blocks a future lockfile
106 /// version might add (or ones we haven't promoted to typed fields
107 /// yet) without silently stripping them on round-trip. Each
108 /// parser/writer is responsible for emitting values in its
109 /// format's native serialization.
110 pub extra_fields: BTreeMap<String, serde_json::Value>,
111 /// Per-workspace-importer extras keyed by importer path (`""` for
112 /// root in bun, `"."` for others). Stores anything in the
113 /// workspace entry the typed model doesn't capture so a parse/
114 /// write cycle doesn't drop fields the user (or bun) wrote there.
115 pub workspace_extra_fields: BTreeMap<String, BTreeMap<String, serde_json::Value>>,
116}
117
118/// One entry in a lockfile catalog: the workspace-declared range and the
119/// resolved version. Mirrors pnpm v9's `catalogs:` block exactly.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct CatalogEntry {
122 pub specifier: String,
123 pub version: String,
124}
125
126/// Per-graph settings that mirror pnpm v9's `settings:` header.
127/// Extend as more knobs become round-trip-aware.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct LockfileSettings {
130 /// pnpm's `auto-install-peers` — when false the resolver leaves
131 /// unmet peers alone (just warns) instead of dragging them in.
132 pub auto_install_peers: bool,
133 /// pnpm's `exclude-links-from-lockfile` — not yet honored by aube
134 /// but round-tripped for lockfile compatibility.
135 pub exclude_links_from_lockfile: bool,
136 /// pnpm's `lockfile-include-tarball-url` — when true the writer
137 /// emits the full registry tarball URL in each package's
138 /// `resolution.tarball:` field alongside `integrity:`. Makes the
139 /// lockfile self-contained so air-gapped installs don't need to
140 /// derive the URL from `.npmrc`. Round-tripped through the
141 /// `settings:` header so it survives parse/write cycles without
142 /// re-reading `.npmrc`.
143 pub lockfile_include_tarball_url: bool,
144}
145
146impl Default for LockfileSettings {
147 fn default() -> Self {
148 Self {
149 auto_install_peers: true,
150 exclude_links_from_lockfile: false,
151 lockfile_include_tarball_url: false,
152 }
153 }
154}
155
156/// A direct dependency of a workspace importer.
157#[derive(Debug, Clone)]
158pub struct DirectDep {
159 pub name: String,
160 /// The dep_path key in the lockfile (e.g., "is-odd@3.0.1")
161 pub dep_path: String,
162 pub dep_type: DepType,
163 /// The specifier as written in package.json at the time the lockfile was
164 /// generated (e.g., `"^4.17.0"`). Used by drift detection to compare against
165 /// the current manifest. Only populated by formats that record it
166 /// (pnpm-lock.yaml v9). `None` for npm/yarn/bun lockfiles.
167 pub specifier: Option<String>,
168}
169
170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
171pub enum DepType {
172 Production,
173 Dev,
174 Optional,
175}
176
177/// Non-registry source for a locked package.
178///
179/// When a package comes from a local path (via `file:` or `link:` in
180/// `package.json`) it doesn't have a tarball URL or integrity hash, so we
181/// record the source separately and let the linker materialize it
182/// on-the-fly.
183#[derive(Debug, Clone, PartialEq, Eq)]
184pub enum LocalSource {
185 /// `file:<dir>` — a directory on disk whose contents should be
186 /// hardlink-copied into the virtual store like a normal package.
187 /// Path is stored relative to the project root.
188 Directory(PathBuf),
189 /// `file:<tarball>` — a `.tgz` on disk, extracted into the virtual
190 /// store the same way we extract registry tarballs.
191 Tarball(PathBuf),
192 /// `link:<dir>` — a plain symlink into `node_modules/<name>`, never
193 /// materialized into the virtual store. Transitive deps are the
194 /// target's responsibility.
195 Link(PathBuf),
196 /// `git+https://`, `git+ssh://`, `github:user/repo`, etc. — a
197 /// remote git repo. Cloned at fetch time and imported like a
198 /// `file:` directory. `url` is the normalized clone URL (what
199 /// gets passed to `git clone`). `committish` is the user-written
200 /// ref after `#` (branch, tag, or commit; `None` means HEAD).
201 /// `resolved` is the 40-char commit SHA that `git ls-remote`
202 /// pinned the ref to — the lockfile records this so repeat
203 /// installs reproduce bit-for-bit.
204 Git(GitSource),
205 /// `https://example.com/pkg.tgz` — a remote tarball URL. Fetched
206 /// once at resolve time so the resolver can read the enclosed
207 /// `package.json` for version + transitive deps and pin the
208 /// sha512 integrity. `integrity` stays empty on freshly-parsed
209 /// specifiers and is filled in by the resolver after download.
210 RemoteTarball(RemoteTarballSource),
211}
212
213/// A remote tarball dependency spec. See [`LocalSource::RemoteTarball`].
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct RemoteTarballSource {
216 pub url: String,
217 pub integrity: String,
218}
219
220/// A git dependency spec. See [`LocalSource::Git`].
221#[derive(Debug, Clone, PartialEq, Eq)]
222pub struct GitSource {
223 pub url: String,
224 pub committish: Option<String>,
225 pub resolved: String,
226 /// pnpm `&path:/sub/dir` selector — when set, only this
227 /// subdirectory of the cloned repo is treated as the package
228 /// root. Stored without leading slash so dep_path hashes are
229 /// stable regardless of whether the user wrote `path:/x` or
230 /// `path:x`.
231 pub subpath: Option<String>,
232}
233
234impl LocalSource {
235 /// The original path (relative to the project root) the user wrote
236 /// in `package.json`. `None` for non-path sources like git.
237 pub fn path(&self) -> Option<&Path> {
238 match self {
239 LocalSource::Directory(p) | LocalSource::Tarball(p) | LocalSource::Link(p) => Some(p),
240 LocalSource::Git(_) | LocalSource::RemoteTarball(_) => None,
241 }
242 }
243
244 /// The protocol kind (`"file"` / `"link"` / `"git"` / `"url"`).
245 pub fn kind_str(&self) -> &'static str {
246 match self {
247 LocalSource::Directory(_) | LocalSource::Tarball(_) => "file",
248 LocalSource::Link(_) => "link",
249 LocalSource::Git(_) => "git",
250 LocalSource::RemoteTarball(_) => "url",
251 }
252 }
253
254 /// The path as a POSIX-style string with forward-slash separators.
255 /// `Path::display()` and `to_string_lossy()` honor the host's
256 /// separator (backslash on Windows), which would make `dep_path`
257 /// hashes and lockfile `specifier:` strings non-portable: the
258 /// same `file:./some/dir` would render as `some\dir` on Windows
259 /// and `some/dir` on Unix, producing two different hashes for
260 /// the same logical target. Always rendering with `/` keeps
261 /// lockfiles cross-platform identical.
262 pub fn path_posix(&self) -> String {
263 self.path()
264 .map(|p| p.to_string_lossy().replace('\\', "/"))
265 .unwrap_or_default()
266 }
267
268 /// Canonical specifier string as pnpm writes it in the `packages:`
269 /// and `snapshots:` keys (post-`<name>@` part). For `file:` /
270 /// `link:` this is `file:./vendor/foo` / `link:../sibling`. For
271 /// `git`, pnpm uses the resolved form `<url>#<commit>` (no
272 /// `git+` prefix) because the lockfile pins to the exact commit
273 /// regardless of what the user wrote. Always emits POSIX
274 /// separators so the resulting lockfile is portable.
275 pub fn specifier(&self) -> String {
276 match self {
277 LocalSource::Git(g) => match &g.subpath {
278 Some(sub) => format!("{}#{}&path:/{}", g.url, g.resolved, sub),
279 None => format!("{}#{}", g.url, g.resolved),
280 },
281 LocalSource::RemoteTarball(t) => t.url.clone(),
282 _ => format!("{}:{}", self.kind_str(), self.path_posix()),
283 }
284 }
285
286 /// Internal FS-safe dep_path used as the key in
287 /// `LockfileGraph.packages` and as the `.aube/` subdir name.
288 ///
289 /// Distinct paths must map to distinct keys (otherwise the
290 /// linker would silently mix files between two local packages),
291 /// and the result must be a single filesystem component — no
292 /// `/`, `\`, `:`, or `..`. Ad-hoc character substitution trips
293 /// over cases like `../vendor` vs `__/vendor` or `a.b` vs `a_b`
294 /// collapsing to the same string, so we hash the raw path bytes
295 /// and suffix the first 16 hex chars (64 bits — more than enough
296 /// to avoid collisions inside a single project).
297 ///
298 /// The hash input is the POSIX-form path string so a checked-in
299 /// lockfile resolves to the same key regardless of which
300 /// platform ran `aube install`.
301 pub fn dep_path(&self, name: &str) -> String {
302 use sha2::{Digest, Sha256};
303 let mut hasher = Sha256::new();
304 match self {
305 LocalSource::Git(g) => {
306 hasher.update(g.url.as_bytes());
307 hasher.update(b"#");
308 hasher.update(g.resolved.as_bytes());
309 if let Some(sub) = &g.subpath {
310 hasher.update(b"&path:/");
311 hasher.update(sub.as_bytes());
312 }
313 }
314 LocalSource::RemoteTarball(t) => {
315 hasher.update(t.url.as_bytes());
316 }
317 _ => hasher.update(self.path_posix().as_bytes()),
318 }
319 let digest = hasher.finalize();
320 let short: String = digest.iter().take(8).map(|b| format!("{b:02x}")).collect();
321 format!("{name}@{}+{short}", self.kind_str())
322 }
323
324 /// Classify a user-written `file:` / `link:` specifier against the
325 /// project root. Returns `None` if `spec` isn't a local specifier.
326 /// Resolves the target path relative to `project_root`; a `file:`
327 /// target that resolves to a `.tgz` / `.tar.gz` on disk is treated
328 /// as a tarball, anything else as a directory.
329 pub fn parse(spec: &str, project_root: &Path) -> Option<Self> {
330 // Check git first so URLs like `https://host/user/repo.git`
331 // aren't swallowed by the broader bare-http tarball check
332 // below.
333 if let Some((url, committish, subpath)) = parse_git_spec(spec) {
334 // `resolved` is filled in by the resolver after running
335 // `git ls-remote`. A lockfile round-trip that never
336 // re-resolves will leave this empty, which is the sentinel
337 // the resolver checks for before calling ls-remote.
338 return Some(LocalSource::Git(GitSource {
339 url,
340 committish,
341 resolved: String::new(),
342 subpath,
343 }));
344 }
345 // Any remaining bare `http(s)://` URL is a remote tarball.
346 // npm semantics treat *all* non-git HTTP URLs in a dependency
347 // value as tarball URLs, so services that serve tarballs from
348 // URLs without a `.tgz` extension (pkg.pr.new, GitHub
349 // codeload, etc.) classify correctly here.
350 if Self::looks_like_remote_tarball_url(spec) {
351 return Some(LocalSource::RemoteTarball(RemoteTarballSource {
352 url: spec.to_string(),
353 integrity: String::new(),
354 }));
355 }
356 let (kind, rest) = if let Some(r) = spec.strip_prefix("file:") {
357 ("file", r)
358 } else if let Some(r) = spec.strip_prefix("link:") {
359 ("link", r)
360 } else {
361 return None;
362 };
363 let rel = PathBuf::from(rest);
364 let abs = project_root.join(&rel);
365 if kind == "link" {
366 return Some(LocalSource::Link(rel));
367 }
368 if abs.is_file() && Self::path_looks_like_tarball(&rel) {
369 return Some(LocalSource::Tarball(rel));
370 }
371 Some(LocalSource::Directory(rel))
372 }
373
374 /// Whether a specifier looks like a direct HTTP(S) URL that should
375 /// be fetched as a tarball. Per npm semantics, *any* `http://` or
376 /// `https://` URL in a dependency value is a tarball URL — services
377 /// like pkg.pr.new, GitHub codeload, and private registries with
378 /// auth-token query strings serve tarballs from URLs that don't
379 /// carry a `.tgz` extension. Git URLs must already have been
380 /// ruled out by the caller (see [`parse_git_spec`]) so a
381 /// `.git`-suffixed URL doesn't get misclassified here.
382 pub fn looks_like_remote_tarball_url(spec: &str) -> bool {
383 spec.starts_with("https://") || spec.starts_with("http://")
384 }
385
386 pub fn path_looks_like_tarball(path: &Path) -> bool {
387 let name = match path.file_name().and_then(|n| n.to_str()) {
388 Some(n) => n,
389 None => return false,
390 };
391 let lower = name.to_ascii_lowercase();
392 lower.ends_with(".tgz") || lower.ends_with(".tar.gz")
393 }
394}
395
396/// Parse a git dependency specifier into `(clone_url, committish)`.
397///
398/// Recognized forms:
399/// - `git+https://host/user/repo.git[#ref]`
400/// - `git+ssh://git@host/user/repo.git[#ref]`
401/// - `git://host/user/repo.git[#ref]`
402/// - `https://host/user/repo.git[#ref]` (only when ending in `.git`)
403/// - `user@host:path[.git][#ref]` (scp-form, only for github.com / gitlab.com /
404/// bitbucket.org — matches pnpm 11 behavior, where unknown SCP hosts are
405/// treated as local paths) → `ssh://user@host/path[.git]`
406/// - `github:user/repo[#ref]` → `https://github.com/user/repo.git`
407/// - `gitlab:user/repo[#ref]` → `https://gitlab.com/user/repo.git`
408/// - `bitbucket:user/repo[#ref]` → `https://bitbucket.org/user/repo.git`
409///
410/// Returns `None` for any specifier that doesn't look like a git URL,
411/// so the caller can fall through to other protocol parsers.
412pub fn parse_git_spec(spec: &str) -> Option<(String, Option<String>, Option<String>)> {
413 let (body, committish, subpath) = match spec.find('#') {
414 Some(idx) => {
415 let (c, s) = parse_git_fragment(&spec[idx + 1..]);
416 (&spec[..idx], c, s)
417 }
418 None => (spec, None, None),
419 };
420 let is_bare_transport = body.starts_with("https://")
421 || body.starts_with("http://")
422 || body.starts_with("ssh://")
423 || body.starts_with("file://");
424 let url = if let Some(rest) = body.strip_prefix("git+") {
425 // `git+` explicitly tags the URL as git, so the `.git`
426 // suffix is optional (GitHub/GitLab accept both forms).
427 rest.to_string()
428 } else if body.starts_with("git://") {
429 body.to_string()
430 } else if let Some(scp) = parse_scp_url(body) {
431 scp
432 } else if let Some(path) = body.strip_prefix("github:") {
433 format!("https://github.com/{path}.git")
434 } else if let Some(path) = body.strip_prefix("gitlab:") {
435 format!("https://gitlab.com/{path}.git")
436 } else if let Some(path) = body.strip_prefix("bitbucket:") {
437 format!("https://bitbucket.org/{path}.git")
438 } else if is_bare_transport && body.ends_with(".git") {
439 body.to_string()
440 } else if is_bare_transport
441 && committish
442 .as_deref()
443 .is_some_and(|c| c.len() == 40 && c.chars().all(|ch| ch.is_ascii_hexdigit()))
444 {
445 // Lockfile round-trip form: `specifier()` writes the stored
446 // URL verbatim plus `#<sha>`. URLs that dropped the `git+`
447 // prefix (and happen to lack `.git`) are disambiguated from
448 // plain tarball URLs by the 40-hex committish suffix.
449 body.to_string()
450 } else {
451 return None;
452 };
453 Some((url, committish, subpath))
454}
455
456/// A git URL that maps to one of the three "hosted" providers npm /
457/// pnpm both special-case (github / gitlab / bitbucket). For these
458/// hosts a public read can be served as a flat HTTPS tarball over
459/// `codeload.github.com` (or each host's equivalent), bypassing `git`
460/// entirely. The lockfile's stored URL is canonical-identity only —
461/// pnpm and npm both re-derive the fetch URL from `(host, owner,
462/// repo)` on every install rather than dialing whatever scheme
463/// happens to be in `resolved:`.
464#[derive(Debug, Clone, PartialEq, Eq)]
465pub struct HostedGit {
466 pub host: HostedGitHost,
467 pub owner: String,
468 pub repo: String,
469}
470
471#[derive(Debug, Clone, Copy, PartialEq, Eq)]
472pub enum HostedGitHost {
473 GitHub,
474 GitLab,
475 Bitbucket,
476}
477
478impl HostedGit {
479 /// `https://github.com/<owner>/<repo>.git` — the form `git fetch`
480 /// can dial without an SSH key. Used as the runtime fetch URL when
481 /// the lockfile's stored URL is `git+ssh://git@…` (npm canonical
482 /// identity) but the actual install host has no SSH configured.
483 pub fn https_url(&self) -> String {
484 let host = self.host.host_domain();
485 format!("https://{host}/{}/{}.git", self.owner, self.repo)
486 }
487
488 /// `https://codeload.github.com/<owner>/<repo>/tar.gz/<sha>` (or
489 /// each host's equivalent) — a flat HTTPS tarball at the given
490 /// commit. Returns `None` unless `committish` is a 40-char hex
491 /// SHA, since the codeload path can't be verified after extraction
492 /// without `.git/` metadata. Branch / tag names round-trip through
493 /// `git ls-remote` to get pinned to a SHA first.
494 pub fn tarball_url(&self, committish: &str) -> Option<String> {
495 if committish.len() != 40 || !committish.chars().all(|c| c.is_ascii_hexdigit()) {
496 return None;
497 }
498 let sha = committish.to_ascii_lowercase();
499 Some(match self.host {
500 HostedGitHost::GitHub => format!(
501 "https://codeload.github.com/{}/{}/tar.gz/{sha}",
502 self.owner, self.repo
503 ),
504 HostedGitHost::GitLab => format!(
505 "https://gitlab.com/{}/{}/-/archive/{sha}/{}-{sha}.tar.gz",
506 self.owner, self.repo, self.repo
507 ),
508 HostedGitHost::Bitbucket => format!(
509 "https://bitbucket.org/{}/{}/get/{sha}.tar.gz",
510 self.owner, self.repo
511 ),
512 })
513 }
514}
515
516impl HostedGitHost {
517 fn from_domain(domain: &str) -> Option<Self> {
518 match domain {
519 "github.com" => Some(HostedGitHost::GitHub),
520 "gitlab.com" => Some(HostedGitHost::GitLab),
521 "bitbucket.org" => Some(HostedGitHost::Bitbucket),
522 _ => None,
523 }
524 }
525
526 pub fn host_domain(self) -> &'static str {
527 match self {
528 HostedGitHost::GitHub => "github.com",
529 HostedGitHost::GitLab => "gitlab.com",
530 HostedGitHost::Bitbucket => "bitbucket.org",
531 }
532 }
533}
534
535/// Parse a clone URL — in any form `parse_git_spec` accepts as input
536/// or produces as output — into its `(host, owner, repo)` components,
537/// when the host is one of the three providers npm / pnpm route
538/// through HTTPS tarballs. Returns `None` for any other host (including
539/// self-hosted GitLab / Gitea / Bitbucket Data Center): those still
540/// need a real `git clone` because no codeload-style HTTP archive is
541/// available.
542///
543/// Accepts:
544/// - `https://github.com/owner/repo[.git]`
545/// - `git+https://github.com/owner/repo[.git]`
546/// - `git://github.com/owner/repo[.git]`
547/// - `ssh://git@github.com/owner/repo[.git]`
548/// - `git+ssh://git@github.com/owner/repo[.git]` (npm canonical lockfile form)
549/// - `git@github.com:owner/repo[.git]` (scp shorthand, in case a caller
550/// parses raw lockfile fields without going through `parse_git_spec`)
551pub fn parse_hosted_git(url: &str) -> Option<HostedGit> {
552 let body = url.strip_prefix("git+").unwrap_or(url);
553 let after_scheme = if let Some(rest) = body.strip_prefix("https://") {
554 rest
555 } else if let Some(rest) = body.strip_prefix("http://") {
556 rest
557 } else if let Some(rest) = body.strip_prefix("ssh://") {
558 rest
559 } else if let Some(rest) = body.strip_prefix("git://") {
560 rest
561 } else {
562 // scp shorthand `user@host:path` — not produced by parse_git_spec
563 // but accepted defensively in case a raw lockfile string ever
564 // bypasses it.
565 let scp_path = parse_scp_url(body)?;
566 return parse_hosted_git(&scp_path);
567 };
568 // Strip optional `user@` (always `git@` for hosted forms).
569 let host_and_path = match after_scheme.split_once('@') {
570 Some((_, rest)) => rest,
571 None => after_scheme,
572 };
573 let (host, path) = host_and_path.split_once('/')?;
574 let host = HostedGitHost::from_domain(host)?;
575 // Take exactly two path segments: owner and repo. Anything beyond
576 // (subgroup-style GitLab paths) doesn't have a stable HTTPS tarball
577 // form on the three providers we care about, so refuse and let the
578 // caller fall back to clone.
579 let mut segs = path.splitn(3, '/');
580 let owner = segs.next()?;
581 let repo = segs.next()?;
582 if owner.is_empty() || repo.is_empty() || segs.next().is_some() {
583 return None;
584 }
585 let repo = repo
586 .strip_suffix(".git")
587 .unwrap_or(repo)
588 .trim_end_matches('/');
589 if repo.is_empty() {
590 return None;
591 }
592 Some(HostedGit {
593 host,
594 owner: owner.to_string(),
595 repo: repo.to_string(),
596 })
597}
598
599fn parse_scp_url(body: &str) -> Option<String> {
600 if body.contains("://") {
601 return None;
602 }
603 let colon = body.find(':')?;
604 let before = &body[..colon];
605 let path = &body[colon + 1..];
606 if before.is_empty() || path.is_empty() {
607 return None;
608 }
609 if path.starts_with('/') {
610 return None;
611 }
612 let at = before.find('@')?;
613 let user = &before[..at];
614 let host = &before[at + 1..];
615 if user.is_empty() || host.is_empty() || host.contains('/') || host.contains('@') {
616 return None;
617 }
618 // pnpm 11 only resolves SCP-form as hosted Git for the three known
619 // providers; other hosts (e.g. `git@example.com:foo/bar.git`) are
620 // treated as local paths, and `host:path` without a user errors.
621 if !matches!(host, "github.com" | "gitlab.com" | "bitbucket.org") {
622 return None;
623 }
624 Some(format!("ssh://{user}@{host}/{path}"))
625}
626
627/// Normalize git URL fragments used by npm-compatible lockfiles.
628///
629/// Plain git accepts `#<ref>`, while npm and Yarn Berry also write
630/// key/value fragments such as `#commit=<sha>` for pinned git deps.
631/// Downstream code passes this value directly to `git ls-remote` and
632/// `git checkout`, so strip the selector key here and keep only the
633/// actual ref name or SHA.
634pub(crate) fn normalize_git_fragment(fragment: &str) -> Option<String> {
635 parse_git_fragment(fragment).0
636}
637
638/// Parse a git URL fragment into `(committish, subpath)`. Handles the
639/// pnpm/hosted-git-info form `<ref>&path:/sub/dir` (the `path:` key
640/// uses a colon, not `=`, by historical convention) as well as the
641/// `key=value` form npm/Yarn Berry write. Unknown selectors are
642/// ignored. Subpath is returned without leading slash so the caller
643/// can join it with a clone dir without tripping the absolute-path
644/// branch of `Path::join`.
645pub(crate) fn parse_git_fragment(fragment: &str) -> (Option<String>, Option<String>) {
646 if fragment.is_empty() {
647 return (None, None);
648 }
649
650 let mut fallback: Option<&str> = None;
651 let mut preferred: Option<&str> = None;
652 let mut subpath: Option<String> = None;
653 for part in fragment.split('&') {
654 if part.is_empty() {
655 continue;
656 }
657 // Try `key=value` first; fall back to `key:value` only for
658 // the small set of selectors we actually handle below. A tag
659 // name with a colon (e.g. `release:2026-01`) is left alone —
660 // and `semver:^1.0.0` stays as a literal ref so `ls-remote`
661 // surfaces an explicit error rather than silently HEAD-ing.
662 let split = part.split_once('=').or_else(|| {
663 part.split_once(':')
664 .filter(|(k, _)| matches!(*k, "commit" | "tag" | "head" | "branch" | "path"))
665 });
666 let (key, value) = split.unwrap_or(("", part));
667 if value.is_empty() {
668 continue;
669 }
670 match key {
671 "commit" => {
672 preferred.get_or_insert(value);
673 }
674 "tag" | "head" | "branch" => {
675 fallback.get_or_insert(value);
676 }
677 "path" => {
678 // Strip leading slashes (pnpm writes `path:/sub`) and
679 // reject any `..` / `.` component. Without this, a
680 // crafted spec like `&path:/../../etc` would let the
681 // resolver and installer escape the clone dir and
682 // import an arbitrary host directory into the store.
683 if subpath.is_some() {
684 // First-wins, matching the other selectors above.
685 continue;
686 }
687 let trimmed = value.trim_start_matches('/');
688 if trimmed.is_empty() {
689 continue;
690 }
691 if trimmed
692 .split('/')
693 .any(|c| c.is_empty() || c == "." || c == "..")
694 {
695 continue;
696 }
697 subpath = Some(trimmed.to_string());
698 }
699 "" => {
700 fallback.get_or_insert(value);
701 }
702 _ => {}
703 }
704 }
705
706 (preferred.or(fallback).map(ToString::to_string), subpath)
707}
708
709/// A single resolved package in the lockfile.
710///
711/// The `dependencies` map keys are dep names and values are the dependency's
712/// dep_path *tail* — i.e. the string that follows `<name>@`. For a plain
713/// package this is just the version (`"4.17.21"`); for a package with its
714/// own peer context it includes the suffix (`"18.2.0(prop-types@15.8.1)"`).
715/// Combining the key with its value reproduces the full dep_path (which is
716/// also the key in `LockfileGraph.packages`).
717#[derive(Debug, Clone, Default)]
718pub struct LockedPackage {
719 /// Package name (e.g., "lodash")
720 pub name: String,
721 /// Exact resolved version (e.g., "4.17.21")
722 pub version: String,
723 /// Integrity hash (e.g., "sha512-...")
724 pub integrity: Option<String>,
725 /// Dependencies of this package (name -> dep_path tail, see struct docs)
726 pub dependencies: BTreeMap<String, String>,
727 /// Optional dependency edges for this package. Active optional edges are
728 /// also mirrored in `dependencies` so graph walks and the linker continue
729 /// to see them; this separate map lets platform filtering prune optional
730 /// edges without touching regular dependencies.
731 pub optional_dependencies: BTreeMap<String, String>,
732 /// Peer dependency ranges as *declared* by the package (from its
733 /// package.json / packument). These are the constraints; the resolved
734 /// versions live in `dependencies` after the peer-context pass runs.
735 pub peer_dependencies: BTreeMap<String, String>,
736 /// `peerDependenciesMeta` entries, keyed by peer name.
737 pub peer_dependencies_meta: BTreeMap<String, PeerDepMeta>,
738 /// The dep_path key used in the lockfile. For packages with resolved
739 /// peer contexts this includes the suffix, e.g.
740 /// `"styled-components@6.1.0(react@18.2.0)"`.
741 pub dep_path: String,
742 /// Set for non-registry packages (those installed via `file:` or
743 /// `link:` specifiers). `None` for the common case of a package
744 /// resolved from an npm registry, where `integrity` is the full
745 /// record of where the bits came from.
746 pub local_source: Option<LocalSource>,
747 /// `os` / `cpu` / `libc` arrays from the package's manifest. Used
748 /// by the resolver to filter optional deps that can't run on the
749 /// current (or user-overridden) platform. Empty arrays mean no
750 /// constraint.
751 pub os: PlatformList,
752 pub cpu: PlatformList,
753 pub libc: PlatformList,
754 /// Names declared in the package's own `bundledDependencies`. These
755 /// ship inside the parent tarball's `node_modules/`, so the resolver
756 /// neither fetches nor recurses into them, and the linker avoids
757 /// creating sibling symlinks that would shadow the bundled tree.
758 /// An empty Vec means "no bundled deps"; `None` is kept as a
759 /// distinct value only inside the resolver and collapsed to empty
760 /// here because the lockfile round-trip doesn't need to preserve
761 /// the "unset" vs "empty list" distinction.
762 pub bundled_dependencies: Vec<String>,
763 /// Full registry tarball URL for registry-sourced packages. Only
764 /// populated when `LockfileSettings::lockfile_include_tarball_url`
765 /// is active on this graph; otherwise `None` and the lockfile
766 /// writer derives the URL at fetch time from the configured
767 /// registry. `local_source`-backed packages (file:, link:, git:,
768 /// remote tarball) already carry their own URL via `LocalSource`
769 /// and don't populate this field.
770 pub tarball_url: Option<String>,
771 /// For npm-alias deps (`"h3-v2": "npm:h3@2.0.1-rc.20"`): the real
772 /// package name on the registry (`"h3"`). `None` means the entry
773 /// is not aliased and `name` already holds the registry name.
774 ///
775 /// Install semantics when `Some(real)`:
776 /// - `name` is the *alias* — that's the folder under `node_modules/`,
777 /// the symlink name for transitive deps, and the key every package
778 /// that declares this dep refers to.
779 /// - `alias_of` is the real package name used for tarball URL lookup,
780 /// store index keying, and packument fetches.
781 /// - `version` is the real resolved version.
782 ///
783 /// `registry_name()` returns the right name for registry IO; every
784 /// call site that talks to the registry or the CAS uses that helper.
785 pub alias_of: Option<String>,
786 /// Yarn berry's `checksum:` field, preserved verbatim when parsing a
787 /// yarn 2+ lockfile (e.g. `"10c0/<blake2b-hex>"`). The format is
788 /// yarn-specific — it uses a yarn-chosen hash family prefixed with
789 /// the `cacheKey` that produced it — and doesn't share a hash
790 /// algorithm with `integrity` (sha-512). When re-emitting a yarn
791 /// berry lockfile we write this field back as-is; packages that
792 /// didn't come through a berry parse (e.g. freshly-resolved entries
793 /// in a new install) leave this `None` and the writer omits the
794 /// `checksum:` field, which berry tolerates at the default
795 /// `checksumBehavior: throw` when the cache is fresh.
796 pub yarn_checksum: Option<String>,
797 /// `engines:` from the package's manifest, round-tripped through
798 /// the lockfile so pnpm-style writers can emit the same flow-form
799 /// `engines: {node: '>=8'}` line pnpm writes. Empty map means
800 /// "no engines declared" — the writer skips the field entirely.
801 pub engines: BTreeMap<String, String>,
802 /// `bin:` map from the package's manifest, normalized to
803 /// `name → path`. An empty map means "no bins declared".
804 ///
805 /// pnpm-style writers derive `hasBin: true` from
806 /// `!bin.is_empty()` (they don't preserve the names/paths); bun's
807 /// format emits the full map on the package's meta block. Keeping
808 /// the map here lets both writers render byte-identical output
809 /// without an extra tarball-level re-parse.
810 pub bin: BTreeMap<String, String>,
811 /// Dependency ranges as declared in this package's own
812 /// `package.json` — keyed by dep name, values are the raw
813 /// specifiers (`"^4.1.0"`, `"~1.1.4"`, `"workspace:*"`, …).
814 ///
815 /// Distinct from [`Self::dependencies`], which stores the
816 /// *resolved* dep_path tail (`"4.3.0"`). npm / yarn / bun
817 /// lockfiles preserve the declared ranges on every nested
818 /// package entry — rewriting them to the resolved pins is the
819 /// biggest source of round-trip churn against those formats. This
820 /// map lets writers emit the declared range when available and
821 /// fall back to the resolved pin otherwise (e.g. when the source
822 /// lockfile was pnpm, whose `snapshots:` only carries pins).
823 ///
824 /// Empty means "unknown" — writers should fall back to pins.
825 /// Covers production *and* optional dependencies in one map since
826 /// a package can't declare the same name twice across those
827 /// sections.
828 pub declared_dependencies: BTreeMap<String, String>,
829 /// Package's `license` field, collapsed to the simple string
830 /// form. Round-tripped so npm's lockfile keeps its per-entry
831 /// `"license": "MIT"` line; pnpm / yarn / bun don't record
832 /// licenses and leave this `None` on parse.
833 pub license: Option<String>,
834 /// Package's funding URL, extracted from whatever shape the
835 /// manifest's `funding:` field took (string / object / array).
836 /// Round-tripped so npm's lockfile keeps its per-entry
837 /// `"funding": {"url": "…"}` block.
838 pub funding_url: Option<String>,
839 /// pnpm `snapshots:` `optional: true` flag, marking a package
840 /// reachable only through optional edges (typically platform-
841 /// specific binaries like `@reflink/reflink-darwin-arm64`). pnpm
842 /// uses this on the next install to decide whether the entry
843 /// should be skipped on a non-matching platform; dropping it on
844 /// round-trip would let pnpm treat the package as required.
845 /// Always `false` outside the pnpm parse/write path.
846 pub optional: bool,
847 /// pnpm `snapshots:` `transitivePeerDependencies:` list — peer
848 /// names that bubble up transitively through this package. pnpm
849 /// reads it during hoisting and as a resolver staleness signal
850 /// (`resolveDependencies.ts`'s non-zero-length check); a missing
851 /// list looks like a graph change and triggers needless re-
852 /// resolution on the next pnpm install. Empty outside the pnpm
853 /// parse/write path. Fresh resolves leave this empty too — pnpm
854 /// recomputes it from the graph during `resolvePeers` when needed.
855 pub transitive_peer_dependencies: Vec<String>,
856 /// Per-package-meta extras preserved verbatim from the source
857 /// lockfile. Captures fields the typed model doesn't yet cover
858 /// (`deprecated`, `hasInstallScript`, bun's `optionalPeers`, and
859 /// anything a future lockfile bump adds) so a parse/write cycle
860 /// doesn't drop them. Each format's writer re-emits what makes
861 /// sense there — bun inlines the extras back on the package-entry
862 /// meta object, pnpm / yarn / npm currently ignore them.
863 pub extra_meta: BTreeMap<String, serde_json::Value>,
864}
865
866impl LockedPackage {
867 /// The package name to use for registry / store operations — the real
868 /// name behind an npm-alias when aliased, otherwise just `name`. Used
869 /// at every site that derives a tarball URL, a packument URL, or an
870 /// aube-store cache key so aliased entries hit the actual package
871 /// instead of the alias-qualified name.
872 pub fn registry_name(&self) -> &str {
873 self.alias_of.as_deref().unwrap_or(&self.name)
874 }
875
876 /// Canonical `"name@version"` key used as a handle in patches,
877 /// approve-builds prompts, lockfile canonical maps, and display
878 /// paths. Not the dep-path — that includes peer-context suffixes.
879 pub fn spec_key(&self) -> String {
880 format!("{}@{}", self.name, self.version)
881 }
882}
883
884/// Metadata about a single declared peer dependency. Matches the shape of
885/// `peerDependenciesMeta` in package.json.
886#[derive(Debug, Clone, Default, PartialEq, Eq)]
887pub struct PeerDepMeta {
888 /// When true, an unmet peer is silently allowed rather than warned about.
889 pub optional: bool,
890}
891
892/// Which source lockfile format was parsed.
893#[derive(Debug, Clone, Copy, PartialEq, Eq)]
894pub enum LockfileKind {
895 /// `aube-lock.yaml` — aube's default lockfile when no existing
896 /// lockfile is present. Same on-disk format as pnpm v9 for now
897 /// (we piggyback on pnpm::read/write).
898 Aube,
899 /// `pnpm-lock.yaml` — pnpm v9 format. If this is the existing
900 /// project lockfile, aube reads and writes it in place.
901 Pnpm,
902 Npm,
903 /// `yarn.lock` v1 (classic yarn). Line-based text format with
904 /// 2-space indented fields.
905 Yarn,
906 /// `yarn.lock` v2+ (yarn berry). YAML format with `__metadata:`
907 /// header, `resolution:` / `checksum:` fields, and
908 /// `languageName` / `linkType`. Same filename as `Yarn`; detection
909 /// peeks at the content for the `__metadata:` marker to pick
910 /// between the two.
911 YarnBerry,
912 NpmShrinkwrap,
913 Bun,
914}
915
916impl LockfileKind {
917 pub fn filename(self) -> &'static str {
918 match self {
919 LockfileKind::Aube => "aube-lock.yaml",
920 LockfileKind::Pnpm => "pnpm-lock.yaml",
921 LockfileKind::Npm => "package-lock.json",
922 LockfileKind::Yarn | LockfileKind::YarnBerry => "yarn.lock",
923 LockfileKind::NpmShrinkwrap => "npm-shrinkwrap.json",
924 LockfileKind::Bun => "bun.lock",
925 }
926 }
927}
928
929impl LockfileGraph {
930 /// Get all direct dependencies of the root project.
931 pub fn root_deps(&self) -> &[DirectDep] {
932 self.importers.get(".").map(|v| v.as_slice()).unwrap_or(&[])
933 }
934
935 /// Get a package by its dep_path key.
936 pub fn get_package(&self, dep_path: &str) -> Option<&LockedPackage> {
937 self.packages.get(dep_path)
938 }
939
940 /// BFS the transitive closure of `roots` through `self.packages`,
941 /// returning every reachable dep_path (roots included). Missing
942 /// roots are skipped silently — a root without a matching package
943 /// is treated as a leaf, which matches what `filter_deps` /
944 /// `subset_to_importer` need when a retained importer points at a
945 /// package that was never fully installed (e.g. optional deps
946 /// filtered out on this platform).
947 ///
948 /// `LockedPackage.dependencies` maps `child_name → dep_path tail`,
949 /// so each child's full key reconstructs as `{child_name}@{tail}`.
950 fn transitive_closure<'a>(
951 &self,
952 roots: impl IntoIterator<Item = &'a str>,
953 ) -> std::collections::HashSet<String> {
954 let mut reachable: std::collections::HashSet<String> = std::collections::HashSet::new();
955 let mut queue: std::collections::VecDeque<String> = std::collections::VecDeque::new();
956 for root in roots {
957 if reachable.insert(root.to_string()) {
958 queue.push_back(root.to_string());
959 }
960 }
961 while let Some(dep_path) = queue.pop_front() {
962 let Some(pkg) = self.packages.get(&dep_path) else {
963 continue;
964 };
965 for (child_name, child_version) in &pkg.dependencies {
966 let child_key = format!("{child_name}@{child_version}");
967 if reachable.insert(child_key.clone()) {
968 queue.push_back(child_key);
969 }
970 }
971 }
972 reachable
973 }
974
975 /// Clone only the `packages` entries whose keys are in `reachable`.
976 /// Paired with `transitive_closure` to produce the pruned
977 /// `LockfileGraph.packages` for `filter_deps` / `subset_to_importer`.
978 fn packages_restricted_to(
979 &self,
980 reachable: &std::collections::HashSet<String>,
981 ) -> BTreeMap<String, LockedPackage> {
982 self.packages
983 .iter()
984 .filter(|(dep_path, _)| reachable.contains(*dep_path))
985 .map(|(k, v)| (k.clone(), v.clone()))
986 .collect()
987 }
988
989 /// Produce a new `LockfileGraph` containing only the direct deps that match
990 /// `keep` and the transitive deps reachable from them.
991 ///
992 /// Used by `install --prod` to drop `DepType::Dev` roots and everything
993 /// only reachable through them, and by `install --no-optional` for optional
994 /// deps. The filter runs over every importer's direct-dep list, so workspace
995 /// projects behave correctly.
996 ///
997 /// Packages that are reachable from a retained root through a transitive
998 /// chain are kept even if a pruned dev dep also happened to depend on them —
999 /// the check is "is this package reachable from any retained root?", not
1000 /// "was this package introduced by a retained root?".
1001 pub fn filter_deps<F>(&self, keep: F) -> LockfileGraph
1002 where
1003 F: Fn(&DirectDep) -> bool,
1004 {
1005 // Filter each importer's DirectDep list.
1006 let importers: BTreeMap<String, Vec<DirectDep>> = self
1007 .importers
1008 .iter()
1009 .map(|(path, deps)| {
1010 let filtered: Vec<DirectDep> = deps.iter().filter(|d| keep(d)).cloned().collect();
1011 (path.clone(), filtered)
1012 })
1013 .collect();
1014
1015 // BFS from every retained root across every importer.
1016 let reachable = self.transitive_closure(
1017 importers
1018 .values()
1019 .flat_map(|deps| deps.iter().map(|d| d.dep_path.as_str())),
1020 );
1021 let packages = self.packages_restricted_to(&reachable);
1022
1023 LockfileGraph {
1024 importers,
1025 packages,
1026 // Preserve the source graph's settings — filter is a
1027 // structural operation, not a resolution-mode reset.
1028 // Writing the filtered graph (e.g. from `aube prune`) must
1029 // emit the same `settings:` header the user chose.
1030 settings: self.settings.clone(),
1031 // Overrides are part of the user's resolution intent and
1032 // should survive structural filters like `aube prune`.
1033 overrides: self.overrides.clone(),
1034 ignored_optional_dependencies: self.ignored_optional_dependencies.clone(),
1035 // Times follow the same round-trip invariant as settings:
1036 // filter doesn't change what versions are locked, so the
1037 // per-package publish timestamps carry through unchanged.
1038 times: self.times.clone(),
1039 skipped_optional_dependencies: self.skipped_optional_dependencies.clone(),
1040 catalogs: self.catalogs.clone(),
1041 bun_config_version: self.bun_config_version,
1042 patched_dependencies: self.patched_dependencies.clone(),
1043 trusted_dependencies: self.trusted_dependencies.clone(),
1044 extra_fields: self.extra_fields.clone(),
1045 workspace_extra_fields: self.workspace_extra_fields.clone(),
1046 }
1047 }
1048
1049 /// Produce a new `LockfileGraph` rooted at the importer at
1050 /// `importer_path`, with its transitive closure preserved and every
1051 /// other importer dropped. The retained importer is remapped to
1052 /// `"."` because the consumer installs the result as a standalone
1053 /// project.
1054 ///
1055 /// Used by `aube deploy`: reading the source workspace lockfile
1056 /// and subsetting it to the deployed package lets a frozen install
1057 /// in the target reproduce the workspace's exact versions without
1058 /// re-resolving against the registry. `keep` filters the importer's
1059 /// direct deps the same way `filter_deps` does, so `--prod` /
1060 /// `--dev` / `--no-optional` deploys drop the matching roots.
1061 ///
1062 /// Returns `None` if `importer_path` is not present in
1063 /// `self.importers`. Graph-wide metadata (`settings`, `overrides`,
1064 /// `times`, `catalogs`, `ignored_optional_dependencies`) is copied
1065 /// verbatim — structural pruning, not a resolution-mode reset.
1066 /// Callers targeting a non-workspace install may want to clear
1067 /// workspace-scope fields that would otherwise trigger drift
1068 /// detection against a rewritten target manifest.
1069 pub fn subset_to_importer<F>(&self, importer_path: &str, keep: F) -> Option<LockfileGraph>
1070 where
1071 F: Fn(&DirectDep) -> bool,
1072 {
1073 let src_deps = self.importers.get(importer_path)?;
1074 let kept: Vec<DirectDep> = src_deps.iter().filter(|d| keep(d)).cloned().collect();
1075
1076 // BFS the transitive closure from retained roots, scoped to
1077 // just this importer's kept direct deps.
1078 let reachable = self.transitive_closure(kept.iter().map(|d| d.dep_path.as_str()));
1079 let packages = self.packages_restricted_to(&reachable);
1080
1081 // Per-importer metadata: keep only the retained importer's
1082 // entry, rekeyed to `.`. The source workspace's other
1083 // importers are meaningless in a target that has exactly one.
1084 let mut skipped_optional_dependencies = BTreeMap::new();
1085 if let Some(skipped) = self.skipped_optional_dependencies.get(importer_path) {
1086 skipped_optional_dependencies.insert(".".to_string(), skipped.clone());
1087 }
1088
1089 let mut importers = BTreeMap::new();
1090 importers.insert(".".to_string(), kept);
1091
1092 Some(LockfileGraph {
1093 importers,
1094 packages,
1095 settings: self.settings.clone(),
1096 overrides: self.overrides.clone(),
1097 ignored_optional_dependencies: self.ignored_optional_dependencies.clone(),
1098 times: self.times.clone(),
1099 skipped_optional_dependencies,
1100 catalogs: self.catalogs.clone(),
1101 bun_config_version: self.bun_config_version,
1102 patched_dependencies: self.patched_dependencies.clone(),
1103 trusted_dependencies: self.trusted_dependencies.clone(),
1104 extra_fields: self.extra_fields.clone(),
1105 workspace_extra_fields: self.workspace_extra_fields.clone(),
1106 })
1107 }
1108
1109 /// Overlay per-package metadata fields from `prior` onto `self`
1110 /// for every `(name, version)` that survives in both graphs.
1111 /// Carries forward only fields the abbreviated packument (npm
1112 /// corgi) doesn't ship — `license`, `funding_url`, and the
1113 /// bun-format `configVersion` — so a fresh re-resolve against
1114 /// the same spec set doesn't lose them.
1115 ///
1116 /// Keyed by canonical `name@version`, so a peer-context rewrite
1117 /// between the old and new graph still lines up. `self`'s own
1118 /// values win when set (fresh registry data is authoritative);
1119 /// `prior`'s fill in only the `None` / empty slots. Safe to call
1120 /// on any pair of graphs — parsing the old lockfile is the
1121 /// caller's concern.
1122 pub fn overlay_metadata_from(&mut self, prior: &LockfileGraph) {
1123 // Build a canonical `name@version → prior pkg` lookup once so
1124 // repeated peer-context variants in `self.packages` all hit
1125 // the same prior entry.
1126 let prior_index = build_canonical_map(prior);
1127 for pkg in self.packages.values_mut() {
1128 let key = pkg.spec_key();
1129 let Some(prior_pkg) = prior_index.get(&key) else {
1130 continue;
1131 };
1132 if pkg.license.is_none() && prior_pkg.license.is_some() {
1133 pkg.license = prior_pkg.license.clone();
1134 }
1135 if pkg.funding_url.is_none() && prior_pkg.funding_url.is_some() {
1136 pkg.funding_url = prior_pkg.funding_url.clone();
1137 }
1138 // Per-entry extras (`deprecated`, `optionalPeers`,
1139 // format-specific fields bun/npm/yarn wrote into the
1140 // meta block) can't be recovered from a fresh resolve,
1141 // so carry them forward when the newer graph doesn't
1142 // already carry its own. `self`-side keys always win.
1143 for (k, v) in &prior_pkg.extra_meta {
1144 pkg.extra_meta.entry(k.clone()).or_insert_with(|| v.clone());
1145 }
1146 }
1147 if self.bun_config_version.is_none() {
1148 self.bun_config_version = prior.bun_config_version;
1149 }
1150 if self.patched_dependencies.is_empty() {
1151 self.patched_dependencies = prior.patched_dependencies.clone();
1152 }
1153 if self.trusted_dependencies.is_empty() {
1154 self.trusted_dependencies = prior.trusted_dependencies.clone();
1155 }
1156 if self.extra_fields.is_empty() {
1157 self.extra_fields = prior.extra_fields.clone();
1158 }
1159 if self.workspace_extra_fields.is_empty() {
1160 self.workspace_extra_fields = prior.workspace_extra_fields.clone();
1161 }
1162 }
1163
1164 /// Compare this lockfile's root importer against a single manifest.
1165 ///
1166 /// Mirrors pnpm's `prefer-frozen-lockfile` check: a lockfile is "fresh" iff
1167 /// every direct dep specifier in `package.json` exactly matches the specifier
1168 /// recorded in the lockfile (string compare, not semver). Used to decide
1169 /// whether to skip resolution and trust the lockfile (`Fresh`) or fall back
1170 /// to a full re-resolve (`Stale { reason }`).
1171 ///
1172 /// For workspace projects, use [`check_drift_workspace`] instead — this
1173 /// method only inspects the root importer.
1174 ///
1175 /// `workspace_overrides` is the `overrides:` block from
1176 /// `pnpm-workspace.yaml` (pnpm v10 moved overrides there). Pass an
1177 /// empty map when the project has no workspace-yaml overrides. Keys
1178 /// are merged on top of `manifest.overrides_map()` before the drift
1179 /// comparison, matching the resolver's effective-override set —
1180 /// otherwise a lockfile written with a workspace override
1181 /// immediately looks stale on the next `--frozen-lockfile` run.
1182 ///
1183 /// `workspace_ignored_optional` is the same idea for
1184 /// `pnpm-workspace.yaml`'s `ignoredOptionalDependencies` block:
1185 /// the resolver unions it with the manifest's list, so the drift
1186 /// check has to see the same union or a freshly-written lockfile
1187 /// immediately reads as stale.
1188 ///
1189 /// `workspace_catalogs` is the `catalog:` / `catalogs:` block from
1190 /// `pnpm-workspace.yaml`. pnpm resolves `catalog:` references in
1191 /// override values against this map before writing the lockfile
1192 /// and before comparing on re-install, so both sides of the drift
1193 /// check have to see the catalog-resolved form — otherwise a
1194 /// `"lodash": "catalog:"` override reads as stale against a
1195 /// lockfile that recorded the resolved `"lodash": "4.17.21"`.
1196 ///
1197 /// Lockfile formats that don't record specifiers (npm, yarn, bun) always
1198 /// return `Fresh` since we have no way to detect drift without re-resolving.
1199 ///
1200 /// [`check_drift_workspace`]: Self::check_drift_workspace
1201 pub fn check_drift(
1202 &self,
1203 manifest: &aube_manifest::PackageJson,
1204 workspace_overrides: &BTreeMap<String, String>,
1205 workspace_ignored_optional: &[String],
1206 workspace_catalogs: &BTreeMap<String, BTreeMap<String, String>>,
1207 ) -> DriftStatus {
1208 let effective = resolve_catalog_refs_in_overrides(
1209 &merge_manifest_and_workspace_overrides(manifest, workspace_overrides),
1210 workspace_catalogs,
1211 );
1212 let locked = resolve_catalog_refs_in_overrides(&self.overrides, workspace_catalogs);
1213 if let Some(reason) = overrides_drift_reason(&locked, &effective) {
1214 return DriftStatus::Stale { reason };
1215 }
1216 let mut effective_ignored = manifest.pnpm_ignored_optional_dependencies();
1217 effective_ignored.extend(workspace_ignored_optional.iter().cloned());
1218 if let Some(reason) =
1219 ignored_optional_drift_reason(&self.ignored_optional_dependencies, &effective_ignored)
1220 {
1221 return DriftStatus::Stale { reason };
1222 }
1223 self.check_drift_for_importer(".", manifest, &effective)
1224 }
1225
1226 /// Workspace-aware drift check.
1227 ///
1228 /// Each entry in `manifests` is `(importer_path, manifest)` — for example
1229 /// `(".", root_manifest), ("packages/app", app_manifest), ...`. Every
1230 /// importer is checked against its own manifest; the first stale importer
1231 /// determines the result.
1232 ///
1233 /// See [`check_drift`] for the `workspace_overrides` contract.
1234 ///
1235 /// [`check_drift`]: Self::check_drift
1236 pub fn check_drift_workspace(
1237 &self,
1238 manifests: &[(String, aube_manifest::PackageJson)],
1239 workspace_overrides: &BTreeMap<String, String>,
1240 workspace_ignored_optional: &[String],
1241 workspace_catalogs: &BTreeMap<String, BTreeMap<String, String>>,
1242 ) -> DriftStatus {
1243 // Override drift is checked once at the workspace level, against
1244 // the root manifest. Workspace-package manifests may declare
1245 // their own `overrides` blocks but pnpm only honors the root's,
1246 // so we mirror that here.
1247 let effective_overrides = match manifests.iter().find(|(p, _)| p == ".") {
1248 Some((_, root_manifest)) => {
1249 let effective = resolve_catalog_refs_in_overrides(
1250 &merge_manifest_and_workspace_overrides(root_manifest, workspace_overrides),
1251 workspace_catalogs,
1252 );
1253 let locked = resolve_catalog_refs_in_overrides(&self.overrides, workspace_catalogs);
1254 if let Some(reason) = overrides_drift_reason(&locked, &effective) {
1255 return DriftStatus::Stale { reason };
1256 }
1257 let mut effective_ignored = root_manifest.pnpm_ignored_optional_dependencies();
1258 effective_ignored.extend(workspace_ignored_optional.iter().cloned());
1259 if let Some(reason) = ignored_optional_drift_reason(
1260 &self.ignored_optional_dependencies,
1261 &effective_ignored,
1262 ) {
1263 return DriftStatus::Stale { reason };
1264 }
1265 effective
1266 }
1267 None => BTreeMap::new(),
1268 };
1269 for (importer_path, manifest) in manifests {
1270 match self.check_drift_for_importer(importer_path, manifest, &effective_overrides) {
1271 DriftStatus::Fresh => continue,
1272 stale => return stale,
1273 }
1274 }
1275 DriftStatus::Fresh
1276 }
1277
1278 /// Compare this lockfile's catalog snapshot against the current
1279 /// `pnpm-workspace.yaml` catalogs.
1280 ///
1281 /// pnpm only writes catalog entries that at least one importer
1282 /// references — unused entries are absent from the lockfile. So
1283 /// "missing from lockfile" doesn't mean "added by the user", it
1284 /// means "declared but unreferenced", which is not drift. The
1285 /// transition from unused → used is caught by the importer-level
1286 /// drift check, since a fresh `catalog:` reference shows up as a
1287 /// new dep in some `package.json`.
1288 ///
1289 /// We fire on two cases only:
1290 /// - the spec changed for an entry the lockfile already records
1291 /// (the entry is in use, and re-resolution must rerun);
1292 /// - the workspace removed an entry that the lockfile records
1293 /// (the importer using `catalog:` now points at nothing).
1294 ///
1295 /// Resolved versions are deliberately not part of the comparison —
1296 /// the version is an *output* of resolution, so a stale lockfile
1297 /// version is what re-resolution is supposed to fix. Drift only
1298 /// fires on user intent (the specifier).
1299 pub fn check_catalogs_drift(
1300 &self,
1301 workspace_catalogs: &BTreeMap<String, BTreeMap<String, String>>,
1302 ) -> DriftStatus {
1303 for (cat_name, cat) in workspace_catalogs {
1304 let Some(locked) = self.catalogs.get(cat_name) else {
1305 continue;
1306 };
1307 for (pkg, spec) in cat {
1308 if let Some(entry) = locked.get(pkg)
1309 && entry.specifier != *spec
1310 {
1311 return DriftStatus::Stale {
1312 reason: format!(
1313 "catalogs.{cat_name}.{pkg}: workspace says {spec}, lockfile says {}",
1314 entry.specifier
1315 ),
1316 };
1317 }
1318 }
1319 }
1320 for (cat_name, cat) in &self.catalogs {
1321 let workspace_cat = workspace_catalogs.get(cat_name);
1322 for pkg in cat.keys() {
1323 if workspace_cat.map(|c| c.contains_key(pkg)) != Some(true) {
1324 return DriftStatus::Stale {
1325 reason: format!("catalogs.{cat_name}: workspace removed {pkg}"),
1326 };
1327 }
1328 }
1329 }
1330 DriftStatus::Fresh
1331 }
1332
1333 /// Compare a single importer's `DirectDep` list against the corresponding
1334 /// `package.json`. Used by both [`check_drift`] and [`check_drift_workspace`].
1335 ///
1336 /// [`check_drift`]: Self::check_drift
1337 /// [`check_drift_workspace`]: Self::check_drift_workspace
1338 fn check_drift_for_importer(
1339 &self,
1340 importer_path: &str,
1341 manifest: &aube_manifest::PackageJson,
1342 effective_overrides: &BTreeMap<String, String>,
1343 ) -> DriftStatus {
1344 let label = if importer_path == "." {
1345 String::new()
1346 } else {
1347 format!("{importer_path}: ")
1348 };
1349
1350 let importer_deps: &[DirectDep] = self
1351 .importers
1352 .get(importer_path)
1353 .map(|v| v.as_slice())
1354 .unwrap_or(&[]);
1355
1356 // Skip the check entirely if no DirectDep has a specifier (non-pnpm format).
1357 if importer_deps.iter().all(|d| d.specifier.is_none()) {
1358 return DriftStatus::Fresh;
1359 }
1360 let lockfile_specs: BTreeMap<&str, &str> = importer_deps
1361 .iter()
1362 .filter_map(|d| d.specifier.as_deref().map(|s| (d.name.as_str(), s)))
1363 .collect();
1364
1365 let override_rules = override_match::compile(effective_overrides);
1366
1367 // Optionals the previous resolve recorded as intentionally
1368 // skipped on this importer's platform — keyed by name, value
1369 // is the specifier captured at that time. Distinct from
1370 // `ignored_optional_dependencies`, which is the user's static
1371 // ignore list; this map captures *runtime* platform skips.
1372 let skipped_optionals: BTreeMap<&str, &str> = self
1373 .skipped_optional_dependencies
1374 .get(importer_path)
1375 .map(|m| m.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect())
1376 .unwrap_or_default();
1377
1378 // Iterate prod / dev / optional with a flag so the
1379 // skipped-optional exemption only applies to deps that came
1380 // from `optional_dependencies`. Without the flag, moving a
1381 // previously-skipped optional into `dependencies` with the same
1382 // specifier would silently report Fresh and the dep would
1383 // never install as a required dep.
1384 //
1385 // Optionals named in `ignored_optional_dependencies` are
1386 // dropped from the manifest-side scan: the resolver never
1387 // enqueues them, so the lockfile importer never has them
1388 // either, and the loop would otherwise report drift on every
1389 // install. (Their *spec* is still verified separately by the
1390 // round-tripped `ignored_optional_dependencies` block below.)
1391 let ignored = &self.ignored_optional_dependencies;
1392 let manifest_deps = manifest
1393 .dependencies
1394 .iter()
1395 .map(|(k, v)| (k, v, false))
1396 .chain(manifest.dev_dependencies.iter().map(|(k, v)| (k, v, false)))
1397 .chain(
1398 manifest
1399 .optional_dependencies
1400 .iter()
1401 .filter(|(name, _)| !ignored.contains(name.as_str()))
1402 .map(|(k, v)| (k, v, true)),
1403 );
1404
1405 for (name, spec, is_optional) in manifest_deps {
1406 match lockfile_specs.get(name.as_str()) {
1407 None => {
1408 // A *missing* optional dep is only "fresh" if the
1409 // previous resolve recorded it as intentionally
1410 // skipped (platform mismatch or
1411 // `pnpm.ignoredOptionalDependencies`) AND the
1412 // recorded specifier still matches what's in the
1413 // manifest. A genuinely *new* optional that the
1414 // resolver has never seen is real drift — without
1415 // that branch, adding `fsevents` to a fresh manifest
1416 // would silently never get installed.
1417 if is_optional && let Some(locked_spec) = skipped_optionals.get(name.as_str()) {
1418 if *locked_spec == spec {
1419 continue;
1420 }
1421 return DriftStatus::Stale {
1422 reason: format!(
1423 "{label}{name}: manifest says {spec}, lockfile (skipped) says {locked_spec}"
1424 ),
1425 };
1426 }
1427 return DriftStatus::Stale {
1428 reason: format!("{label}manifest adds {name}@{spec}"),
1429 };
1430 }
1431 Some(locked_spec) if *locked_spec != spec => {
1432 // pnpm rewrites the importer specifier to the
1433 // override-applied value when an override fires on
1434 // a direct dep, so a pnpm-generated lockfile shows
1435 // `specifier: ">=3.0.5"` even though `package.json`
1436 // still reads `^3.0.4`. Accept that as fresh when
1437 // an override for this name (bare or version-keyed)
1438 // resolves to the lockfile's recorded spec —
1439 // otherwise any pnpm-written lockfile with
1440 // overrides reads stale on every frozen install.
1441 if let Some(override_spec) =
1442 override_match::apply(&override_rules, name.as_str(), spec)
1443 && override_spec == *locked_spec
1444 {
1445 continue;
1446 }
1447 return DriftStatus::Stale {
1448 reason: format!(
1449 "{label}{name}: manifest says {spec}, lockfile says {locked_spec}"
1450 ),
1451 };
1452 }
1453 Some(_) => {}
1454 }
1455 }
1456
1457 // Anything in the lockfile but missing from the manifest is stale
1458 // — UNLESS it was auto-hoisted as a peer by the resolver. pnpm-style
1459 // `auto-install-peers=true` puts peers into the importer's
1460 // `dependencies` without the user having written them in
1461 // `package.json`, so we have to recognize those as derived state
1462 // rather than user intent.
1463 //
1464 // Critically, we identify an auto-hoisted entry by matching its
1465 // *recorded specifier* against peer ranges declared in the graph,
1466 // not just by name. A name-only check would silently exempt a
1467 // user-pinned `react` that the user later removed (if any package
1468 // anywhere in the graph peer-declares react, the name match would
1469 // fire and we'd report Fresh forever — defeating the drift check).
1470 //
1471 // The rule: a lockfile entry whose (name, specifier) pair exactly
1472 // matches some package's declared (peer_name, peer_range) is
1473 // auto-hoisted. If the user had pinned react with a different
1474 // specifier string and then removed it, the (name, specifier)
1475 // pair no longer matches any peer range, and drift correctly
1476 // fires so the resolver re-runs and rewrites the lockfile.
1477 let manifest_names: std::collections::HashSet<&str> = manifest
1478 .dependencies
1479 .keys()
1480 .chain(manifest.dev_dependencies.keys())
1481 .chain(
1482 manifest
1483 .optional_dependencies
1484 .keys()
1485 .filter(|name| !ignored.contains(name.as_str())),
1486 )
1487 .map(|s| s.as_str())
1488 .collect();
1489 let auto_hoisted_peer_specs: std::collections::HashSet<(&str, &str)> = self
1490 .packages
1491 .values()
1492 .flat_map(|p| {
1493 p.peer_dependencies
1494 .iter()
1495 .map(|(name, range)| (name.as_str(), range.as_str()))
1496 })
1497 .collect();
1498 for (locked_name, locked_spec) in &lockfile_specs {
1499 if manifest_names.contains(locked_name) {
1500 continue;
1501 }
1502 if auto_hoisted_peer_specs.contains(&(*locked_name, *locked_spec)) {
1503 continue;
1504 }
1505 return DriftStatus::Stale {
1506 reason: format!("{label}manifest removed {locked_name}"),
1507 };
1508 }
1509
1510 DriftStatus::Fresh
1511 }
1512}
1513
1514/// Merge `pnpm-workspace.yaml` overrides on top of the manifest's
1515/// `overrides_map()`. Workspace entries win on key conflict, matching
1516/// pnpm v10's behavior where the workspace yaml is the canonical
1517/// home for overrides. Callers pass this into `overrides_drift_reason`
1518/// so the drift check sees the same effective map the resolver used.
1519fn merge_manifest_and_workspace_overrides(
1520 manifest: &aube_manifest::PackageJson,
1521 workspace_overrides: &BTreeMap<String, String>,
1522) -> BTreeMap<String, String> {
1523 let mut out = manifest.overrides_map();
1524 for (k, v) in workspace_overrides {
1525 out.insert(k.clone(), v.clone());
1526 }
1527 out
1528}
1529
1530/// Rewrite `catalog:` / `catalog:<name>` override values to the catalog's
1531/// resolved range. pnpm writes resolved override values into the lockfile
1532/// and compares against the resolved form on re-install, so both sides
1533/// of the drift check have to see the catalog-substituted map — otherwise
1534/// a `"lodash": "catalog:"` workspace-yaml override reads as stale against
1535/// a lockfile that recorded `"lodash": "4.17.21"`. Unresolvable references
1536/// (missing catalog or missing entry) pass through untouched; the caller
1537/// would have errored at resolve time if this ever reached a real install,
1538/// so a drift-mismatch here is fine.
1539fn resolve_catalog_refs_in_overrides(
1540 overrides: &BTreeMap<String, String>,
1541 workspace_catalogs: &BTreeMap<String, BTreeMap<String, String>>,
1542) -> BTreeMap<String, String> {
1543 overrides
1544 .iter()
1545 .map(|(k, v)| {
1546 let resolved = v
1547 .strip_prefix("catalog:")
1548 .map(|tail| if tail.is_empty() { "default" } else { tail })
1549 .and_then(|cat_name| workspace_catalogs.get(cat_name))
1550 .and_then(|cat| cat.get(override_key_package_name(k)))
1551 .cloned()
1552 .unwrap_or_else(|| v.clone());
1553 (k.clone(), resolved)
1554 })
1555 .collect()
1556}
1557
1558/// Extract the package name from an override selector key so the catalog
1559/// can be looked up by pkg name. Handles bare (`lodash`), scoped
1560/// (`@babel/core`), ranged (`lodash@<5`), ancestor-chained
1561/// (`parent>lodash`), and combinations. Unparseable keys return the
1562/// input unchanged; the catalog lookup will then miss and leave the
1563/// value as-is.
1564fn override_key_package_name(key: &str) -> &str {
1565 let last = key.rsplit('>').next().unwrap_or(key);
1566 if let Some(after_scope) = last.strip_prefix('@') {
1567 match after_scope.find('@') {
1568 Some(idx) => &last[..idx + 1],
1569 None => last,
1570 }
1571 } else {
1572 match last.find('@') {
1573 Some(idx) => &last[..idx],
1574 None => last,
1575 }
1576 }
1577}
1578
1579/// Compare two override maps and return a human-readable reason
1580/// describing the first difference, or `None` if they're identical.
1581/// Drift messages cite the offending key by name so users can act on
1582/// them — `(lockfile: N entries, manifest: M entries)` is useless
1583/// when N == M but a value changed.
1584fn overrides_drift_reason(
1585 lockfile: &BTreeMap<String, String>,
1586 manifest: &BTreeMap<String, String>,
1587) -> Option<String> {
1588 for (k, v) in manifest {
1589 match lockfile.get(k) {
1590 None => return Some(format!("overrides: manifest adds {k}@{v}")),
1591 Some(locked) if locked != v => {
1592 return Some(format!("overrides: {k} changed ({locked} → {v})"));
1593 }
1594 Some(_) => {}
1595 }
1596 }
1597 for k in lockfile.keys() {
1598 if !manifest.contains_key(k) {
1599 return Some(format!("overrides: manifest removes {k}"));
1600 }
1601 }
1602 None
1603}
1604
1605/// Compare two `ignoredOptionalDependencies` sets and return a drift
1606/// reason string for the first difference, or `None` if identical.
1607fn ignored_optional_drift_reason(
1608 lockfile: &BTreeSet<String>,
1609 manifest: &BTreeSet<String>,
1610) -> Option<String> {
1611 for name in manifest {
1612 if !lockfile.contains(name) {
1613 return Some(format!("ignoredOptionalDependencies: manifest adds {name}"));
1614 }
1615 }
1616 for name in lockfile {
1617 if !manifest.contains(name) {
1618 return Some(format!(
1619 "ignoredOptionalDependencies: manifest removes {name}"
1620 ));
1621 }
1622 }
1623 None
1624}
1625
1626/// Result of comparing a lockfile against a manifest.
1627#[derive(Debug, Clone, PartialEq, Eq)]
1628pub enum DriftStatus {
1629 /// The lockfile is in sync with the manifest. Safe to use without re-resolving.
1630 Fresh,
1631 /// The lockfile is out of date. The reason describes the first mismatch found.
1632 Stale { reason: String },
1633}
1634
1635/// Atomic lockfile write. Tempfile in the same dir, fsync, rename
1636/// over the target. Every format writer goes through this so a
1637/// crash or Ctrl+C mid-write cannot leave a truncated lockfile on
1638/// disk. Rename is atomic on POSIX, on Windows MoveFileEx gives
1639/// the same guarantee post Win10. Caller passes the serialized
1640/// bytes already formatted, this just handles the IO layer.
1641pub(crate) fn atomic_write_lockfile(path: &Path, body: &[u8]) -> Result<(), Error> {
1642 aube_util::fs_atomic::atomic_write(path, body).map_err(|e| Error::Io(path.to_path_buf(), e))
1643}
1644
1645/// Write a lockfile to the given project directory using aube's default
1646/// filename (`aube-lock.yaml`, or `aube-lock.<branch>.yaml` when branch
1647/// lockfiles are enabled).
1648pub fn write_lockfile(
1649 project_dir: &Path,
1650 graph: &LockfileGraph,
1651 manifest: &aube_manifest::PackageJson,
1652) -> Result<(), Error> {
1653 write_lockfile_as(project_dir, graph, manifest, LockfileKind::Aube)?;
1654 Ok(())
1655}
1656
1657/// Write a lockfile using the existing project lockfile kind, or
1658/// Collapse peer-context variants from `graph` into a single map keyed
1659/// by `"name@version"`, pointing at the first-seen package. Several
1660/// writers (npm, yarn, …) share this shape: one canonical entry per
1661/// `(name, version)` pair regardless of how many peer suffixes the
1662/// full graph emits.
1663pub fn build_canonical_map(graph: &LockfileGraph) -> BTreeMap<String, &LockedPackage> {
1664 let mut canonical: BTreeMap<String, &LockedPackage> = BTreeMap::new();
1665 for pkg in graph.packages.values() {
1666 canonical.entry(pkg.spec_key()).or_insert(pkg);
1667 }
1668 canonical
1669}
1670
1671/// `aube-lock.yaml` when the project does not have one yet.
1672///
1673/// This is the default write path for commands that mutate the active
1674/// project graph (`install`, `add`, `remove`, `update`, `dedupe`, ...).
1675pub fn write_lockfile_preserving_existing(
1676 project_dir: &Path,
1677 graph: &LockfileGraph,
1678 manifest: &aube_manifest::PackageJson,
1679) -> Result<PathBuf, Error> {
1680 let kind = detect_existing_lockfile_kind(project_dir).unwrap_or(LockfileKind::Aube);
1681 write_lockfile_as(project_dir, graph, manifest, kind)
1682}
1683
1684/// Write `graph` in the requested lockfile format into `project_dir`.
1685///
1686/// Returns the path that was actually written (useful for logging
1687/// since `Aube` may resolve to a branch-specific filename). Callers
1688/// that want to preserve whatever format was already on disk should
1689/// pair this with [`detect_existing_lockfile_kind`].
1690///
1691/// All supported formats: `Aube`, `Pnpm`, `Npm`, `NpmShrinkwrap`,
1692/// `Yarn`, and `Bun`. This preserves the lockfile kind that already
1693/// exists in the project; callers should pass `Aube` only when no
1694/// lockfile exists yet. See each writer module's doc comment for
1695/// per-format lossy areas (peer contexts, `resolved` URLs, etc.).
1696pub fn write_lockfile_as(
1697 project_dir: &Path,
1698 graph: &LockfileGraph,
1699 manifest: &aube_manifest::PackageJson,
1700 kind: LockfileKind,
1701) -> Result<PathBuf, Error> {
1702 let filename = match kind {
1703 LockfileKind::Aube => aube_lock_filename(project_dir),
1704 LockfileKind::Pnpm => pnpm_lock_filename(project_dir),
1705 other => other.filename().to_string(),
1706 };
1707 let path = project_dir.join(&filename);
1708 match kind {
1709 LockfileKind::Aube | LockfileKind::Pnpm => pnpm::write(&path, graph, manifest)?,
1710 LockfileKind::Npm | LockfileKind::NpmShrinkwrap => npm::write(&path, graph, manifest)?,
1711 LockfileKind::Yarn => yarn::write_classic(&path, graph, manifest)?,
1712 LockfileKind::YarnBerry => yarn::write_berry(&path, graph, manifest)?,
1713 LockfileKind::Bun => bun::write(&path, graph, manifest)?,
1714 }
1715 Ok(path)
1716}
1717
1718/// Return the [`LockfileKind`] of the lockfile already on disk in
1719/// `project_dir`, if any. Follows the same precedence as
1720/// [`parse_lockfile_with_kind`] (aube > pnpm > bun > yarn >
1721/// npm-shrinkwrap > npm). Used by install to preserve a project's
1722/// existing lockfile format when rewriting after a re-resolve — a
1723/// user with only `pnpm-lock.yaml`, `package-lock.json`, or another
1724/// supported lockfile gets that file written back, not a surprise
1725/// `aube-lock.yaml` alongside it.
1726pub fn detect_existing_lockfile_kind(project_dir: &Path) -> Option<LockfileKind> {
1727 for (path, kind) in lockfile_candidates(project_dir, /*include_aube=*/ true) {
1728 if path.exists() {
1729 return Some(refine_yarn_kind(&path, kind));
1730 }
1731 }
1732 None
1733}
1734
1735/// Resolve the canonical lockfile filename for `project_dir` (aube's own).
1736///
1737/// Returns `aube-lock.<branch>.yaml` when `gitBranchLockfile: true` is
1738/// set in `pnpm-workspace.yaml` (or `aube-workspace.yaml`) and the
1739/// project is inside a git checkout with a current branch. Forward
1740/// slashes in the branch name are encoded as `!`, matching pnpm. Falls
1741/// back to plain `aube-lock.yaml` in every other case.
1742///
1743/// Memoized per `project_dir` for the lifetime of the process: a
1744/// single install resolves this 3–5 times (lockfile_candidates,
1745/// write_lockfile, debug log, state read/write), and
1746/// `check_needs_install` runs on every `aube run`/`aube exec` via
1747/// `ensure_installed`. Without caching, every command would pay for a
1748/// YAML parse + a `git branch --show-current` subprocess just to
1749/// recompute a value that can't change mid-process.
1750pub fn aube_lock_filename(project_dir: &Path) -> String {
1751 use std::sync::{Mutex, OnceLock};
1752 static CACHE: OnceLock<Mutex<std::collections::HashMap<PathBuf, String>>> = OnceLock::new();
1753 let cache = CACHE.get_or_init(|| Mutex::new(std::collections::HashMap::new()));
1754 if let Ok(map) = cache.lock()
1755 && let Some(hit) = map.get(project_dir)
1756 {
1757 return hit.clone();
1758 }
1759 let resolved = if !git_branch_lockfile_enabled(project_dir) {
1760 "aube-lock.yaml".to_string()
1761 } else {
1762 match current_git_branch(project_dir) {
1763 Some(branch) => format!("aube-lock.{}.yaml", branch.replace('/', "!")),
1764 None => "aube-lock.yaml".to_string(),
1765 }
1766 };
1767 if let Ok(mut map) = cache.lock() {
1768 map.insert(project_dir.to_path_buf(), resolved.clone());
1769 }
1770 resolved
1771}
1772
1773/// Resolve the pnpm lockfile filename for `project_dir`.
1774///
1775/// Mirrors [`aube_lock_filename`] for branch lockfiles, but keeps the
1776/// pnpm filename prefix so projects with an existing `pnpm-lock.yaml`
1777/// keep writing to pnpm's file.
1778pub fn pnpm_lock_filename(project_dir: &Path) -> String {
1779 let aube_name = aube_lock_filename(project_dir);
1780 // `aube_lock_filename` always returns "aube-lock.<rest>", so strip_prefix
1781 // always succeeds. The fallback is purely defensive.
1782 aube_name
1783 .strip_prefix("aube-lock.")
1784 .map(|rest| format!("pnpm-lock.{rest}"))
1785 .unwrap_or_else(|| "pnpm-lock.yaml".to_string())
1786}
1787
1788fn git_branch_lockfile_enabled(project_dir: &Path) -> bool {
1789 // Goes through the build-time-generated typed accessor in
1790 // `aube_settings::resolved` so the alias list is driven off
1791 // `settings.toml` — no hand-maintained typed field. This path
1792 // reads only `pnpm-workspace.yaml`; `.npmrc` values are out of
1793 // scope here because aube-lockfile doesn't want a dependency on
1794 // aube-registry just to load npmrc (and the historical behavior
1795 // never read `.npmrc` either).
1796 let Ok(raw) = aube_manifest::workspace::load_raw(project_dir) else {
1797 return false;
1798 };
1799 let npmrc: Vec<(String, String)> = Vec::new();
1800 let ctx = aube_settings::ResolveCtx::files_only(&npmrc, &raw);
1801 aube_settings::resolved::git_branch_lockfile(&ctx)
1802}
1803
1804pub(crate) fn current_git_branch(project_dir: &Path) -> Option<String> {
1805 let out = std::process::Command::new("git")
1806 .args(["-C"])
1807 .arg(project_dir)
1808 .args(["branch", "--show-current"])
1809 .output()
1810 .ok()?;
1811 if !out.status.success() {
1812 return None;
1813 }
1814 let branch = String::from_utf8(out.stdout).ok()?.trim().to_string();
1815 if branch.is_empty() {
1816 None
1817 } else {
1818 Some(branch)
1819 }
1820}
1821
1822/// Detect and parse the lockfile in the given project directory.
1823///
1824/// Priority: `aube-lock.yaml` → `pnpm-lock.yaml` → `bun.lock` →
1825/// `yarn.lock` → `npm-shrinkwrap.json` → `package-lock.json`.
1826/// (Shrinkwrap takes priority over package-lock.json when both exist, matching npm's behavior.)
1827///
1828/// `manifest` is needed to classify direct vs transitive deps when
1829/// reading yarn.lock (which has no notion of that distinction).
1830pub fn parse_lockfile(
1831 project_dir: &Path,
1832 manifest: &aube_manifest::PackageJson,
1833) -> Result<LockfileGraph, Error> {
1834 let (graph, _kind) = parse_lockfile_with_kind(project_dir, manifest)?;
1835 Ok(graph)
1836}
1837
1838/// Like [`parse_lockfile`] but also returns which format was read.
1839pub fn parse_lockfile_with_kind(
1840 project_dir: &Path,
1841 manifest: &aube_manifest::PackageJson,
1842) -> Result<(LockfileGraph, LockfileKind), Error> {
1843 reject_bun_binary(project_dir)?;
1844 for (path, kind) in lockfile_candidates(project_dir, /*include_aube=*/ true) {
1845 if !path.exists() {
1846 continue;
1847 }
1848 let kind = refine_yarn_kind(&path, kind);
1849 let graph = parse_one(&path, kind, manifest)?;
1850 return Ok((graph, kind));
1851 }
1852 Err(Error::NotFound(project_dir.to_path_buf()))
1853}
1854
1855/// Variant of [`parse_lockfile_with_kind`] used by `aube import`.
1856///
1857/// Skips `aube-lock.yaml` — if the project already has one, there's
1858/// nothing to import. `pnpm-lock.yaml` *is* included because the whole
1859/// point of `aube import` is to convert a foreign lockfile (including
1860/// pnpm's) into `aube-lock.yaml`.
1861pub fn parse_for_import(
1862 project_dir: &Path,
1863 manifest: &aube_manifest::PackageJson,
1864) -> Result<(LockfileGraph, LockfileKind), Error> {
1865 reject_bun_binary(project_dir)?;
1866 for (path, kind) in lockfile_candidates(project_dir, /*include_aube=*/ false) {
1867 if !path.exists() {
1868 continue;
1869 }
1870 let kind = refine_yarn_kind(&path, kind);
1871 let graph = parse_one(&path, kind, manifest)?;
1872 return Ok((graph, kind));
1873 }
1874 Err(Error::NotFound(project_dir.to_path_buf()))
1875}
1876
1877/// If only `bun.lockb` is present (without a text `bun.lock`), surface an
1878/// actionable error instead of silently falling through to another format.
1879fn reject_bun_binary(project_dir: &Path) -> Result<(), Error> {
1880 let lockb = project_dir.join("bun.lockb");
1881 let text = project_dir.join("bun.lock");
1882 if lockb.exists() && !text.exists() {
1883 return Err(Error::parse(
1884 &lockb,
1885 "bun.lockb (binary format) is not supported — run `bun install --save-text-lockfile` to generate a bun.lock text file first, or upgrade to bun 1.2+ where text is the default",
1886 ));
1887 }
1888 Ok(())
1889}
1890
1891fn lockfile_candidates(project_dir: &Path, include_aube: bool) -> Vec<(PathBuf, LockfileKind)> {
1892 let mut out = Vec::new();
1893 if include_aube {
1894 // Prefer the branch-specific lockfile (if `gitBranchLockfile` is on
1895 // and we resolve a branch); fall through to plain `aube-lock.yaml`
1896 // so a freshly-enabled branch still picks up the base lockfile.
1897 let branch_name = aube_lock_filename(project_dir);
1898 if branch_name != "aube-lock.yaml" {
1899 out.push((project_dir.join(&branch_name), LockfileKind::Aube));
1900 }
1901 out.push((project_dir.join("aube-lock.yaml"), LockfileKind::Aube));
1902 }
1903 // Preserve pnpm lockfiles in place. Branch-specific
1904 // `pnpm-lock.<branch>.yaml` mirrors the aube branch lockfile naming
1905 // logic, so a project that already uses pnpm branch lockfiles keeps
1906 // writing through that file.
1907 let pnpm_branch = {
1908 let mut s = aube_lock_filename(project_dir);
1909 if let Some(rest) = s.strip_prefix("aube-lock.") {
1910 s = format!("pnpm-lock.{rest}");
1911 }
1912 s
1913 };
1914 if pnpm_branch != "pnpm-lock.yaml" {
1915 out.push((project_dir.join(&pnpm_branch), LockfileKind::Pnpm));
1916 }
1917 out.push((project_dir.join("pnpm-lock.yaml"), LockfileKind::Pnpm));
1918 out.push((project_dir.join("bun.lock"), LockfileKind::Bun));
1919 out.push((project_dir.join("yarn.lock"), LockfileKind::Yarn));
1920 out.push((
1921 project_dir.join("npm-shrinkwrap.json"),
1922 LockfileKind::NpmShrinkwrap,
1923 ));
1924 out.push((project_dir.join("package-lock.json"), LockfileKind::Npm));
1925 out
1926}
1927
1928fn parse_one(
1929 path: &Path,
1930 kind: LockfileKind,
1931 manifest: &aube_manifest::PackageJson,
1932) -> Result<LockfileGraph, Error> {
1933 match kind {
1934 // `aube-lock.yaml` uses the same on-disk format as pnpm v9 for
1935 // now — same parser, same writer — so we piggyback on the pnpm
1936 // module. Keeping the variant distinct lets detection/import
1937 // treat the two differently even though the bytes are the same.
1938 LockfileKind::Aube | LockfileKind::Pnpm => pnpm::parse(path),
1939 // yarn.rs::parse peeks the file for `__metadata:` and
1940 // dispatches between classic (v1) and berry (v2+) internally,
1941 // so we can hand both kinds to the same entry point. The
1942 // caller keeps the kind label it resolved from
1943 // `refine_yarn_kind` for downstream write-back.
1944 LockfileKind::Yarn | LockfileKind::YarnBerry => yarn::parse(path, manifest),
1945 LockfileKind::Npm | LockfileKind::NpmShrinkwrap => npm::parse(path),
1946 LockfileKind::Bun => bun::parse(path),
1947 }
1948}
1949
1950/// Replace `LockfileKind::Yarn` with `LockfileKind::YarnBerry` when
1951/// the yarn.lock at `path` is actually a yarn 2+ lockfile. Other
1952/// kinds pass through unchanged.
1953///
1954/// `lockfile_candidates` only knows filenames, not content, so the
1955/// yarn entry is always tagged `Yarn`. Callers that need the precise
1956/// variant (install write-back, import conversions, drift logging)
1957/// funnel through this helper after confirming the candidate exists.
1958fn refine_yarn_kind(path: &Path, kind: LockfileKind) -> LockfileKind {
1959 if kind == LockfileKind::Yarn && yarn::is_berry_path(path) {
1960 LockfileKind::YarnBerry
1961 } else {
1962 kind
1963 }
1964}
1965
1966#[derive(Debug, thiserror::Error, miette::Diagnostic)]
1967pub enum Error {
1968 #[error("no lockfile found in {0}")]
1969 NotFound(std::path::PathBuf),
1970 #[error("unsupported lockfile format: {0}")]
1971 UnsupportedFormat(String),
1972 #[error("failed to read lockfile {0}: {1}")]
1973 Io(std::path::PathBuf, std::io::Error),
1974 /// Structural/serialization lockfile errors that have no source
1975 /// location — shape checks (`must be a mapping`), version guards
1976 /// (`lockfileVersion N unsupported`), and `yaml_serde::to_string`
1977 /// failures during write.
1978 #[error("failed to parse lockfile {0}: {1}")]
1979 Parse(std::path::PathBuf, String),
1980 /// Deserialization failure with a byte offset into the source
1981 /// content, so miette's `fancy` handler can draw a pointer at the
1982 /// offending byte of the lockfile. Reuses `aube_manifest`'s
1983 /// `ParseError` — identical shape, identical rendering — via the
1984 /// same `ParseDiag` pattern `aube-workspace` uses.
1985 #[error(transparent)]
1986 #[diagnostic(transparent)]
1987 ParseDiag(Box<aube_manifest::ParseError>),
1988}
1989
1990/// Read a lockfile from disk, mapping I/O errors to `Error::Io`.
1991pub fn read_lockfile(path: &std::path::Path) -> Result<String, Error> {
1992 std::fs::read_to_string(path).map_err(|e| Error::Io(path.to_path_buf(), e))
1993}
1994
1995/// Parse a JSON lockfile document, attaching a miette source span on
1996/// failure so the fancy handler can point at the offending byte.
1997pub fn parse_json<T: serde::de::DeserializeOwned>(
1998 path: &std::path::Path,
1999 content: String,
2000) -> Result<T, Error> {
2001 // simd-json mutates the input buffer in place to unflatten
2002 // escape sequences. On parse failure that mutation has already
2003 // happened, so the diagnostic must run on the ORIGINAL bytes,
2004 // not the simd-json buffer. Keeping `content` and feeding a
2005 // clone to simd-json preserves both: zero-alloc happy path on
2006 // simd-json success (one clone, dropped immediately), correct
2007 // diagnostic on failure (uses untouched `content`).
2008 let mut buf = content.clone().into_bytes();
2009 match simd_json::serde::from_slice(&mut buf) {
2010 Ok(v) => Ok(v),
2011 Err(_) => match serde_json::from_str(&content) {
2012 Ok(v) => Ok(v),
2013 Err(e) => Err(Error::parse_json_err(path, content, &e)),
2014 },
2015 }
2016}
2017
2018impl Error {
2019 pub fn parse(path: &std::path::Path, msg: impl Into<String>) -> Self {
2020 Error::Parse(path.to_path_buf(), msg.into())
2021 }
2022
2023 pub fn parse_json_err(
2024 path: &std::path::Path,
2025 content: String,
2026 err: &serde_json::Error,
2027 ) -> Self {
2028 Error::ParseDiag(Box::new(aube_manifest::ParseError::from_json_err(
2029 path, content, err,
2030 )))
2031 }
2032
2033 pub fn parse_yaml_err(
2034 path: &std::path::Path,
2035 content: String,
2036 err: &yaml_serde::Error,
2037 ) -> Self {
2038 Error::ParseDiag(Box::new(aube_manifest::ParseError::from_yaml_err(
2039 path, content, err,
2040 )))
2041 }
2042}
2043
2044#[cfg(test)]
2045mod parse_diag_tests {
2046 use super::*;
2047 use std::path::Path;
2048
2049 /// Trailing `,` in an otherwise fine JSON lockfile — confirm the
2050 /// helper attaches a `NamedSource` pointed at the lockfile path and
2051 /// the span stays in bounds so miette can render a pointer.
2052 #[test]
2053 fn parse_json_attaches_span_for_bad_input() {
2054 let path = Path::new("package-lock.json");
2055 let content = r#"{"name":"x","#.to_string();
2056 let Err(Error::ParseDiag(pe)) = parse_json::<serde_json::Value>(path, content.clone())
2057 else {
2058 panic!("parse_json must produce ParseDiag on malformed input");
2059 };
2060 let offset: usize = pe.span.offset();
2061 let len: usize = pe.span.len();
2062 assert!(offset + len <= content.len());
2063 assert_eq!(pe.path, path);
2064 }
2065
2066 /// Same story for YAML — yaml_serde reports a `Location` with a
2067 /// byte index directly, so no line/col conversion is exercised
2068 /// here. Both production sites (`pnpm.rs`, `yarn.rs`) call
2069 /// `Error::parse_yaml_err` directly (one iterates multiple YAML
2070 /// documents, the other has only borrowed content), so that's the
2071 /// entry point this test locks down.
2072 #[test]
2073 fn parse_yaml_err_attaches_span_for_bad_input() {
2074 let path = Path::new("yarn.lock");
2075 let content = "packages:\n\t- pkg\n".to_string();
2076 let yaml_err: yaml_serde::Error = yaml_serde::from_str::<yaml_serde::Value>(&content)
2077 .expect_err("tab-indented YAML must fail");
2078 let Error::ParseDiag(pe) = Error::parse_yaml_err(path, content.clone(), &yaml_err) else {
2079 panic!("parse_yaml_err must produce ParseDiag");
2080 };
2081 let offset: usize = pe.span.offset();
2082 let len: usize = pe.span.len();
2083 assert!(offset + len <= content.len());
2084 assert_eq!(pe.path, path);
2085 }
2086}
2087
2088#[cfg(test)]
2089mod looks_like_remote_tarball_url_tests {
2090 use super::*;
2091
2092 #[test]
2093 fn matches_https_tgz() {
2094 assert!(LocalSource::looks_like_remote_tarball_url(
2095 "https://example.com/pkg-1.0.0.tgz"
2096 ));
2097 }
2098
2099 #[test]
2100 fn matches_http_tar_gz() {
2101 assert!(LocalSource::looks_like_remote_tarball_url(
2102 "http://example.com/pkg-1.0.0.tar.gz"
2103 ));
2104 }
2105
2106 #[test]
2107 fn strips_fragment_before_suffix_check() {
2108 assert!(LocalSource::looks_like_remote_tarball_url(
2109 "https://example.com/pkg-1.0.0.tgz#sha512-abc"
2110 ));
2111 }
2112
2113 #[test]
2114 fn strips_query_string_before_suffix_check() {
2115 // Auth-token URLs from private registries (JFrog, Nexus,
2116 // CodeArtifact, …) routinely trail `?token=…` after the
2117 // filename. Must still classify as a tarball URL.
2118 assert!(LocalSource::looks_like_remote_tarball_url(
2119 "https://registry.example.com/pkg/-/pkg-1.0.0.tgz?token=abc"
2120 ));
2121 assert!(LocalSource::looks_like_remote_tarball_url(
2122 "https://example.com/pkg-1.0.0.tar.gz?v=2&signed=1"
2123 ));
2124 }
2125
2126 #[test]
2127 fn matches_bare_http_url_without_tarball_suffix() {
2128 // pkg.pr.new serves tarballs from URLs without a `.tgz`
2129 // extension; npm treats all non-git http(s) URLs as tarball
2130 // URLs, so these must classify as remote tarballs.
2131 assert!(LocalSource::looks_like_remote_tarball_url(
2132 "https://pkg.pr.new/lunariajs/lunaria/@lunariajs/core@904b935"
2133 ));
2134 assert!(LocalSource::looks_like_remote_tarball_url(
2135 "https://codeload.github.com/user/repo/tar.gz/main"
2136 ));
2137 }
2138
2139 #[test]
2140 fn rejects_non_http_schemes() {
2141 assert!(!LocalSource::looks_like_remote_tarball_url(
2142 "ftp://example.com/pkg.tgz"
2143 ));
2144 assert!(!LocalSource::looks_like_remote_tarball_url(
2145 "git://example.com/repo.git"
2146 ));
2147 }
2148
2149 #[test]
2150 fn parse_classifies_bare_http_url_as_remote_tarball() {
2151 use std::path::Path;
2152 let parsed = LocalSource::parse(
2153 "https://pkg.pr.new/lunariajs/lunaria/@lunariajs/core@904b935",
2154 Path::new(""),
2155 );
2156 assert!(matches!(parsed, Some(LocalSource::RemoteTarball(_))));
2157 }
2158
2159 #[test]
2160 fn parse_prefers_git_over_tarball_for_dot_git_url() {
2161 use std::path::Path;
2162 let parsed = LocalSource::parse("https://github.com/user/repo.git", Path::new(""));
2163 assert!(matches!(parsed, Some(LocalSource::Git(_))));
2164 }
2165}
2166
2167#[cfg(test)]
2168mod filename_tests {
2169 use super::*;
2170
2171 #[test]
2172 fn defaults_to_plain_lockfile_when_setting_absent() {
2173 let dir = tempfile::tempdir().unwrap();
2174 assert_eq!(aube_lock_filename(dir.path()), "aube-lock.yaml");
2175 assert_eq!(pnpm_lock_filename(dir.path()), "pnpm-lock.yaml");
2176 }
2177
2178 #[test]
2179 fn defaults_to_plain_lockfile_when_setting_explicit_false() {
2180 let dir = tempfile::tempdir().unwrap();
2181 std::fs::write(
2182 dir.path().join("pnpm-workspace.yaml"),
2183 "gitBranchLockfile: false\n",
2184 )
2185 .unwrap();
2186 assert_eq!(aube_lock_filename(dir.path()), "aube-lock.yaml");
2187 }
2188
2189 #[test]
2190 fn uses_branch_filename_when_enabled_inside_git_repo() {
2191 let dir = tempfile::tempdir().unwrap();
2192 std::fs::write(
2193 dir.path().join("pnpm-workspace.yaml"),
2194 "gitBranchLockfile: true\n",
2195 )
2196 .unwrap();
2197 // git init + checkout a branch with a `/` so we exercise the
2198 // pnpm-style `!` encoding.
2199 let run = |args: &[&str]| {
2200 std::process::Command::new("git")
2201 .args(["-C"])
2202 .arg(dir.path())
2203 .args(args)
2204 .output()
2205 .unwrap()
2206 };
2207 if run(&["init", "-q"]).status.success() {
2208 run(&["checkout", "-q", "-b", "feature/x"]);
2209 assert_eq!(aube_lock_filename(dir.path()), "aube-lock.feature!x.yaml");
2210 assert_eq!(pnpm_lock_filename(dir.path()), "pnpm-lock.feature!x.yaml");
2211 }
2212 }
2213}
2214
2215#[cfg(test)]
2216mod git_spec_tests {
2217 use super::*;
2218
2219 #[test]
2220 fn git_plus_https_without_dot_git_roundtrips_via_lockfile_form() {
2221 // Initial parse: `git+https://…/repo` (no `.git`).
2222 let (url, committish, subpath) = parse_git_spec("git+https://host/user/repo").unwrap();
2223 assert_eq!(url, "https://host/user/repo");
2224 assert_eq!(committish, None);
2225 assert_eq!(subpath, None);
2226
2227 // After resolving, the serializer writes `<url>#<sha>` into
2228 // the lockfile's importer `version:` field.
2229 let sha = "abcdef0123456789abcdef0123456789abcdef01";
2230 let source = LocalSource::Git(GitSource {
2231 url: url.clone(),
2232 committish: None,
2233 resolved: sha.to_string(),
2234 subpath: None,
2235 });
2236 let lockfile_version = source.specifier();
2237 assert_eq!(lockfile_version, format!("https://host/user/repo#{sha}"));
2238
2239 // Re-parse must recognize the bare URL because the 40-hex
2240 // committish suffix unambiguously tags it as git.
2241 let (round_url, round_committish, round_subpath) =
2242 parse_git_spec(&lockfile_version).unwrap();
2243 assert_eq!(round_url, "https://host/user/repo");
2244 assert_eq!(round_committish.as_deref(), Some(sha));
2245 assert_eq!(round_subpath, None);
2246 }
2247
2248 #[test]
2249 fn bare_https_without_dot_git_and_no_committish_is_not_git() {
2250 // A plain `https://…` URL with no `.git` and no SHA could be
2251 // anything (including a tarball); don't claim it.
2252 assert!(parse_git_spec("https://example.com/pkg").is_none());
2253 }
2254
2255 #[test]
2256 fn github_shorthand_expands_and_roundtrips() {
2257 let (url, _, _) = parse_git_spec("github:user/repo").unwrap();
2258 assert_eq!(url, "https://github.com/user/repo.git");
2259 }
2260
2261 #[test]
2262 fn scp_form_recognized() {
2263 let (url, committish, _) =
2264 parse_git_spec("git@github.com:EthanHenrickson/math-mcp.git").unwrap();
2265 assert_eq!(url, "ssh://git@github.com/EthanHenrickson/math-mcp.git");
2266 assert!(committish.is_none());
2267 }
2268
2269 #[test]
2270 fn scp_form_with_ref_recognized() {
2271 let (url, committish, _) =
2272 parse_git_spec("git@github.com:EthanHenrickson/math-mcp.git#0.1.5").unwrap();
2273 assert_eq!(url, "ssh://git@github.com/EthanHenrickson/math-mcp.git");
2274 assert_eq!(committish.as_deref(), Some("0.1.5"));
2275 }
2276
2277 #[test]
2278 fn scp_form_bitbucket_recognized() {
2279 let (url, _, _) = parse_git_spec("git@bitbucket.org:pnpmjs/git-resolver.git").unwrap();
2280 assert_eq!(url, "ssh://git@bitbucket.org/pnpmjs/git-resolver.git");
2281 }
2282
2283 #[test]
2284 fn scp_form_unknown_host_rejected() {
2285 // pnpm 11 treats `user@unknown-host:path` as a local path, not Git.
2286 assert!(parse_git_spec("git@example.com:org/repo.git").is_none());
2287 assert!(parse_git_spec("alice@host.example.com:org/repo.git").is_none());
2288 }
2289
2290 #[test]
2291 fn scp_form_without_user_rejected() {
2292 // pnpm 11 errors on bare `host:path` as unsupported.
2293 assert!(parse_git_spec("github.com:user/repo.git").is_none());
2294 }
2295
2296 #[test]
2297 fn commit_selector_fragment_normalizes_to_sha() {
2298 let sha = "abcdef0123456789abcdef0123456789abcdef01";
2299 let (url, committish, _) =
2300 parse_git_spec(&format!("https://host/user/repo.git#commit={sha}")).unwrap();
2301 assert_eq!(url, "https://host/user/repo.git");
2302 assert_eq!(committish.as_deref(), Some(sha));
2303 }
2304
2305 #[test]
2306 fn named_selector_fragment_normalizes_to_ref() {
2307 let (url, committish, _) = parse_git_spec("git+https://host/user/repo#tag=v1.2.3").unwrap();
2308 assert_eq!(url, "https://host/user/repo");
2309 assert_eq!(committish.as_deref(), Some("v1.2.3"));
2310 }
2311
2312 #[test]
2313 fn pnpm_path_subpath_extracted_from_fragment() {
2314 // pnpm syntax: `<url>#<ref>&path:/<subdir>` selects a
2315 // subdirectory of the cloned repo as the package root.
2316 let (url, committish, subpath) =
2317 parse_git_spec("github:org/dep#v0.1.4&path:/packages/special").unwrap();
2318 assert_eq!(url, "https://github.com/org/dep.git");
2319 assert_eq!(committish.as_deref(), Some("v0.1.4"));
2320 assert_eq!(subpath.as_deref(), Some("packages/special"));
2321 }
2322
2323 #[test]
2324 fn path_subpath_roundtrips_via_specifier() {
2325 let sha = "abcdef0123456789abcdef0123456789abcdef01";
2326 let source = LocalSource::Git(GitSource {
2327 url: "https://github.com/org/dep.git".to_string(),
2328 committish: None,
2329 resolved: sha.to_string(),
2330 subpath: Some("packages/special".to_string()),
2331 });
2332 let spec = source.specifier();
2333 assert_eq!(
2334 spec,
2335 format!("https://github.com/org/dep.git#{sha}&path:/packages/special")
2336 );
2337 let (url, committish, subpath) = parse_git_spec(&spec).unwrap();
2338 assert_eq!(url, "https://github.com/org/dep.git");
2339 assert_eq!(committish.as_deref(), Some(sha));
2340 assert_eq!(subpath.as_deref(), Some("packages/special"));
2341 }
2342
2343 #[test]
2344 fn parse_hosted_git_recognizes_canonical_forms() {
2345 // All these point at the same (github.com, owner, repo) tuple
2346 // and must map to the same HostedGit so the runtime fetch URL
2347 // doesn't depend on which scheme the lockfile happens to record.
2348 let canonical = HostedGit {
2349 host: HostedGitHost::GitHub,
2350 owner: "owner".to_string(),
2351 repo: "repo".to_string(),
2352 };
2353 for spec in [
2354 "https://github.com/owner/repo.git",
2355 "https://github.com/owner/repo",
2356 "http://github.com/owner/repo.git",
2357 "git+https://github.com/owner/repo.git",
2358 "git+https://github.com/owner/repo",
2359 "git://github.com/owner/repo.git",
2360 "ssh://git@github.com/owner/repo.git",
2361 "git+ssh://git@github.com/owner/repo.git",
2362 "git@github.com:owner/repo.git",
2363 ] {
2364 assert_eq!(
2365 parse_hosted_git(spec).as_ref(),
2366 Some(&canonical),
2367 "spec {spec} should map to canonical HostedGit",
2368 );
2369 }
2370 }
2371
2372 #[test]
2373 fn parse_hosted_git_returns_none_for_non_hosted() {
2374 // Self-hosted GitLab / Gitea / arbitrary hosts: no codeload
2375 // template, so the codeload fast path doesn't apply.
2376 for spec in [
2377 "https://example.com/owner/repo.git",
2378 "ssh://git@gitea.internal/owner/repo.git",
2379 "git+ssh://git@gitlab.example.com/group/sub/repo.git",
2380 "https://github.com/owner/repo/sub",
2381 "https://github.com/owner",
2382 ] {
2383 assert!(
2384 parse_hosted_git(spec).is_none(),
2385 "spec {spec} must not match a hosted provider",
2386 );
2387 }
2388 }
2389
2390 #[test]
2391 fn hosted_tarball_url_only_for_full_sha() {
2392 let g = HostedGit {
2393 host: HostedGitHost::GitHub,
2394 owner: "o".to_string(),
2395 repo: "r".to_string(),
2396 };
2397 let sha = "abcdef0123456789abcdef0123456789abcdef01";
2398 assert_eq!(
2399 g.tarball_url(sha).as_deref(),
2400 Some("https://codeload.github.com/o/r/tar.gz/abcdef0123456789abcdef0123456789abcdef01"),
2401 );
2402 // Branch / tag / abbreviated SHA don't take the fast path —
2403 // codeload accepts them but the wrapper-dir name varies and
2404 // we can't verify a non-SHA committish post-extraction.
2405 assert!(g.tarball_url("main").is_none());
2406 assert!(g.tarball_url("v1.2.3").is_none());
2407 assert!(g.tarball_url("abcdef0").is_none());
2408 }
2409
2410 #[test]
2411 fn hosted_tarball_url_per_provider() {
2412 let sha = "abcdef0123456789abcdef0123456789abcdef01";
2413 let gitlab = HostedGit {
2414 host: HostedGitHost::GitLab,
2415 owner: "g".to_string(),
2416 repo: "r".to_string(),
2417 }
2418 .tarball_url(sha)
2419 .unwrap();
2420 assert!(gitlab.starts_with("https://gitlab.com/g/r/-/archive/"));
2421 assert!(gitlab.ends_with("/r-abcdef0123456789abcdef0123456789abcdef01.tar.gz"));
2422 let bitbucket = HostedGit {
2423 host: HostedGitHost::Bitbucket,
2424 owner: "g".to_string(),
2425 repo: "r".to_string(),
2426 }
2427 .tarball_url(sha)
2428 .unwrap();
2429 assert_eq!(
2430 bitbucket,
2431 "https://bitbucket.org/g/r/get/abcdef0123456789abcdef0123456789abcdef01.tar.gz",
2432 );
2433 }
2434
2435 #[test]
2436 fn hosted_https_url_normalizes() {
2437 let g = parse_hosted_git("git+ssh://git@github.com/owner/repo.git").unwrap();
2438 assert_eq!(g.https_url(), "https://github.com/owner/repo.git");
2439 }
2440
2441 #[test]
2442 fn path_traversal_components_in_subpath_are_rejected() {
2443 // `..` and `.` components would let a crafted spec escape the
2444 // clone dir at install time. The parser drops them so the
2445 // resolver/installer never see a traversal-laden subpath.
2446 let cases = [
2447 "github:org/dep#main&path:/../../etc",
2448 "github:org/dep#main&path:/packages/../../../etc",
2449 "github:org/dep#main&path:/./packages/foo",
2450 "github:org/dep#main&path:/packages//foo",
2451 ];
2452 for spec in cases {
2453 let (_, _, subpath) = parse_git_spec(spec).unwrap();
2454 assert_eq!(subpath, None, "spec should drop subpath: {spec}");
2455 }
2456 }
2457
2458 #[test]
2459 fn dep_path_distinguishes_subpaths_under_same_commit() {
2460 // Two packages from the same repo+commit but different
2461 // subdirs must hash to distinct dep_paths so the linker
2462 // doesn't collapse them.
2463 let sha = "abcdef0123456789abcdef0123456789abcdef01";
2464 let a = LocalSource::Git(GitSource {
2465 url: "https://example.com/r.git".to_string(),
2466 committish: None,
2467 resolved: sha.to_string(),
2468 subpath: Some("packages/a".to_string()),
2469 });
2470 let b = LocalSource::Git(GitSource {
2471 url: "https://example.com/r.git".to_string(),
2472 committish: None,
2473 resolved: sha.to_string(),
2474 subpath: Some("packages/b".to_string()),
2475 });
2476 assert_ne!(a.dep_path("dep"), b.dep_path("dep"));
2477 }
2478}
2479
2480#[cfg(test)]
2481mod drift_tests {
2482 use super::*;
2483 use aube_manifest::PackageJson;
2484 use std::collections::BTreeMap;
2485
2486 fn make_manifest(deps: &[(&str, &str)]) -> PackageJson {
2487 let mut m = PackageJson {
2488 name: Some("test".into()),
2489 version: Some("1.0.0".into()),
2490 dependencies: BTreeMap::new(),
2491 dev_dependencies: BTreeMap::new(),
2492 peer_dependencies: BTreeMap::new(),
2493 optional_dependencies: BTreeMap::new(),
2494 update_config: None,
2495 scripts: BTreeMap::new(),
2496 engines: BTreeMap::new(),
2497 workspaces: None,
2498 bundled_dependencies: None,
2499 extra: BTreeMap::new(),
2500 };
2501 for (name, spec) in deps {
2502 m.dependencies.insert((*name).into(), (*spec).into());
2503 }
2504 m
2505 }
2506
2507 fn make_graph(deps: &[(&str, &str, &str)]) -> LockfileGraph {
2508 // (name, specifier, dep_path)
2509 let direct: Vec<DirectDep> = deps
2510 .iter()
2511 .map(|(name, spec, dep_path)| DirectDep {
2512 name: (*name).into(),
2513 dep_path: (*dep_path).into(),
2514 dep_type: DepType::Production,
2515 specifier: Some((*spec).into()),
2516 })
2517 .collect();
2518 let mut importers = BTreeMap::new();
2519 importers.insert(".".to_string(), direct);
2520 LockfileGraph {
2521 importers,
2522 packages: BTreeMap::new(),
2523 ..Default::default()
2524 }
2525 }
2526
2527 #[test]
2528 fn fresh_when_specifiers_match() {
2529 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2530 let graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2531 assert_eq!(
2532 graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()),
2533 DriftStatus::Fresh
2534 );
2535 }
2536
2537 #[test]
2538 fn stale_when_specifier_changes() {
2539 let manifest = make_manifest(&[("lodash", "^4.18.0")]);
2540 let graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2541 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2542 DriftStatus::Stale { reason } => assert!(reason.contains("lodash")),
2543 DriftStatus::Fresh => panic!("expected Stale"),
2544 }
2545 }
2546
2547 #[test]
2548 fn stale_when_manifest_adds_dep() {
2549 let manifest = make_manifest(&[("lodash", "^4.17.0"), ("express", "^4.18.0")]);
2550 let graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2551 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2552 DriftStatus::Stale { reason } => assert!(reason.contains("express")),
2553 DriftStatus::Fresh => panic!("expected Stale"),
2554 }
2555 }
2556
2557 #[test]
2558 fn stale_when_manifest_removes_dep() {
2559 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2560 let graph = make_graph(&[
2561 ("lodash", "^4.17.0", "lodash@4.17.21"),
2562 ("express", "^4.18.0", "express@4.18.0"),
2563 ]);
2564 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2565 DriftStatus::Stale { reason } => assert!(reason.contains("express")),
2566 DriftStatus::Fresh => panic!("expected Stale"),
2567 }
2568 }
2569
2570 // Regression guard for #42: the drift check must recognize
2571 // auto-hoisted peers as derived state, not as "manifest removed X".
2572 // Without this, every project that has any peer dep would trigger
2573 // a full re-resolve on every install, defeating lockfile caching.
2574 #[test]
2575 fn fresh_when_lockfile_has_auto_hoisted_peer() {
2576 let manifest = make_manifest(&[("use-sync-external-store", "1.2.0")]);
2577 let mut graph = make_graph(&[
2578 (
2579 "use-sync-external-store",
2580 "1.2.0",
2581 "use-sync-external-store@1.2.0",
2582 ),
2583 // Hoisted peer — in the lockfile importers but not in the
2584 // user's package.json.
2585 ("react", "^16.8.0 || ^17.0.0 || ^18.0.0", "react@18.3.1"),
2586 ]);
2587 // The declaring package must list react as a peer for the
2588 // drift check to recognize the hoist. We add that here.
2589 let mut declaring_pkg = LockedPackage {
2590 name: "use-sync-external-store".into(),
2591 version: "1.2.0".into(),
2592 dep_path: "use-sync-external-store@1.2.0".into(),
2593 ..Default::default()
2594 };
2595 declaring_pkg
2596 .peer_dependencies
2597 .insert("react".into(), "^16.8.0 || ^17.0.0 || ^18.0.0".into());
2598 graph
2599 .packages
2600 .insert("use-sync-external-store@1.2.0".into(), declaring_pkg);
2601
2602 assert_eq!(
2603 graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()),
2604 DriftStatus::Fresh
2605 );
2606 }
2607
2608 // Regression: when a user explicitly pinned a dep that also happens
2609 // to share its name with a peer declaration elsewhere in the graph,
2610 // removing that pin from package.json must still be flagged as
2611 // stale — otherwise the old pinned version gets locked forever.
2612 // The check must key on (name, specifier), not name alone.
2613 #[test]
2614 fn stale_when_user_removes_pinned_dep_that_shares_name_with_a_peer() {
2615 // Manifest after the user removed react entirely. Only
2616 // use-sync-external-store remains.
2617 let manifest = make_manifest(&[("use-sync-external-store", "1.2.0")]);
2618
2619 // Lockfile still has the user's old `react: 17.0.2` pin alongside
2620 // use-sync-external-store. Pre-removal state.
2621 let mut graph = make_graph(&[
2622 (
2623 "use-sync-external-store",
2624 "1.2.0",
2625 "use-sync-external-store@1.2.0",
2626 ),
2627 ("react", "17.0.2", "react@17.0.2"),
2628 ]);
2629 // Add the peer declaration on the consumer package. This is
2630 // the case that previously defeated the name-only check:
2631 // react's specifier "17.0.2" doesn't match the declared peer
2632 // range, so the hoist recognizer must reject it.
2633 let mut consumer = LockedPackage {
2634 name: "use-sync-external-store".into(),
2635 version: "1.2.0".into(),
2636 dep_path: "use-sync-external-store@1.2.0".into(),
2637 ..Default::default()
2638 };
2639 consumer
2640 .peer_dependencies
2641 .insert("react".into(), "^16.8.0 || ^17.0.0 || ^18.0.0".into());
2642 graph
2643 .packages
2644 .insert("use-sync-external-store@1.2.0".into(), consumer);
2645
2646 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2647 DriftStatus::Stale { reason } => assert!(reason.contains("react")),
2648 DriftStatus::Fresh => panic!(
2649 "drift check should flag a removed user-pinned dep as stale, \
2650 even when its name matches a peer declaration"
2651 ),
2652 }
2653 }
2654
2655 // But if the lockfile has a user-removed dep that ISN'T declared as a
2656 // peer anywhere, we still need to flag it as stale.
2657 #[test]
2658 fn stale_when_lockfile_has_removed_non_peer_dep() {
2659 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2660 let graph = make_graph(&[
2661 ("lodash", "^4.17.0", "lodash@4.17.21"),
2662 ("chalk", "^5.0.0", "chalk@5.0.0"),
2663 ]);
2664 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2665 DriftStatus::Stale { reason } => assert!(reason.contains("chalk")),
2666 DriftStatus::Fresh => panic!("expected Stale"),
2667 }
2668 }
2669
2670 #[test]
2671 fn fresh_when_no_specifiers_recorded() {
2672 // Non-pnpm formats (npm/yarn/bun) don't store specifiers, so we can't
2673 // detect drift — we treat them as fresh and let the resolver decide.
2674 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2675 let graph = LockfileGraph {
2676 importers: {
2677 let mut m = BTreeMap::new();
2678 m.insert(
2679 ".".to_string(),
2680 vec![DirectDep {
2681 name: "lodash".into(),
2682 dep_path: "lodash@4.17.21".into(),
2683 dep_type: DepType::Production,
2684 specifier: None,
2685 }],
2686 );
2687 m
2688 },
2689 packages: BTreeMap::new(),
2690 ..Default::default()
2691 };
2692 assert_eq!(
2693 graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()),
2694 DriftStatus::Fresh
2695 );
2696 }
2697
2698 #[test]
2699 fn stale_when_manifest_adds_override() {
2700 // Lockfile recorded no overrides; manifest now has one. Drift
2701 // must fire so the next install re-runs the resolver and bakes
2702 // the override into the graph.
2703 let mut manifest = make_manifest(&[("lodash", "^4.17.0")]);
2704 manifest
2705 .extra
2706 .insert("overrides".into(), serde_json::json!({"lodash": "4.17.21"}));
2707 let graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2708 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2709 DriftStatus::Stale { reason } => assert!(reason.contains("overrides")),
2710 DriftStatus::Fresh => panic!("expected Stale"),
2711 }
2712 }
2713
2714 #[test]
2715 fn stale_drift_message_names_changed_override_key() {
2716 // Both sides have one entry, but the value differs. The reason
2717 // should name the key — the previous "lockfile: 1 entries,
2718 // manifest: 1 entries" message looked like nothing changed.
2719 let mut manifest = make_manifest(&[("lodash", "^4.17.0")]);
2720 manifest
2721 .extra
2722 .insert("overrides".into(), serde_json::json!({"lodash": "5.0.0"}));
2723 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2724 graph.overrides.insert("lodash".into(), "4.17.21".into());
2725 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2726 DriftStatus::Stale { reason } => {
2727 assert!(reason.contains("lodash"), "expected key in: {reason}");
2728 assert!(
2729 reason.contains("4.17.21"),
2730 "expected old value in: {reason}"
2731 );
2732 assert!(reason.contains("5.0.0"), "expected new value in: {reason}");
2733 }
2734 DriftStatus::Fresh => panic!("expected Stale"),
2735 }
2736 }
2737
2738 #[test]
2739 fn stale_when_manifest_removes_override() {
2740 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2741 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2742 graph.overrides.insert("lodash".into(), "4.17.21".into());
2743 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2744 DriftStatus::Stale { reason } => {
2745 assert!(reason.contains("removes"));
2746 assert!(reason.contains("lodash"));
2747 }
2748 DriftStatus::Fresh => panic!("expected Stale"),
2749 }
2750 }
2751
2752 #[test]
2753 fn fresh_when_overrides_match() {
2754 let mut manifest = make_manifest(&[("lodash", "^4.17.0")]);
2755 manifest
2756 .extra
2757 .insert("overrides".into(), serde_json::json!({"lodash": "4.17.21"}));
2758 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2759 graph.overrides.insert("lodash".into(), "4.17.21".into());
2760 assert_eq!(
2761 graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()),
2762 DriftStatus::Fresh
2763 );
2764 }
2765
2766 #[test]
2767 fn fresh_when_workspace_yaml_overrides_match_lockfile() {
2768 // pnpm v10 moved `overrides` to pnpm-workspace.yaml. When the
2769 // resolver wrote them into `self.overrides`, the drift check
2770 // must see the same map — otherwise the second install run
2771 // rejects the lockfile as stale with "manifest removes ..."
2772 // (reported in discussion #174).
2773 let manifest = make_manifest(&[("semver", "^7.5.0")]);
2774 let mut graph = make_graph(&[("semver", "^7.5.0", "semver@7.7.1")]);
2775 graph.overrides.insert("semver".into(), "7.7.1".into());
2776 let mut ws_overrides = BTreeMap::new();
2777 ws_overrides.insert("semver".into(), "7.7.1".into());
2778 assert_eq!(
2779 graph.check_drift(&manifest, &ws_overrides, &[], &BTreeMap::new()),
2780 DriftStatus::Fresh,
2781 );
2782 }
2783
2784 #[test]
2785 fn workspace_yaml_overrides_win_over_package_json() {
2786 // When both pnpm-workspace.yaml and package.json declare an
2787 // override for the same key, the workspace yaml wins — pnpm
2788 // v10's precedence. The drift check must apply the merged
2789 // effective map.
2790 let mut manifest = make_manifest(&[("semver", "^7.5.0")]);
2791 manifest
2792 .extra
2793 .insert("overrides".into(), serde_json::json!({"semver": "7.0.0"}));
2794 let mut graph = make_graph(&[("semver", "^7.5.0", "semver@7.7.1")]);
2795 graph.overrides.insert("semver".into(), "7.7.1".into());
2796 let mut ws_overrides = BTreeMap::new();
2797 ws_overrides.insert("semver".into(), "7.7.1".into());
2798 assert_eq!(
2799 graph.check_drift(&manifest, &ws_overrides, &[], &BTreeMap::new()),
2800 DriftStatus::Fresh,
2801 );
2802 }
2803
2804 #[test]
2805 fn fresh_when_override_catalog_ref_matches_lockfile_resolved() {
2806 // pnpm-workspace.yaml: `overrides: { lodash: "catalog:" }` with
2807 // `catalog: { lodash: 4.17.21 }`. pnpm writes the lockfile with
2808 // the resolved override value (`lodash: 4.17.21`), so a frozen
2809 // install comparing the raw `catalog:` string against the
2810 // resolved form would always read stale (discussion #174).
2811 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2812 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2813 graph.overrides.insert("lodash".into(), "4.17.21".into());
2814 let mut ws_overrides = BTreeMap::new();
2815 ws_overrides.insert("lodash".into(), "catalog:".into());
2816 let mut catalogs = BTreeMap::new();
2817 let mut default_cat = BTreeMap::new();
2818 default_cat.insert("lodash".into(), "4.17.21".into());
2819 catalogs.insert("default".into(), default_cat);
2820 assert_eq!(
2821 graph.check_drift(&manifest, &ws_overrides, &[], &catalogs),
2822 DriftStatus::Fresh,
2823 );
2824 }
2825
2826 #[test]
2827 fn fresh_when_override_named_catalog_ref_matches_lockfile_resolved() {
2828 // Named catalog variant: `overrides: { lodash: "catalog:evens" }`
2829 // resolves against `catalogs.evens.lodash`.
2830 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2831 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2832 graph.overrides.insert("lodash".into(), "4.17.21".into());
2833 let mut ws_overrides = BTreeMap::new();
2834 ws_overrides.insert("lodash".into(), "catalog:evens".into());
2835 let mut catalogs = BTreeMap::new();
2836 let mut evens = BTreeMap::new();
2837 evens.insert("lodash".into(), "4.17.21".into());
2838 catalogs.insert("evens".into(), evens);
2839 assert_eq!(
2840 graph.check_drift(&manifest, &ws_overrides, &[], &catalogs),
2841 DriftStatus::Fresh,
2842 );
2843 }
2844
2845 #[test]
2846 fn stale_when_override_catalog_ref_diverges_from_lockfile() {
2847 // If the catalog moves to a new version, the resolved override
2848 // no longer matches the lockfile — drift must fire, not silently
2849 // accept.
2850 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2851 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2852 graph.overrides.insert("lodash".into(), "4.17.21".into());
2853 let mut ws_overrides = BTreeMap::new();
2854 ws_overrides.insert("lodash".into(), "catalog:".into());
2855 let mut catalogs = BTreeMap::new();
2856 let mut default_cat = BTreeMap::new();
2857 default_cat.insert("lodash".into(), "4.17.22".into());
2858 catalogs.insert("default".into(), default_cat);
2859 match graph.check_drift(&manifest, &ws_overrides, &[], &catalogs) {
2860 DriftStatus::Stale { reason } => assert!(reason.contains("lodash")),
2861 other => panic!("expected stale, got {other:?}"),
2862 }
2863 }
2864
2865 #[test]
2866 fn fresh_when_pnpm_wrote_override_rewritten_importer_spec() {
2867 // pnpm rewrites the importer `specifier:` to the post-override
2868 // value when a bare-name override applies, so a pnpm-generated
2869 // lockfile records `specifier: 4.17.21` even though
2870 // `package.json` still reads `^4.17.0`. Without override-aware
2871 // drift, every frozen install against a pnpm lockfile with
2872 // overrides reads stale (discussion #174).
2873 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2874 let mut importers = BTreeMap::new();
2875 importers.insert(
2876 ".".to_string(),
2877 vec![DirectDep {
2878 name: "lodash".into(),
2879 dep_path: "lodash@4.17.21".into(),
2880 dep_type: DepType::Production,
2881 specifier: Some("4.17.21".into()),
2882 }],
2883 );
2884 let mut graph = LockfileGraph {
2885 importers,
2886 ..Default::default()
2887 };
2888 graph.overrides.insert("lodash".into(), "4.17.21".into());
2889 let mut ws_overrides = BTreeMap::new();
2890 ws_overrides.insert("lodash".into(), "4.17.21".into());
2891 assert_eq!(
2892 graph.check_drift(&manifest, &ws_overrides, &[], &BTreeMap::new()),
2893 DriftStatus::Fresh,
2894 );
2895 }
2896
2897 #[test]
2898 fn fresh_when_version_keyed_override_rewrites_importer_spec() {
2899 // Discussion #352: an override keyed by name+range
2900 // (`plist@<3.0.5` → `>=3.0.5`) rewrites the importer specifier
2901 // the same way bare-name overrides do. The drift check has to
2902 // parse the key and compare-by-rule, not by raw map lookup,
2903 // otherwise pnpm-written lockfiles read stale on every frozen
2904 // install when version-conditional overrides are in play.
2905 let manifest = make_manifest(&[("plist", "^3.0.4")]);
2906 let mut importers = BTreeMap::new();
2907 importers.insert(
2908 ".".to_string(),
2909 vec![DirectDep {
2910 name: "plist".into(),
2911 dep_path: "plist@3.0.6".into(),
2912 dep_type: DepType::Production,
2913 specifier: Some(">=3.0.5".into()),
2914 }],
2915 );
2916 let mut graph = LockfileGraph {
2917 importers,
2918 ..Default::default()
2919 };
2920 graph
2921 .overrides
2922 .insert("plist@<3.0.5".into(), ">=3.0.5".into());
2923 let mut ws_overrides = BTreeMap::new();
2924 ws_overrides.insert("plist@<3.0.5".into(), ">=3.0.5".into());
2925 assert_eq!(
2926 graph.check_drift(&manifest, &ws_overrides, &[], &BTreeMap::new()),
2927 DriftStatus::Fresh,
2928 );
2929 }
2930
2931 #[test]
2932 fn fresh_when_workspace_yaml_ignored_optional_matches_lockfile() {
2933 // Same drift-shaped bug as overrides: the resolver unions
2934 // `ignoredOptionalDependencies` from package.json and
2935 // pnpm-workspace.yaml, so the lockfile's
2936 // `ignored_optional_dependencies` carries the union, and the
2937 // drift check has to see the same union or the next
2938 // `--frozen-lockfile` run fails with "manifest removes".
2939 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2940 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2941 graph
2942 .ignored_optional_dependencies
2943 .insert("fsevents".to_string());
2944 let ws_ignored = vec!["fsevents".to_string()];
2945 assert_eq!(
2946 graph.check_drift(&manifest, &BTreeMap::new(), &ws_ignored, &BTreeMap::new()),
2947 DriftStatus::Fresh,
2948 );
2949 }
2950
2951 #[test]
2952 fn fresh_when_optional_dep_was_recorded_as_skipped() {
2953 // Regression: a platform-skipped optional dep would otherwise
2954 // loop forever as "manifest adds X". When the previous
2955 // resolve recorded it under skipped_optional_dependencies with
2956 // a matching specifier, drift must report Fresh.
2957 let mut manifest = make_manifest(&[("lodash", "^4.17.0")]);
2958 manifest
2959 .optional_dependencies
2960 .insert("fsevents".into(), "^2.3.0".into());
2961 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2962 let mut inner = BTreeMap::new();
2963 inner.insert("fsevents".to_string(), "^2.3.0".to_string());
2964 graph
2965 .skipped_optional_dependencies
2966 .insert(".".to_string(), inner);
2967 assert_eq!(
2968 graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()),
2969 DriftStatus::Fresh
2970 );
2971 }
2972
2973 #[test]
2974 fn stale_when_new_optional_dep_was_never_seen() {
2975 // Cursor Bugbot regression: a brand-new optional dep that the
2976 // previous resolve never saw must trigger drift, otherwise it
2977 // would silently never get installed. Distinct from a
2978 // platform-skipped optional, which has an entry in
2979 // `skipped_optional_dependencies`.
2980 let mut manifest = make_manifest(&[("lodash", "^4.17.0")]);
2981 manifest
2982 .optional_dependencies
2983 .insert("fsevents".into(), "^2.3.0".into());
2984 let graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2985 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2986 DriftStatus::Stale { reason } => assert!(reason.contains("fsevents"), "{reason}"),
2987 DriftStatus::Fresh => panic!("expected Stale on new optional dep"),
2988 }
2989 }
2990
2991 #[test]
2992 fn stale_when_skipped_optional_dep_specifier_changes() {
2993 // The user bumped the range on a previously-skipped optional;
2994 // the recorded specifier no longer matches the manifest, so we
2995 // need to re-resolve.
2996 let mut manifest = make_manifest(&[("lodash", "^4.17.0")]);
2997 manifest
2998 .optional_dependencies
2999 .insert("fsevents".into(), "^2.4.0".into());
3000 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
3001 let mut inner = BTreeMap::new();
3002 inner.insert("fsevents".to_string(), "^2.3.0".to_string());
3003 graph
3004 .skipped_optional_dependencies
3005 .insert(".".to_string(), inner);
3006 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
3007 DriftStatus::Stale { reason } => assert!(reason.contains("fsevents"), "{reason}"),
3008 DriftStatus::Fresh => panic!("expected Stale on skipped optional spec change"),
3009 }
3010 }
3011
3012 #[test]
3013 fn stale_when_skipped_optional_is_promoted_to_required() {
3014 // Cursor Bugbot regression: if the user moves a previously-
3015 // skipped optional into `dependencies` (same specifier), the
3016 // skipped-list exemption must NOT fire — the dep is now
3017 // required and the lockfile genuinely doesn't include it.
3018 let mut manifest = make_manifest(&[("lodash", "^4.17.0"), ("fsevents", "^2.3.0")]);
3019 // Note: fsevents lives in `dependencies`, not
3020 // `optional_dependencies`, even though the lockfile recorded
3021 // it under skipped optionals from a previous resolve.
3022 manifest.optional_dependencies.clear();
3023 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
3024 let mut inner = BTreeMap::new();
3025 inner.insert("fsevents".to_string(), "^2.3.0".to_string());
3026 graph
3027 .skipped_optional_dependencies
3028 .insert(".".to_string(), inner);
3029 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
3030 DriftStatus::Stale { reason } => assert!(reason.contains("fsevents"), "{reason}"),
3031 DriftStatus::Fresh => {
3032 panic!("expected Stale: skipped-optional exemption must not apply to required deps")
3033 }
3034 }
3035 }
3036
3037 #[test]
3038 fn stale_when_optional_dep_specifier_changes_in_lockfile() {
3039 // Spec changes on optionals that *are* present must still
3040 // drift, so the resolver re-runs when the user bumps a range.
3041 let mut manifest = make_manifest(&[]);
3042 manifest
3043 .optional_dependencies
3044 .insert("fsevents".into(), "^2.4.0".into());
3045 let mut graph = make_graph(&[]);
3046 graph.importers.get_mut(".").unwrap().push(DirectDep {
3047 name: "fsevents".into(),
3048 dep_path: "fsevents@2.3.0".into(),
3049 dep_type: DepType::Optional,
3050 specifier: Some("^2.3.0".into()),
3051 });
3052 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
3053 DriftStatus::Stale { reason } => assert!(reason.contains("fsevents"), "{reason}"),
3054 DriftStatus::Fresh => panic!("expected Stale on optional spec change"),
3055 }
3056 }
3057
3058 #[test]
3059 fn fresh_for_empty_manifest_and_lockfile() {
3060 let manifest = make_manifest(&[]);
3061 let graph = make_graph(&[]);
3062 assert_eq!(
3063 graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()),
3064 DriftStatus::Fresh
3065 );
3066 }
3067
3068 #[test]
3069 fn workspace_drift_detects_change_in_non_root_importer() {
3070 // Build a graph with two importers: root and packages/app.
3071 let root_dep = DirectDep {
3072 name: "lodash".into(),
3073 dep_path: "lodash@4.17.21".into(),
3074 dep_type: DepType::Production,
3075 specifier: Some("^4.17.0".into()),
3076 };
3077 let app_dep = DirectDep {
3078 name: "express".into(),
3079 dep_path: "express@4.18.0".into(),
3080 dep_type: DepType::Production,
3081 specifier: Some("^4.18.0".into()),
3082 };
3083 let mut importers = BTreeMap::new();
3084 importers.insert(".".to_string(), vec![root_dep]);
3085 importers.insert("packages/app".to_string(), vec![app_dep]);
3086 let graph = LockfileGraph {
3087 importers,
3088 packages: BTreeMap::new(),
3089 ..Default::default()
3090 };
3091
3092 let root_manifest = make_manifest(&[("lodash", "^4.17.0")]);
3093 // App manifest changed express to ^5.0.0 — should be detected as stale.
3094 let app_manifest = make_manifest(&[("express", "^5.0.0")]);
3095
3096 let workspace_manifests = vec![
3097 (".".to_string(), root_manifest.clone()),
3098 ("packages/app".to_string(), app_manifest),
3099 ];
3100 match graph.check_drift_workspace(
3101 &workspace_manifests,
3102 &BTreeMap::new(),
3103 &[],
3104 &BTreeMap::new(),
3105 ) {
3106 DriftStatus::Stale { reason } => {
3107 assert!(reason.contains("packages/app"));
3108 assert!(reason.contains("express"));
3109 }
3110 DriftStatus::Fresh => panic!("expected Stale"),
3111 }
3112
3113 // Single-importer check_drift on root only would say Fresh.
3114 assert_eq!(
3115 graph.check_drift(&root_manifest, &BTreeMap::new(), &[], &BTreeMap::new()),
3116 DriftStatus::Fresh
3117 );
3118 }
3119
3120 #[test]
3121 fn filter_deps_prunes_dev_only_subtree() {
3122 // Graph: prod-root (foo) + dev-root (jest) with transitive chains.
3123 // After filtering out Dev, jest + its transitives should be pruned,
3124 // foo + its transitives should remain.
3125 let mut importers = BTreeMap::new();
3126 importers.insert(
3127 ".".to_string(),
3128 vec![
3129 DirectDep {
3130 name: "foo".into(),
3131 dep_path: "foo@1.0.0".into(),
3132 dep_type: DepType::Production,
3133 specifier: Some("^1.0.0".into()),
3134 },
3135 DirectDep {
3136 name: "jest".into(),
3137 dep_path: "jest@29.0.0".into(),
3138 dep_type: DepType::Dev,
3139 specifier: Some("^29.0.0".into()),
3140 },
3141 ],
3142 );
3143
3144 let mut packages = BTreeMap::new();
3145 let mut foo_deps = BTreeMap::new();
3146 foo_deps.insert("bar".to_string(), "2.0.0".to_string());
3147 packages.insert(
3148 "foo@1.0.0".to_string(),
3149 LockedPackage {
3150 name: "foo".into(),
3151 version: "1.0.0".into(),
3152 integrity: None,
3153 dependencies: foo_deps,
3154 dep_path: "foo@1.0.0".into(),
3155 ..Default::default()
3156 },
3157 );
3158 packages.insert(
3159 "bar@2.0.0".to_string(),
3160 LockedPackage {
3161 name: "bar".into(),
3162 version: "2.0.0".into(),
3163 integrity: None,
3164 dependencies: BTreeMap::new(),
3165 dep_path: "bar@2.0.0".into(),
3166 ..Default::default()
3167 },
3168 );
3169 let mut jest_deps = BTreeMap::new();
3170 jest_deps.insert("jest-core".to_string(), "29.0.0".to_string());
3171 packages.insert(
3172 "jest@29.0.0".to_string(),
3173 LockedPackage {
3174 name: "jest".into(),
3175 version: "29.0.0".into(),
3176 integrity: None,
3177 dependencies: jest_deps,
3178 dep_path: "jest@29.0.0".into(),
3179 ..Default::default()
3180 },
3181 );
3182 packages.insert(
3183 "jest-core@29.0.0".to_string(),
3184 LockedPackage {
3185 name: "jest-core".into(),
3186 version: "29.0.0".into(),
3187 integrity: None,
3188 dependencies: BTreeMap::new(),
3189 dep_path: "jest-core@29.0.0".into(),
3190 ..Default::default()
3191 },
3192 );
3193
3194 let graph = LockfileGraph {
3195 importers,
3196 packages,
3197 ..Default::default()
3198 };
3199
3200 let prod = graph.filter_deps(|d| d.dep_type != DepType::Dev);
3201
3202 // Direct deps: only foo, jest dropped
3203 let roots = prod.root_deps();
3204 assert_eq!(roots.len(), 1);
3205 assert_eq!(roots[0].name, "foo");
3206
3207 // Reachable packages: foo + bar (transitive), NOT jest or jest-core
3208 assert!(prod.packages.contains_key("foo@1.0.0"));
3209 assert!(prod.packages.contains_key("bar@2.0.0"));
3210 assert!(!prod.packages.contains_key("jest@29.0.0"));
3211 assert!(!prod.packages.contains_key("jest-core@29.0.0"));
3212 }
3213
3214 // Regression for #50 feedback: `filter_deps` is a structural
3215 // operation and must preserve the source graph's `settings:`
3216 // metadata. A filtered graph that's handed to the lockfile writer
3217 // (as `aube prune` does today) would otherwise reset
3218 // `autoInstallPeers` to its default and silently flip the user's
3219 // choice on the next install.
3220 #[test]
3221 fn filter_deps_preserves_lockfile_settings() {
3222 let graph = LockfileGraph {
3223 importers: BTreeMap::new(),
3224 packages: BTreeMap::new(),
3225 settings: LockfileSettings {
3226 auto_install_peers: false,
3227 exclude_links_from_lockfile: true,
3228 lockfile_include_tarball_url: false,
3229 },
3230 ..Default::default()
3231 };
3232 let filtered = graph.filter_deps(|_| true);
3233 assert!(!filtered.settings.auto_install_peers);
3234 assert!(filtered.settings.exclude_links_from_lockfile);
3235 }
3236
3237 #[test]
3238 fn filter_deps_keeps_shared_transitive_reachable_via_prod() {
3239 // Graph: prod foo → shared, dev jest → shared
3240 // Filtering out Dev should still keep `shared` because foo → shared
3241 // keeps it reachable.
3242 let mut importers = BTreeMap::new();
3243 importers.insert(
3244 ".".to_string(),
3245 vec![
3246 DirectDep {
3247 name: "foo".into(),
3248 dep_path: "foo@1.0.0".into(),
3249 dep_type: DepType::Production,
3250 specifier: Some("^1.0.0".into()),
3251 },
3252 DirectDep {
3253 name: "jest".into(),
3254 dep_path: "jest@29.0.0".into(),
3255 dep_type: DepType::Dev,
3256 specifier: Some("^29.0.0".into()),
3257 },
3258 ],
3259 );
3260
3261 let mut packages = BTreeMap::new();
3262 for (name, ver, deps) in [
3263 ("foo", "1.0.0", vec![("shared", "1.0.0")]),
3264 ("jest", "29.0.0", vec![("shared", "1.0.0")]),
3265 ("shared", "1.0.0", vec![]),
3266 ] {
3267 let mut dep_map = BTreeMap::new();
3268 for (n, v) in deps {
3269 dep_map.insert(n.to_string(), v.to_string());
3270 }
3271 packages.insert(
3272 format!("{name}@{ver}"),
3273 LockedPackage {
3274 name: name.into(),
3275 version: ver.into(),
3276 integrity: None,
3277 dependencies: dep_map,
3278 dep_path: format!("{name}@{ver}"),
3279 ..Default::default()
3280 },
3281 );
3282 }
3283
3284 let graph = LockfileGraph {
3285 importers,
3286 packages,
3287 ..Default::default()
3288 };
3289 let prod = graph.filter_deps(|d| d.dep_type != DepType::Dev);
3290
3291 assert!(prod.packages.contains_key("foo@1.0.0"));
3292 assert!(prod.packages.contains_key("shared@1.0.0"));
3293 assert!(!prod.packages.contains_key("jest@29.0.0"));
3294 }
3295
3296 #[test]
3297 fn subset_to_importer_returns_none_for_missing_importer() {
3298 let graph = LockfileGraph {
3299 importers: BTreeMap::new(),
3300 packages: BTreeMap::new(),
3301 ..Default::default()
3302 };
3303 assert!(graph.subset_to_importer("packages/lib", |_| true).is_none());
3304 }
3305
3306 #[test]
3307 fn subset_to_importer_keeps_only_requested_importer_transitive_closure() {
3308 // Workspace graph with two importers that own independent
3309 // subtrees: packages/lib pulls is-odd → is-number, packages/app
3310 // pulls express. Subsetting to packages/lib must yield a graph
3311 // rooted at `.` containing only is-odd + is-number, with
3312 // express pruned. Matches what `aube deploy --filter @test/lib`
3313 // should write into the target.
3314 let mut importers = BTreeMap::new();
3315 importers.insert(".".to_string(), vec![]);
3316 importers.insert(
3317 "packages/lib".to_string(),
3318 vec![DirectDep {
3319 name: "is-odd".into(),
3320 dep_path: "is-odd@3.0.1".into(),
3321 dep_type: DepType::Production,
3322 specifier: Some("^3.0.1".into()),
3323 }],
3324 );
3325 importers.insert(
3326 "packages/app".to_string(),
3327 vec![DirectDep {
3328 name: "express".into(),
3329 dep_path: "express@4.18.0".into(),
3330 dep_type: DepType::Production,
3331 specifier: Some("^4.18.0".into()),
3332 }],
3333 );
3334
3335 let mut packages = BTreeMap::new();
3336 let mut is_odd_deps = BTreeMap::new();
3337 is_odd_deps.insert("is-number".to_string(), "6.0.0".to_string());
3338 packages.insert(
3339 "is-odd@3.0.1".to_string(),
3340 LockedPackage {
3341 name: "is-odd".into(),
3342 version: "3.0.1".into(),
3343 dependencies: is_odd_deps,
3344 dep_path: "is-odd@3.0.1".into(),
3345 ..Default::default()
3346 },
3347 );
3348 packages.insert(
3349 "is-number@6.0.0".to_string(),
3350 LockedPackage {
3351 name: "is-number".into(),
3352 version: "6.0.0".into(),
3353 dep_path: "is-number@6.0.0".into(),
3354 ..Default::default()
3355 },
3356 );
3357 packages.insert(
3358 "express@4.18.0".to_string(),
3359 LockedPackage {
3360 name: "express".into(),
3361 version: "4.18.0".into(),
3362 dep_path: "express@4.18.0".into(),
3363 ..Default::default()
3364 },
3365 );
3366
3367 let graph = LockfileGraph {
3368 importers,
3369 packages,
3370 ..Default::default()
3371 };
3372 let subset = graph
3373 .subset_to_importer("packages/lib", |_| true)
3374 .expect("packages/lib importer present");
3375
3376 assert_eq!(subset.importers.len(), 1);
3377 let roots = subset.root_deps();
3378 assert_eq!(roots.len(), 1);
3379 assert_eq!(roots[0].name, "is-odd");
3380
3381 assert!(subset.packages.contains_key("is-odd@3.0.1"));
3382 assert!(subset.packages.contains_key("is-number@6.0.0"));
3383 assert!(!subset.packages.contains_key("express@4.18.0"));
3384 }
3385
3386 #[test]
3387 fn subset_to_importer_honors_keep_predicate_for_prod_deploys() {
3388 // packages/lib has both prod (is-odd) and dev (jest) deps.
3389 // `aube deploy --prod` should pass `|d| d.dep_type != Dev` as
3390 // the keep filter; the resulting subset retains only is-odd
3391 // so drift against the target's dev-stripped manifest stays
3392 // clean.
3393 let mut importers = BTreeMap::new();
3394 importers.insert(
3395 "packages/lib".to_string(),
3396 vec![
3397 DirectDep {
3398 name: "is-odd".into(),
3399 dep_path: "is-odd@3.0.1".into(),
3400 dep_type: DepType::Production,
3401 specifier: Some("^3.0.1".into()),
3402 },
3403 DirectDep {
3404 name: "jest".into(),
3405 dep_path: "jest@29.0.0".into(),
3406 dep_type: DepType::Dev,
3407 specifier: Some("^29.0.0".into()),
3408 },
3409 ],
3410 );
3411 let mut packages = BTreeMap::new();
3412 packages.insert(
3413 "is-odd@3.0.1".to_string(),
3414 LockedPackage {
3415 name: "is-odd".into(),
3416 version: "3.0.1".into(),
3417 dep_path: "is-odd@3.0.1".into(),
3418 ..Default::default()
3419 },
3420 );
3421 packages.insert(
3422 "jest@29.0.0".to_string(),
3423 LockedPackage {
3424 name: "jest".into(),
3425 version: "29.0.0".into(),
3426 dep_path: "jest@29.0.0".into(),
3427 ..Default::default()
3428 },
3429 );
3430 let graph = LockfileGraph {
3431 importers,
3432 packages,
3433 ..Default::default()
3434 };
3435
3436 let prod = graph
3437 .subset_to_importer("packages/lib", |d| d.dep_type != DepType::Dev)
3438 .expect("importer present");
3439 let roots = prod.root_deps();
3440 assert_eq!(roots.len(), 1);
3441 assert_eq!(roots[0].name, "is-odd");
3442 assert!(prod.packages.contains_key("is-odd@3.0.1"));
3443 assert!(!prod.packages.contains_key("jest@29.0.0"));
3444 }
3445
3446 #[test]
3447 fn subset_to_importer_preserves_graph_settings() {
3448 // Structural pruning, not a resolution-mode reset: a deploy
3449 // into a target that uses the source workspace's settings
3450 // header (autoInstallPeers / lockfileIncludeTarballUrl)
3451 // should write them through unchanged so a frozen install in
3452 // the target sees the same resolution-mode state.
3453 let mut importers = BTreeMap::new();
3454 importers.insert("packages/lib".to_string(), vec![]);
3455 let graph = LockfileGraph {
3456 importers,
3457 packages: BTreeMap::new(),
3458 settings: LockfileSettings {
3459 auto_install_peers: false,
3460 exclude_links_from_lockfile: true,
3461 lockfile_include_tarball_url: true,
3462 },
3463 ..Default::default()
3464 };
3465 let subset = graph.subset_to_importer("packages/lib", |_| true).unwrap();
3466 assert!(!subset.settings.auto_install_peers);
3467 assert!(subset.settings.exclude_links_from_lockfile);
3468 assert!(subset.settings.lockfile_include_tarball_url);
3469 }
3470
3471 #[test]
3472 fn subset_to_importer_rekeys_skipped_optionals_to_root() {
3473 // `skipped_optional_dependencies` is per-importer. After
3474 // subsetting, only the retained importer's entry should
3475 // survive — rekeyed to `.` so a frozen install in the target
3476 // (which has exactly one importer) doesn't see ghost entries.
3477 let mut importers = BTreeMap::new();
3478 importers.insert("packages/lib".to_string(), vec![]);
3479 importers.insert("packages/app".to_string(), vec![]);
3480 let mut skipped = BTreeMap::new();
3481 let mut lib_skip = BTreeMap::new();
3482 lib_skip.insert("fsevents".to_string(), "^2".to_string());
3483 skipped.insert("packages/lib".to_string(), lib_skip);
3484 let mut app_skip = BTreeMap::new();
3485 app_skip.insert("ghost".to_string(), "*".to_string());
3486 skipped.insert("packages/app".to_string(), app_skip);
3487 let graph = LockfileGraph {
3488 importers,
3489 packages: BTreeMap::new(),
3490 skipped_optional_dependencies: skipped,
3491 ..Default::default()
3492 };
3493 let subset = graph.subset_to_importer("packages/lib", |_| true).unwrap();
3494 assert_eq!(subset.skipped_optional_dependencies.len(), 1);
3495 let root = subset.skipped_optional_dependencies.get(".").unwrap();
3496 assert!(root.contains_key("fsevents"));
3497 assert!(!root.contains_key("ghost"));
3498 }
3499
3500 #[test]
3501 fn workspace_drift_fresh_when_all_importers_match() {
3502 let root_dep = DirectDep {
3503 name: "lodash".into(),
3504 dep_path: "lodash@4.17.21".into(),
3505 dep_type: DepType::Production,
3506 specifier: Some("^4.17.0".into()),
3507 };
3508 let app_dep = DirectDep {
3509 name: "express".into(),
3510 dep_path: "express@4.18.0".into(),
3511 dep_type: DepType::Production,
3512 specifier: Some("^4.18.0".into()),
3513 };
3514 let mut importers = BTreeMap::new();
3515 importers.insert(".".to_string(), vec![root_dep]);
3516 importers.insert("packages/app".to_string(), vec![app_dep]);
3517 let graph = LockfileGraph {
3518 importers,
3519 packages: BTreeMap::new(),
3520 ..Default::default()
3521 };
3522
3523 let workspace_manifests = vec![
3524 (".".to_string(), make_manifest(&[("lodash", "^4.17.0")])),
3525 (
3526 "packages/app".to_string(),
3527 make_manifest(&[("express", "^4.18.0")]),
3528 ),
3529 ];
3530 assert_eq!(
3531 graph.check_drift_workspace(
3532 &workspace_manifests,
3533 &BTreeMap::new(),
3534 &[],
3535 &BTreeMap::new()
3536 ),
3537 DriftStatus::Fresh
3538 );
3539 }
3540
3541 #[allow(clippy::type_complexity)]
3542 fn mk_catalogs(
3543 entries: &[(&str, &[(&str, &str, &str)])],
3544 ) -> BTreeMap<String, BTreeMap<String, CatalogEntry>> {
3545 let mut out: BTreeMap<String, BTreeMap<String, CatalogEntry>> = BTreeMap::new();
3546 for (cat, pkgs) in entries {
3547 let mut inner = BTreeMap::new();
3548 for (pkg, spec, ver) in *pkgs {
3549 inner.insert(
3550 (*pkg).to_string(),
3551 CatalogEntry {
3552 specifier: (*spec).to_string(),
3553 version: (*ver).to_string(),
3554 },
3555 );
3556 }
3557 out.insert((*cat).to_string(), inner);
3558 }
3559 out
3560 }
3561
3562 fn mk_workspace_catalogs(
3563 entries: &[(&str, &[(&str, &str)])],
3564 ) -> BTreeMap<String, BTreeMap<String, String>> {
3565 entries
3566 .iter()
3567 .map(|(cat, pkgs)| {
3568 (
3569 (*cat).to_string(),
3570 pkgs.iter()
3571 .map(|(p, s)| ((*p).to_string(), (*s).to_string()))
3572 .collect(),
3573 )
3574 })
3575 .collect()
3576 }
3577
3578 #[test]
3579 fn catalog_drift_fresh_when_specifiers_match() {
3580 let graph = LockfileGraph {
3581 catalogs: mk_catalogs(&[("default", &[("react", "^18.0.0", "18.2.0")])]),
3582 ..Default::default()
3583 };
3584 let ws = mk_workspace_catalogs(&[("default", &[("react", "^18.0.0")])]);
3585 assert_eq!(graph.check_catalogs_drift(&ws), DriftStatus::Fresh);
3586 }
3587
3588 #[test]
3589 fn catalog_drift_stale_on_changed_specifier() {
3590 let graph = LockfileGraph {
3591 catalogs: mk_catalogs(&[("default", &[("react", "^18.0.0", "18.2.0")])]),
3592 ..Default::default()
3593 };
3594 let ws = mk_workspace_catalogs(&[("default", &[("react", "^19.0.0")])]);
3595 match graph.check_catalogs_drift(&ws) {
3596 DriftStatus::Stale { reason } => assert!(reason.contains("react")),
3597 other => panic!("expected stale, got {other:?}"),
3598 }
3599 }
3600
3601 #[test]
3602 fn catalog_drift_fresh_when_workspace_adds_unused_entry() {
3603 // pnpm only writes referenced entries — an unreferenced
3604 // workspace entry is not drift. The "newly used" transition
3605 // is caught by the importer-level drift check.
3606 let graph = LockfileGraph::default();
3607 let ws = mk_workspace_catalogs(&[("default", &[("react", "^18")])]);
3608 assert_eq!(graph.check_catalogs_drift(&ws), DriftStatus::Fresh);
3609 }
3610
3611 #[test]
3612 fn catalog_drift_stale_on_removed_workspace_entry() {
3613 let graph = LockfileGraph {
3614 catalogs: mk_catalogs(&[("default", &[("react", "^18", "18.2.0")])]),
3615 ..Default::default()
3616 };
3617 let ws = mk_workspace_catalogs(&[]);
3618 assert!(matches!(
3619 graph.check_catalogs_drift(&ws),
3620 DriftStatus::Stale { .. }
3621 ));
3622 }
3623}