aube_lockfile/lib.rs
1pub mod bun;
2pub mod dep_path_filename;
3mod drift;
4pub mod graph_hash;
5mod io;
6pub mod merge;
7pub mod npm;
8mod override_match;
9pub mod pnpm;
10mod source;
11pub mod yarn;
12
13pub use drift::DriftStatus;
14pub use io::{
15 Error, LockfileKind, ParseOptions, active_lockfile_has_conflict_markers, aube_lock_filename,
16 build_canonical_map, detect_existing_lockfile_kind, parse_for_import, parse_json,
17 parse_lockfile, parse_lockfile_with_kind, parse_lockfile_with_kind_and_options,
18 pnpm_lock_filename, read_lockfile, write_lockfile, write_lockfile_as,
19 write_lockfile_preserving_existing,
20};
21pub(crate) use io::{atomic_write_lockfile, current_git_branch};
22pub use merge::{MergeReport, merge_branch_lockfiles};
23pub(crate) use source::normalize_git_fragment;
24pub use source::{
25 GitSource, HostedGit, HostedGitHost, LocalSource, RemoteTarballSource, git_commits_match,
26 parse_git_spec, parse_hosted_git, resolve_dep_edge, shared_local_dep_path,
27};
28
29pub(crate) const EXTRA_PRESERVE_TARBALL_URL: &str = "__aube_preserve_tarball_url";
30
31use smallvec::SmallVec;
32use std::collections::{BTreeMap, BTreeSet};
33
34/// Most npm packages declare zero or one entry in `os`, `cpu`,
35/// `libc`. Two inline `SmallVec` slots cover empty on construction
36/// (zero heap alloc) and one-entry push (still zero heap) for ~99%
37/// of lockfile entries.
38pub type PlatformList = SmallVec<[String; 2]>;
39
40/// Represents a resolved dependency graph from any lockfile format.
41#[derive(Debug, Clone, Default)]
42pub struct LockfileGraph {
43 /// Direct dependencies of the root project (and workspace packages).
44 /// Key: importer path (e.g., "." for root), Value: list of (name, version) pairs.
45 pub importers: BTreeMap<String, Vec<DirectDep>>,
46 /// All resolved packages.
47 pub packages: BTreeMap<String, LockedPackage>,
48 /// Per-graph settings that round-trip through the lockfile header
49 /// (pnpm v9's `settings:` block). Don't affect graph structure;
50 /// stamped into the YAML when writing and read back when parsing,
51 /// so subsequent installs see the same resolution-mode state.
52 pub settings: LockfileSettings,
53 /// Dependency overrides recorded in pnpm-lock.yaml's top-level
54 /// `overrides:` block. Map of raw selector key → version specifier
55 /// (or `npm:` alias). Keys are the user's verbatim selector
56 /// strings — bare name, `foo>bar`, `foo@<2`, `**/foo`, or any
57 /// combination. Round-tripped so subsequent installs can detect
58 /// override drift on a string-compare of the key+value without
59 /// re-running the resolver. The resolver parses these into
60 /// `override_rule::OverrideRule`s at the start of each resolve
61 /// pass.
62 pub overrides: BTreeMap<String, String>,
63 /// pnpm's top-level `packageExtensionsChecksum:` — a `sha256-`
64 /// prefixed `object-hash` of the effective `packageExtensions`
65 /// config. Lets pnpm detect that the extensions changed (and the
66 /// graph must be re-resolved) without re-reading every manifest.
67 /// `None` when there are no package extensions (pnpm omits the
68 /// field). Only the pnpm reader/writer touches this; other formats
69 /// leave it `None`. Computed via
70 /// [`pnpm::package_extensions_checksum`].
71 pub package_extensions_checksum: Option<String>,
72 /// pnpm's top-level `pnpmfileChecksum:` — a `sha256-` prefixed hash
73 /// of the local pnpmfile contents (CRLF-normalized). Lets pnpm
74 /// detect that a `.pnpmfile.cjs`/`.mjs` hook changed without
75 /// re-running it. `None` when no local pnpmfile participates (pnpm
76 /// omits the field). pnpm-only, like `package_extensions_checksum`.
77 /// Computed via [`pnpm::pnpmfile_checksum`].
78 pub pnpmfile_checksum: Option<String>,
79 /// Names listed in the root manifest's `pnpm.ignoredOptionalDependencies`.
80 /// The resolver drops entries in this set from every `optionalDependencies`
81 /// map before enqueueing, matching pnpm's read-package hook. Round-tripped
82 /// through pnpm-lock.yaml's top-level `ignoredOptionalDependencies:` list
83 /// so drift detection can notice when the user edits the field.
84 pub ignored_optional_dependencies: BTreeSet<String>,
85 /// Per-package publish timestamps, keyed by canonical `name@version`
86 /// (no peer suffix). Round-trips through pnpm-lock.yaml's top-level
87 /// `time:` block so `--resolution-mode=time-based` can compute a
88 /// `publishedBy` cutoff from packages already in the lockfile
89 /// without re-fetching packuments.
90 pub times: BTreeMap<String, String>,
91 /// Optional dependencies the resolver intentionally skipped on the
92 /// platform that wrote this lockfile (either filtered by
93 /// `os`/`cpu`/`libc`, or named in
94 /// `pnpm.ignoredOptionalDependencies`). Keyed by importer path,
95 /// inner map is name → specifier captured from `package.json` at
96 /// resolve time.
97 ///
98 /// Drift detection uses this to distinguish "user just added a new
99 /// optional dep" (which is real drift) from "this optional was
100 /// already considered and consciously dropped on this platform"
101 /// (which is *not* drift). Without it, every `--frozen-lockfile`
102 /// install on a platform that skipped a fixture would hard-fail.
103 pub skipped_optional_dependencies: BTreeMap<String, BTreeMap<String, String>>,
104 /// Resolved catalog entries, mirroring pnpm v9's top-level
105 /// `catalogs:` block. Outer key is the catalog name (`default` for
106 /// the unnamed `catalog:` field in `pnpm-workspace.yaml`); inner key
107 /// is the package name. Each entry pairs the original specifier
108 /// from the workspace catalog with the version the resolver chose
109 /// for it. Round-tripped through the lockfile so drift detection
110 /// can fire when a catalog spec changes without re-resolving.
111 pub catalogs: BTreeMap<String, BTreeMap<String, CatalogEntry>>,
112 /// bun's top-level `configVersion` — a second format counter bun
113 /// added alongside `lockfileVersion` to track its own config-
114 /// schema changes. Only the bun parser/writer ever touches this;
115 /// other formats leave it `None`. Round-tripping the parsed
116 /// value keeps the writer from silently downgrading the field
117 /// (e.g. from `2` back to `1`) when bun bumps it in a future
118 /// release.
119 pub bun_config_version: Option<u32>,
120 /// Top-level `patchedDependencies:` block mirrored by bun 1.1+ and
121 /// pnpm 9+. Key: selector (`lodash@4.17.21`), value: relative patch
122 /// file path (`patches/lodash@4.17.21.patch`). Round-tripped
123 /// verbatim so a parse/write cycle doesn't silently drop user
124 /// patches from the lockfile.
125 pub patched_dependencies: BTreeMap<String, String>,
126 /// Top-level `trustedDependencies:` block (bun) — a package-name
127 /// allowlist for lifecycle script execution. Preserved so
128 /// re-emitting a bun.lock doesn't strip the allowlist and cause
129 /// subsequent installs to skip scripts the user explicitly
130 /// approved.
131 ///
132 /// Kept as a `Vec` (not a set) so bun's original order round-trips
133 /// byte-identically; bun emits the list in insertion order. The
134 /// parser is responsible for deduping if the source lockfile
135 /// carried a duplicate.
136 pub trusted_dependencies: Vec<String>,
137 /// Pinned runtimes (pnpm 10.14+ `devEngines.runtime` recording),
138 /// keyed by runtime name (`node`). pnpm models a pinned runtime as
139 /// a synthetic importer dep whose specifier/version carry a
140 /// `runtime:` prefix plus a `packages:` entry keyed
141 /// `<name>@runtime:<version>` holding a `variations` resolution
142 /// with one downloadable artifact per platform. aube lifts that
143 /// encoding into this typed map on parse and re-emits the pnpm
144 /// shape on write (aube-lock.yaml and pnpm-lock.yaml share the
145 /// writer). Foreign formats (npm/yarn/bun) have no runtime shape:
146 /// their parsers leave this empty and their writers skip it.
147 pub runtimes: BTreeMap<String, RuntimePin>,
148 /// Top-level lockfile fields that aren't explicitly modeled on
149 /// `LockfileGraph`. Populated by per-format parsers on best-effort
150 /// basis so the writer can re-emit blocks a future lockfile
151 /// version might add (or ones we haven't promoted to typed fields
152 /// yet) without silently stripping them on round-trip. Each
153 /// parser/writer is responsible for emitting values in its
154 /// format's native serialization.
155 pub extra_fields: BTreeMap<String, serde_json::Value>,
156 /// Per-workspace-importer extras keyed by importer path (`""` for
157 /// root in bun, `"."` for others). Stores anything in the
158 /// workspace entry the typed model doesn't capture so a parse/
159 /// write cycle doesn't drop fields the user (or bun) wrote there.
160 pub workspace_extra_fields: BTreeMap<String, BTreeMap<String, serde_json::Value>>,
161}
162
163/// One entry in a lockfile catalog: the workspace-declared range and the
164/// resolved version. Mirrors pnpm v9's `catalogs:` block exactly.
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub struct CatalogEntry {
167 pub specifier: String,
168 pub version: String,
169}
170
171/// A pinned runtime (Node.js) recorded in the lockfile. Mirrors pnpm
172/// 10.14+'s `devEngines.runtime` encoding: the manifest's requested
173/// range plus the exact resolved version, and one downloadable
174/// artifact per supported platform so any machine reading the
175/// lockfile can fetch the same release without re-resolving.
176#[derive(Debug, Clone, Default, PartialEq, Eq)]
177pub struct RuntimePin {
178 /// The requested range from `devEngines.runtime.version`, without
179 /// the `runtime:` prefix pnpm adds in the importer entry
180 /// (`"^24.4.0"`).
181 pub specifier: String,
182 /// Exact resolved version (`"24.4.1"`).
183 pub version: String,
184 /// Whether the importer entry sits under `devDependencies`
185 /// (devEngines-sourced pins do; pnpm only emits this form today).
186 pub dev: bool,
187 /// `hasBin` flag on the packages entry — always true for real
188 /// runtime pins; round-tripped for byte fidelity.
189 pub has_bin: bool,
190 /// Per-platform artifacts from the `variations` resolution.
191 pub variants: Vec<RuntimeVariant>,
192}
193
194impl RuntimePin {
195 /// The variant whose target list matches `(os, cpu, libc)`. `libc`
196 /// follows pnpm's convention: `Some("musl")` matches only
197 /// musl-tagged targets; `None` matches targets without a libc tag.
198 pub fn variant_for(&self, os: &str, cpu: &str, libc: Option<&str>) -> Option<&RuntimeVariant> {
199 self.variants.iter().find(|v| {
200 v.targets
201 .iter()
202 .any(|t| t.os == os && t.cpu == cpu && t.libc.as_deref() == libc)
203 })
204 }
205}
206
207/// One platform-specific artifact inside a runtime pin's `variations`
208/// resolution. Field set mirrors pnpm's `BinaryResolution` +
209/// `PlatformAssetResolution` pair.
210#[derive(Debug, Clone, Default, PartialEq, Eq)]
211pub struct RuntimeVariant {
212 /// Platforms this artifact serves (usually exactly one).
213 pub targets: Vec<RuntimeTarget>,
214 /// `"tarball"` or `"zip"`.
215 pub archive: String,
216 /// Download URL for the artifact.
217 pub url: String,
218 /// SRI integrity (`sha256-<base64>` — Node publishes SHA-256
219 /// checksums for release artifacts).
220 pub integrity: String,
221 /// Executable map. pnpm writes either a bare string (`bin/node`,
222 /// meaning the `node` bin) or a `name → path` map; both parse into
223 /// this struct and the original shape round-trips via
224 /// [`Self::bin_is_bare_string`].
225 pub bin: BTreeMap<String, String>,
226 /// True when the source lockfile wrote `bin:` as a bare string;
227 /// preserved so a parse/write cycle stays byte-identical.
228 pub bin_is_bare_string: bool,
229 /// Top-level directory to strip when extracting (pnpm sets this on
230 /// zip archives, whose entries are rooted at
231 /// `node-v<V>-win-<arch>/`).
232 pub prefix: Option<String>,
233}
234
235/// One `(os, cpu, libc)` triple a runtime variant targets. Values use
236/// Node's `process.platform` / `process.arch` vocabulary (`win32`,
237/// `darwin`, `linux`; `x64`, `arm64`), with `libc: Some("musl")` only
238/// on musl builds.
239#[derive(Debug, Clone, Default, PartialEq, Eq)]
240pub struct RuntimeTarget {
241 pub os: String,
242 pub cpu: String,
243 pub libc: Option<String>,
244}
245
246/// Per-graph settings that mirror pnpm v9's `settings:` header.
247/// Extend as more knobs become round-trip-aware.
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub struct LockfileSettings {
250 /// pnpm's `auto-install-peers` — when false the resolver leaves
251 /// unmet peers alone (just warns) instead of dragging them in.
252 pub auto_install_peers: bool,
253 /// pnpm's `exclude-links-from-lockfile` — not yet honored by aube
254 /// but round-tripped for lockfile compatibility.
255 pub exclude_links_from_lockfile: bool,
256 /// pnpm's `lockfile-include-tarball-url` — when true the writer
257 /// emits the full registry tarball URL in each package's
258 /// `resolution.tarball:` field alongside `integrity:`. Makes the
259 /// lockfile self-contained so air-gapped installs don't need to
260 /// derive the URL from `.npmrc`. Round-tripped through the
261 /// `settings:` header so it survives parse/write cycles without
262 /// re-reading `.npmrc`.
263 pub lockfile_include_tarball_url: bool,
264}
265
266impl Default for LockfileSettings {
267 fn default() -> Self {
268 Self {
269 auto_install_peers: true,
270 exclude_links_from_lockfile: false,
271 lockfile_include_tarball_url: false,
272 }
273 }
274}
275
276/// A direct dependency of a workspace importer.
277#[derive(Debug, Clone)]
278pub struct DirectDep {
279 pub name: String,
280 /// The dep_path key in the lockfile (e.g., "is-odd@3.0.1")
281 pub dep_path: String,
282 pub dep_type: DepType,
283 /// The specifier as written in package.json at the time the lockfile was
284 /// generated (e.g., `"^4.17.0"`). Used by drift detection to compare against
285 /// the current manifest. Populated by formats that record it
286 /// (pnpm importers and npm root/workspace package entries).
287 pub specifier: Option<String>,
288}
289
290#[derive(Debug, Clone, Copy, PartialEq, Eq)]
291pub enum DepType {
292 Production,
293 Dev,
294 Optional,
295}
296
297/// Render a `DepType` as the matching `package.json` field name
298/// (`dependencies` / `devDependencies` / `optionalDependencies`).
299/// Single source of truth so drift diagnostics, install summaries,
300/// the `outdated` / `why` / `deprecations` renderers, and the
301/// `outdated --json` shape all agree on the spelling.
302pub fn dep_type_label(dt: DepType) -> &'static str {
303 match dt {
304 DepType::Production => "dependencies",
305 DepType::Dev => "devDependencies",
306 DepType::Optional => "optionalDependencies",
307 }
308}
309
310/// A single resolved package in the lockfile.
311///
312/// The `dependencies` map keys are dep names and values are the dependency's
313/// dep_path *tail* — i.e. the string that follows `<name>@`. For a plain
314/// package this is just the version (`"4.17.21"`); for a package with its
315/// own peer context it includes the suffix (`"18.2.0(prop-types@15.8.1)"`).
316/// Combining the key with its value reproduces the full dep_path (which is
317/// also the key in `LockfileGraph.packages`).
318#[derive(Debug, Clone, Default)]
319pub struct LockedPackage {
320 /// Package name (e.g., "lodash")
321 pub name: String,
322 /// Exact resolved version (e.g., "4.17.21")
323 pub version: String,
324 /// Integrity hash (e.g., "sha512-...")
325 pub integrity: Option<String>,
326 /// Dependencies of this package (name -> dep_path tail, see struct docs)
327 pub dependencies: BTreeMap<String, String>,
328 /// Optional dependency edges for this package. Active optional edges are
329 /// also mirrored in `dependencies` so graph walks and the linker continue
330 /// to see them; this separate map lets platform filtering prune optional
331 /// edges without touching regular dependencies.
332 pub optional_dependencies: BTreeMap<String, String>,
333 /// Peer dependency ranges as *declared* by the package (from its
334 /// package.json / packument). These are the constraints; the resolved
335 /// versions live in `dependencies` after the peer-context pass runs.
336 pub peer_dependencies: BTreeMap<String, String>,
337 /// `peerDependenciesMeta` entries, keyed by peer name.
338 pub peer_dependencies_meta: BTreeMap<String, PeerDepMeta>,
339 /// The dep_path key used in the lockfile. For packages with resolved
340 /// peer contexts this includes the suffix, e.g.
341 /// `"styled-components@6.1.0(react@18.2.0)"`.
342 pub dep_path: String,
343 /// Set for non-registry packages (those installed via `file:` or
344 /// `link:` specifiers). `None` for the common case of a package
345 /// resolved from an npm registry, where `integrity` is the full
346 /// record of where the bits came from.
347 pub local_source: Option<LocalSource>,
348 /// `os` / `cpu` / `libc` arrays from the package's manifest. Used
349 /// by the resolver to filter optional deps that can't run on the
350 /// current (or user-overridden) platform. Empty arrays mean no
351 /// constraint.
352 pub os: PlatformList,
353 pub cpu: PlatformList,
354 pub libc: PlatformList,
355 /// Names declared in the package's own `bundledDependencies`. These
356 /// ship inside the parent tarball's `node_modules/`, so the resolver
357 /// neither fetches nor recurses into them, and the linker avoids
358 /// creating sibling symlinks that would shadow the bundled tree.
359 /// An empty Vec means "no bundled deps"; `None` is kept as a
360 /// distinct value only inside the resolver and collapsed to empty
361 /// here because the lockfile round-trip doesn't need to preserve
362 /// the "unset" vs "empty list" distinction.
363 pub bundled_dependencies: Vec<String>,
364 /// Full registry tarball URL for registry-sourced packages. Only
365 /// populated when `LockfileSettings::lockfile_include_tarball_url`
366 /// is active on this graph; otherwise `None` and the lockfile
367 /// writer derives the URL at fetch time from the configured
368 /// registry. `local_source`-backed packages (file:, link:, git:,
369 /// remote tarball) already carry their own URL via `LocalSource`
370 /// and don't populate this field.
371 pub tarball_url: Option<String>,
372 /// pnpm `resolution.gitHosted` for registry-keyed packages. Remote
373 /// tarball sources carry the same flag on `RemoteTarballSource`,
374 /// but registry entries keep `local_source: None`, so this field
375 /// preserves third-party pnpm lockfiles that mark registry-shaped
376 /// tarballs as hosted git.
377 pub registry_git_hosted: bool,
378 /// For npm-alias deps (`"h3-v2": "npm:h3@2.0.1-rc.20"`): the real
379 /// package name on the registry (`"h3"`). `None` means the entry
380 /// is not aliased and `name` already holds the registry name.
381 ///
382 /// Install semantics when `Some(real)`:
383 /// - `name` is the *alias* — that's the folder under `node_modules/`,
384 /// the symlink name for transitive deps, and the key every package
385 /// that declares this dep refers to.
386 /// - `alias_of` is the real package name used for tarball URL lookup,
387 /// store index keying, and packument fetches.
388 /// - `version` is the real resolved version.
389 ///
390 /// `registry_name()` returns the right name for registry IO; every
391 /// call site that talks to the registry or the CAS uses that helper.
392 pub alias_of: Option<String>,
393 /// Yarn berry's `checksum:` field, preserved verbatim when parsing a
394 /// yarn 2+ lockfile (e.g. `"10c0/<blake2b-hex>"`). The format is
395 /// yarn-specific — it uses a yarn-chosen hash family prefixed with
396 /// the `cacheKey` that produced it — and doesn't share a hash
397 /// algorithm with `integrity` (sha-512). When re-emitting a yarn
398 /// berry lockfile we write this field back as-is; packages that
399 /// didn't come through a berry parse (e.g. freshly-resolved entries
400 /// in a new install) leave this `None` and the writer omits the
401 /// `checksum:` field, which berry tolerates at the default
402 /// `checksumBehavior: throw` when the cache is fresh.
403 pub yarn_checksum: Option<String>,
404 /// `engines:` from the package's manifest, round-tripped through
405 /// the lockfile so pnpm-style writers can emit the same flow-form
406 /// `engines: {node: '>=8'}` line pnpm writes. Empty map means
407 /// "no engines declared" — the writer skips the field entirely.
408 pub engines: BTreeMap<String, String>,
409 /// `bin:` map from the package's manifest, normalized to
410 /// `name → path`. An empty map means "no bins declared".
411 ///
412 /// pnpm-style writers derive `hasBin: true` from
413 /// `!bin.is_empty()` (they don't preserve the names/paths); bun's
414 /// format emits the full map on the package's meta block. Keeping
415 /// the map here lets both writers render byte-identical output
416 /// without an extra tarball-level re-parse.
417 pub bin: BTreeMap<String, String>,
418 /// Dependency ranges as declared in this package's own
419 /// `package.json` — keyed by dep name, values are the raw
420 /// specifiers (`"^4.1.0"`, `"~1.1.4"`, `"workspace:*"`, …).
421 ///
422 /// Distinct from [`Self::dependencies`], which stores the
423 /// *resolved* dep_path tail (`"4.3.0"`). npm / yarn / bun
424 /// lockfiles preserve the declared ranges on every nested
425 /// package entry — rewriting them to the resolved pins is the
426 /// biggest source of round-trip churn against those formats. This
427 /// map lets writers emit the declared range when available and
428 /// fall back to the resolved pin otherwise (e.g. when the source
429 /// lockfile was pnpm, whose `snapshots:` only carries pins).
430 ///
431 /// Empty means "unknown" — writers should fall back to pins.
432 /// Covers production *and* optional dependencies in one map since
433 /// a package can't declare the same name twice across those
434 /// sections.
435 pub declared_dependencies: BTreeMap<String, String>,
436 /// Package's `license` field, collapsed to the simple string
437 /// form. Round-tripped so npm's lockfile keeps its per-entry
438 /// `"license": "MIT"` line; pnpm / yarn / bun don't record
439 /// licenses and leave this `None` on parse.
440 pub license: Option<String>,
441 /// Package's funding URL, extracted from whatever shape the
442 /// manifest's `funding:` field took (string / object / array).
443 /// Round-tripped so npm's lockfile keeps its per-entry
444 /// `"funding": {"url": "…"}` block.
445 pub funding_url: Option<String>,
446 /// pnpm `snapshots:` `optional: true` flag, marking a package
447 /// reachable only through optional edges (typically platform-
448 /// specific binaries like `@reflink/reflink-darwin-arm64`). pnpm
449 /// uses this on the next install to decide whether the entry
450 /// should be skipped on a non-matching platform; dropping it on
451 /// round-trip would let pnpm treat the package as required.
452 /// Always `false` outside the pnpm parse/write path.
453 pub optional: bool,
454 /// pnpm `snapshots:` `transitivePeerDependencies:` list — peer
455 /// names that bubble up transitively through this package. pnpm
456 /// reads it during hoisting and as a resolver staleness signal
457 /// (`resolveDependencies.ts`'s non-zero-length check); a missing
458 /// list looks like a graph change and triggers needless re-
459 /// resolution on the next pnpm install. Empty outside the pnpm
460 /// parse/write path. Fresh resolves leave this empty too — pnpm
461 /// recomputes it from the graph during `resolvePeers` when needed.
462 pub transitive_peer_dependencies: Vec<String>,
463 /// Per-package-meta extras preserved verbatim from the source
464 /// lockfile. Captures fields the typed model doesn't yet cover
465 /// (`deprecated`, `hasInstallScript`, bun's `optionalPeers`, and
466 /// anything a future lockfile bump adds) so a parse/write cycle
467 /// doesn't drop them. Each format's writer re-emits what makes
468 /// sense there — bun inlines the extras back on the package-entry
469 /// meta object, pnpm / yarn / npm currently ignore them.
470 pub extra_meta: BTreeMap<String, serde_json::Value>,
471}
472
473impl LockedPackage {
474 /// The package name to use for registry / store operations — the real
475 /// name behind an npm-alias when aliased, otherwise just `name`. Used
476 /// at every site that derives a tarball URL, a packument URL, or an
477 /// aube-store cache key so aliased entries hit the actual package
478 /// instead of the alias-qualified name.
479 pub fn registry_name(&self) -> &str {
480 self.alias_of.as_deref().unwrap_or(&self.name)
481 }
482
483 /// Canonical `"name@version"` key used as a handle in patches,
484 /// approve-builds prompts, lockfile canonical maps, and display
485 /// paths. Not the dep-path — that includes peer-context suffixes.
486 pub fn spec_key(&self) -> String {
487 format!("{}@{}", self.name, self.version)
488 }
489
490 /// Exact approval key for non-registry package sources.
491 ///
492 /// Name-wide build approvals are only trustworthy for packages
493 /// fetched from a registry. Source-backed entries need to be
494 /// approved by their source identity as pnpm records it in
495 /// lockfile keys / `allowBuilds` placeholders.
496 pub fn source_approval_key(&self) -> Option<String> {
497 self.local_source
498 .as_ref()
499 .map(|source| format!("{}@{}", self.registry_name(), source.specifier()))
500 }
501
502 /// Declared peer ranges with pnpm's meta-only peers folded in as `*`.
503 ///
504 /// pnpm records a `peerDependencies: { x: '*' }` entry for every
505 /// `peerDependenciesMeta` key a package ships without an explicit
506 /// range (debug's optional `supports-color`, typescript-eslint's
507 /// optional `typescript`, …). This returns `peer_dependencies` with
508 /// those meta-only keys added as `*` — both what the pnpm writer emits
509 /// in `packages:` and the "declared peers" set the transitive-peer
510 /// pass subtracts resolved deps from. Centralizing the rule keeps the
511 /// writer and the resolver's transitive-peer pass from drifting.
512 pub fn peer_dependencies_with_meta_defaults(&self) -> BTreeMap<String, String> {
513 let mut deps = self.peer_dependencies.clone();
514 for name in self.peer_dependencies_meta.keys() {
515 deps.entry(name.clone()).or_insert_with(|| "*".to_string());
516 }
517 deps
518 }
519}
520
521#[cfg(test)]
522mod locked_package_tests {
523 use super::*;
524 use std::path::PathBuf;
525
526 fn pkg() -> LockedPackage {
527 LockedPackage {
528 name: "pkg".to_string(),
529 version: "1.0.0".to_string(),
530 integrity: Some("sha512-abc".to_string()),
531 dependencies: BTreeMap::new(),
532 optional_dependencies: BTreeMap::new(),
533 peer_dependencies: BTreeMap::new(),
534 peer_dependencies_meta: BTreeMap::new(),
535 dep_path: "pkg@1.0.0".to_string(),
536 local_source: None,
537 os: PlatformList::default(),
538 cpu: PlatformList::default(),
539 libc: PlatformList::default(),
540 bundled_dependencies: Vec::new(),
541 tarball_url: None,
542 registry_git_hosted: false,
543 alias_of: None,
544 yarn_checksum: None,
545 engines: BTreeMap::new(),
546 bin: BTreeMap::new(),
547 declared_dependencies: BTreeMap::new(),
548 license: None,
549 funding_url: None,
550 optional: false,
551 transitive_peer_dependencies: Vec::new(),
552 extra_meta: BTreeMap::new(),
553 }
554 }
555
556 #[test]
557 fn source_approval_key_ignores_registry_git_hosted_packages() {
558 let mut pkg = pkg();
559 pkg.registry_git_hosted = true;
560
561 assert_eq!(pkg.source_approval_key(), None);
562 }
563
564 #[test]
565 fn source_approval_key_uses_source_spec_for_local_sources() {
566 let mut pkg = pkg();
567 pkg.dep_path = "pkg@file+abc(peer@1.0.0)".to_string();
568 pkg.local_source = Some(LocalSource::Directory(PathBuf::from("vendor/pkg")));
569
570 assert_eq!(
571 pkg.source_approval_key(),
572 Some("pkg@file:vendor/pkg".to_string())
573 );
574 }
575
576 #[test]
577 fn source_approval_key_uses_raw_remote_tarball_url() {
578 let mut pkg = pkg();
579 pkg.dep_path = "pkg@url+abc123".to_string();
580 pkg.local_source = Some(LocalSource::RemoteTarball(RemoteTarballSource {
581 url: "https://example.com/pkg.tgz".to_string(),
582 integrity: "sha512-tarball".to_string(),
583 git_hosted: false,
584 }));
585
586 assert_eq!(
587 pkg.source_approval_key(),
588 Some("pkg@https://example.com/pkg.tgz".to_string())
589 );
590 }
591}
592
593/// Metadata about a single declared peer dependency. Matches the shape of
594/// `peerDependenciesMeta` in package.json.
595#[derive(Debug, Clone, Default, PartialEq, Eq)]
596pub struct PeerDepMeta {
597 /// When true, an unmet peer is silently allowed rather than warned about.
598 pub optional: bool,
599}
600
601impl LockfileGraph {
602 /// Get all direct dependencies of the root project.
603 pub fn root_deps(&self) -> &[DirectDep] {
604 self.importers.get(".").map(|v| v.as_slice()).unwrap_or(&[])
605 }
606
607 /// Get a package by its dep_path key.
608 pub fn get_package(&self, dep_path: &str) -> Option<&LockedPackage> {
609 self.packages.get(dep_path)
610 }
611
612 /// BFS the transitive closure of `roots` through `self.packages`,
613 /// returning every reachable dep_path (roots included). Missing
614 /// roots are skipped silently — a root without a matching package
615 /// is treated as a leaf, which matches what `filter_deps` /
616 /// `subset_to_importer` need when a retained importer points at a
617 /// package that was never fully installed (e.g. optional deps
618 /// filtered out on this platform).
619 ///
620 /// `LockedPackage.dependencies` maps `child_name → dep_path tail`,
621 /// so each child's full key reconstructs as `{child_name}@{tail}`.
622 fn transitive_closure<'a>(
623 &self,
624 roots: impl IntoIterator<Item = &'a str>,
625 ) -> std::collections::HashSet<String> {
626 let mut reachable: std::collections::HashSet<String> = std::collections::HashSet::new();
627 let mut queue: std::collections::VecDeque<String> = std::collections::VecDeque::new();
628 for root in roots {
629 if reachable.insert(root.to_string()) {
630 queue.push_back(root.to_string());
631 }
632 }
633 while let Some(dep_path) = queue.pop_front() {
634 let Some(pkg) = self.packages.get(&dep_path) else {
635 continue;
636 };
637 for (child_name, child_version) in &pkg.dependencies {
638 let child_key = format!("{child_name}@{child_version}");
639 if reachable.insert(child_key.clone()) {
640 queue.push_back(child_key);
641 }
642 }
643 }
644 reachable
645 }
646
647 /// Clone only the `packages` entries whose keys are in `reachable`.
648 /// Paired with `transitive_closure` to produce the pruned
649 /// `LockfileGraph.packages` for `filter_deps` / `subset_to_importer`.
650 fn packages_restricted_to(
651 &self,
652 reachable: &std::collections::HashSet<String>,
653 ) -> BTreeMap<String, LockedPackage> {
654 self.packages
655 .iter()
656 .filter(|(dep_path, _)| reachable.contains(*dep_path))
657 .map(|(k, v)| (k.clone(), v.clone()))
658 .collect()
659 }
660
661 /// Produce a new `LockfileGraph` containing only the direct deps that match
662 /// `keep` and the transitive deps reachable from them.
663 ///
664 /// Used by `install --prod` to drop `DepType::Dev` roots and everything
665 /// only reachable through them, and by `install --no-optional` for optional
666 /// deps. The filter runs over every importer's direct-dep list, so workspace
667 /// projects behave correctly.
668 ///
669 /// Packages that are reachable from a retained root through a transitive
670 /// chain are kept even if a pruned dev dep also happened to depend on them —
671 /// the check is "is this package reachable from any retained root?", not
672 /// "was this package introduced by a retained root?".
673 pub fn filter_deps<F>(&self, keep: F) -> LockfileGraph
674 where
675 F: Fn(&DirectDep) -> bool,
676 {
677 // Filter each importer's DirectDep list.
678 let importers: BTreeMap<String, Vec<DirectDep>> = self
679 .importers
680 .iter()
681 .map(|(path, deps)| {
682 let filtered: Vec<DirectDep> = deps.iter().filter(|d| keep(d)).cloned().collect();
683 (path.clone(), filtered)
684 })
685 .collect();
686
687 // BFS from every retained root across every importer.
688 let reachable = self.transitive_closure(
689 importers
690 .values()
691 .flat_map(|deps| deps.iter().map(|d| d.dep_path.as_str())),
692 );
693 let packages = self.packages_restricted_to(&reachable);
694
695 LockfileGraph {
696 importers,
697 packages,
698 // Preserve the source graph's settings — filter is a
699 // structural operation, not a resolution-mode reset.
700 // Writing the filtered graph (e.g. from `aube prune`) must
701 // emit the same `settings:` header the user chose.
702 settings: self.settings.clone(),
703 // Overrides are part of the user's resolution intent and
704 // should survive structural filters like `aube prune`.
705 overrides: self.overrides.clone(),
706 // Config checksums describe the inputs that produced the
707 // graph, not its shape — a structural filter must carry
708 // them through unchanged.
709 package_extensions_checksum: self.package_extensions_checksum.clone(),
710 pnpmfile_checksum: self.pnpmfile_checksum.clone(),
711 ignored_optional_dependencies: self.ignored_optional_dependencies.clone(),
712 // Times follow the same round-trip invariant as settings:
713 // filter doesn't change what versions are locked, so the
714 // per-package publish timestamps carry through unchanged.
715 times: self.times.clone(),
716 skipped_optional_dependencies: self.skipped_optional_dependencies.clone(),
717 catalogs: self.catalogs.clone(),
718 bun_config_version: self.bun_config_version,
719 patched_dependencies: self.patched_dependencies.clone(),
720 trusted_dependencies: self.trusted_dependencies.clone(),
721 // Runtime pins are graph-wide resolution intent, same as
722 // overrides/catalogs — structural filters carry them.
723 runtimes: self.runtimes.clone(),
724 extra_fields: self.extra_fields.clone(),
725 workspace_extra_fields: self.workspace_extra_fields.clone(),
726 }
727 }
728
729 /// Produce a new `LockfileGraph` rooted at the importer at
730 /// `importer_path`, with its transitive closure preserved and every
731 /// other importer dropped. The retained importer is remapped to
732 /// `"."` because the consumer installs the result as a standalone
733 /// project.
734 ///
735 /// Used by `aube deploy`: reading the source workspace lockfile
736 /// and subsetting it to the deployed package lets a frozen install
737 /// in the target reproduce the workspace's exact versions without
738 /// re-resolving against the registry. `keep` filters the importer's
739 /// direct deps the same way `filter_deps` does, so `--prod` /
740 /// `--dev` / `--no-optional` deploys drop the matching roots.
741 ///
742 /// Returns `None` if `importer_path` is not present in
743 /// `self.importers`. Graph-wide metadata (`settings`, `overrides`,
744 /// `times`, `catalogs`, `ignored_optional_dependencies`) is copied
745 /// verbatim — structural pruning, not a resolution-mode reset.
746 /// Callers targeting a non-workspace install may want to clear
747 /// workspace-scope fields that would otherwise trigger drift
748 /// detection against a rewritten target manifest.
749 pub fn subset_to_importer<F>(&self, importer_path: &str, keep: F) -> Option<LockfileGraph>
750 where
751 F: Fn(&DirectDep) -> bool,
752 {
753 let src_deps = self.importers.get(importer_path)?;
754 let kept: Vec<DirectDep> = src_deps.iter().filter(|d| keep(d)).cloned().collect();
755
756 // BFS the transitive closure from retained roots, scoped to
757 // just this importer's kept direct deps.
758 let reachable = self.transitive_closure(kept.iter().map(|d| d.dep_path.as_str()));
759 let packages = self.packages_restricted_to(&reachable);
760
761 // Per-importer metadata: keep only the retained importer's
762 // entry, rekeyed to `.`. The source workspace's other
763 // importers are meaningless in a target that has exactly one.
764 let mut skipped_optional_dependencies = BTreeMap::new();
765 if let Some(skipped) = self.skipped_optional_dependencies.get(importer_path) {
766 skipped_optional_dependencies.insert(".".to_string(), skipped.clone());
767 }
768
769 let mut importers = BTreeMap::new();
770 importers.insert(".".to_string(), kept);
771
772 Some(LockfileGraph {
773 importers,
774 packages,
775 settings: self.settings.clone(),
776 overrides: self.overrides.clone(),
777 // The deployed subset inherits the source workspace's
778 // config checksums: the same `packageExtensions`/pnpmfile
779 // governed the resolution being subsetted.
780 package_extensions_checksum: self.package_extensions_checksum.clone(),
781 pnpmfile_checksum: self.pnpmfile_checksum.clone(),
782 ignored_optional_dependencies: self.ignored_optional_dependencies.clone(),
783 times: self.times.clone(),
784 skipped_optional_dependencies,
785 catalogs: self.catalogs.clone(),
786 bun_config_version: self.bun_config_version,
787 patched_dependencies: self.patched_dependencies.clone(),
788 trusted_dependencies: self.trusted_dependencies.clone(),
789 runtimes: self.runtimes.clone(),
790 extra_fields: self.extra_fields.clone(),
791 workspace_extra_fields: self.workspace_extra_fields.clone(),
792 })
793 }
794
795 /// Overlay per-package metadata fields from `prior` onto `self`
796 /// for every `(name, version)` that survives in both graphs.
797 /// Carries forward only fields the abbreviated packument (npm
798 /// corgi) doesn't ship — `license`, `funding_url`, and the
799 /// bun-format `configVersion` — so a fresh re-resolve against
800 /// the same spec set doesn't lose them.
801 ///
802 /// Keyed by canonical `name@version`, so a peer-context rewrite
803 /// between the old and new graph still lines up. `self`'s own
804 /// values win when set (fresh registry data is authoritative);
805 /// `prior`'s fill in only the `None` / empty slots. Safe to call
806 /// on any pair of graphs — parsing the old lockfile is the
807 /// caller's concern.
808 pub fn overlay_metadata_from(&mut self, prior: &LockfileGraph) {
809 // Build a canonical `name@version → prior pkg` lookup once so
810 // repeated peer-context variants in `self.packages` all hit
811 // the same prior entry.
812 let prior_index = build_canonical_map(prior);
813 for pkg in self.packages.values_mut() {
814 let key = pkg.spec_key();
815 let Some(prior_pkg) = prior_index.get(&key) else {
816 continue;
817 };
818 if pkg.license.is_none() && prior_pkg.license.is_some() {
819 pkg.license = prior_pkg.license.clone();
820 }
821 if pkg.funding_url.is_none() && prior_pkg.funding_url.is_some() {
822 pkg.funding_url = prior_pkg.funding_url.clone();
823 }
824 // Per-entry extras (`deprecated`, `optionalPeers`,
825 // format-specific fields bun/npm/yarn wrote into the
826 // meta block) can't be recovered from a fresh resolve,
827 // so carry them forward when the newer graph doesn't
828 // already carry its own. `self`-side keys always win.
829 for (k, v) in &prior_pkg.extra_meta {
830 pkg.extra_meta.entry(k.clone()).or_insert_with(|| v.clone());
831 }
832 }
833 if self.bun_config_version.is_none() {
834 self.bun_config_version = prior.bun_config_version;
835 }
836 if self.patched_dependencies.is_empty() {
837 self.patched_dependencies = prior.patched_dependencies.clone();
838 }
839 if self.trusted_dependencies.is_empty() {
840 self.trusted_dependencies = prior.trusted_dependencies.clone();
841 }
842 // Runtime pins can't be recovered from a fresh package resolve
843 // (they come from devEngines resolution, a separate pass), so a
844 // re-resolved graph that hasn't re-pinned yet inherits the
845 // prior pin. The install driver overwrites it when the
846 // devEngines range drifted.
847 if self.runtimes.is_empty() {
848 self.runtimes = prior.runtimes.clone();
849 }
850 if self.extra_fields.is_empty() {
851 self.extra_fields = prior.extra_fields.clone();
852 }
853 if self.workspace_extra_fields.is_empty() {
854 self.workspace_extra_fields = prior.workspace_extra_fields.clone();
855 }
856 }
857}