Skip to main content

aube_resolver/
lib.rs

1mod builder;
2mod catalog;
3mod error;
4mod local_source;
5pub mod override_rule;
6mod package_ext;
7mod peer_context;
8pub mod platform;
9mod primer;
10mod resolve;
11mod semver_util;
12mod trust;
13mod types;
14
15pub use error::{AgeGateDetails, CatalogDetails, Error, ExoticSubdepDetails, NoMatchDetails};
16pub use package_ext::is_deprecation_allowed;
17pub use peer_context::{
18    PeerContextOptions, UnmetPeer, apply_peer_contexts, detect_unmet_peers,
19    hoist_auto_installed_peers,
20};
21pub use platform::{SupportedArchitectures, is_supported};
22pub use primer::{PruneStats as PrimerPruneStats, prune_cache as prune_primer_cache};
23pub use trust::{MissingTimeDetails as MissingTrustTimeDetails, TrustDowngradeDetails};
24pub use trust::{TrustEvidence, TrustExcludeParseError, TrustExcludeRules};
25pub use types::{
26    DependencyPolicy, MinimumReleaseAge, PackageExtension, ReadPackageHook, ResolutionMode,
27    ResolvedPackage, TrustPolicy,
28};
29
30use semver_util::version_satisfies;
31
32#[cfg(test)]
33use aube_lockfile::{DirectDep, LocalSource, LockedPackage, LockfileGraph};
34#[cfg(test)]
35use aube_manifest::PackageJson;
36#[cfg(test)]
37use error::{
38    RegistryErrorKind, build_age_gate, build_no_match, classify_registry_error,
39    format_registry_help,
40};
41#[cfg(test)]
42use local_source::{dep_path_for, should_block_exotic_subdep};
43#[cfg(test)]
44use package_ext::{apply_package_extensions, package_selector_matches, pick_override_spec};
45#[cfg(test)]
46use peer_context::{
47    apply_dedupe_peers_to_key, contains_canonical_back_ref, dedupe_peer_suffixes,
48    dedupe_peer_variants, hash_peer_suffix,
49};
50#[cfg(test)]
51use semver_util::{PickResult, pick_version, strip_alias_prefix};
52#[cfg(test)]
53use types::format_iso8601_utc;
54
55use aube_lockfile::DepType;
56use aube_registry::Packument;
57use aube_registry::client::RegistryClient;
58use rustc_hash::FxHashMap;
59use std::collections::{BTreeMap, BTreeSet};
60use std::path::PathBuf;
61use std::sync::Arc;
62use tokio::sync::mpsc;
63
64/// BFS dependency resolver.
65pub struct Resolver {
66    client: Arc<RegistryClient>,
67    cache: FxHashMap<String, Packument>,
68    /// Optional channel to stream resolved packages as they're discovered.
69    resolved_tx: Option<mpsc::Sender<ResolvedPackage>>,
70    /// Optional disk cache directory for packuments (with ETag revalidation).
71    packument_cache_dir: Option<std::path::PathBuf>,
72    /// Separate disk cache for full (non-corgi) packuments; only used
73    /// when `resolution_mode` is `TimeBased` (which needs the `time:`
74    /// map). Defaults to the sibling `packuments-full-v1/` directory
75    /// next to `packument_cache_dir`.
76    packument_full_cache_dir: Option<std::path::PathBuf>,
77    /// When true (pnpm's default), a package's declared `peerDependencies`
78    /// are enqueued like regular transitives and — if not already
79    /// satisfied by the importer — hoisted to the importer's direct deps.
80    /// When false, peers neither get auto-installed as transitives nor
81    /// hoisted; unmet peers still surface as warnings via
82    /// `detect_unmet_peers`, but the user is on the hook for adding them
83    /// explicitly to `package.json`.
84    auto_install_peers: bool,
85    /// pnpm's `exclude-links-from-lockfile`. Round-tripped through the
86    /// lockfile's `settings:` header; when true, the pnpm writer omits
87    /// `link:` deps from the importer `dependencies:` maps so a
88    /// sibling symlink change doesn't churn the lockfile. Defaults to
89    /// false (pnpm's default). Does not affect resolution itself, only
90    /// the `canonical.settings.exclude_links_from_lockfile` flag the
91    /// writer reads.
92    exclude_links_from_lockfile: bool,
93    /// User-declared override for the host platform triple, used when
94    /// deciding whether an optional dep's `os`/`cpu`/`libc` constraints
95    /// are satisfied. Empty fields fall back to the host.
96    supported_architectures: SupportedArchitectures,
97    /// Raw dependency override map from the manifest (selector key →
98    /// replacement spec). Round-tripped verbatim through the lockfile
99    /// for drift detection; the compiled form in `override_rules` is
100    /// what the resolver hot loop actually consults.
101    overrides: BTreeMap<String, String>,
102    /// Compiled view of `overrides`. Built by `with_overrides`.
103    /// Unparseable selector keys are dropped at compile time so the
104    /// matcher never has to think about them.
105    override_rules: Vec<override_rule::OverrideRule>,
106    /// Names listed in the root manifest's `pnpm.ignoredOptionalDependencies`.
107    /// Any optional dep (root or transitive) whose name is in this set is
108    /// dropped before enqueueing — the resolver never fetches or locks it.
109    /// Mirrors pnpm's `createOptionalDependenciesRemover` read-package hook.
110    ignored_optional_dependencies: BTreeSet<String>,
111    /// pnpm's `resolution-mode` — `Highest` (default) or `TimeBased`.
112    resolution_mode: ResolutionMode,
113    /// Project root used to resolve `file:` / `link:` paths to the
114    /// target directory. Defaults to the current working directory;
115    /// callers set it via `with_project_root`.
116    project_root: PathBuf,
117    /// pnpm v11's `minimumReleaseAge` triplet. `None` disables the
118    /// supply-chain age gate entirely (matching `minimumReleaseAge: 0`).
119    minimum_release_age: Option<MinimumReleaseAge>,
120    /// Workspace catalog ranges. Outer key is the catalog name
121    /// (`default` for the unnamed `catalog:` field in
122    /// `pnpm-workspace.yaml`); inner key is the package name; value is
123    /// the version range. When the resolver encounters a `catalog:` or
124    /// `catalog:<name>` task range, it rewrites the task in place to
125    /// the matching range *before* the override / npm-alias passes,
126    /// while preserving the original `catalog:...` text in
127    /// `original_specifier` so the lockfile importer keeps the
128    /// reference verbatim.
129    catalogs: BTreeMap<String, BTreeMap<String, String>>,
130    /// Optional `readPackage` hook, invoked once per resolved package
131    /// before its transitive deps are enqueued. See [`ReadPackageHook`].
132    /// Wired up by `aube` when a `.pnpmfile.cjs` is detected and
133    /// `--ignore-pnpmfile` was not set.
134    read_package_hook: Option<Box<dyn ReadPackageHook>>,
135    dependency_policy: DependencyPolicy,
136    /// Advisory ranges to avoid when resolving audit fixes. The map is
137    /// keyed by registry package name and values are npm semver ranges
138    /// from `vulnerable_versions`. When a clean satisfying version
139    /// exists, it wins over locked/sibling reuse and the normal highest
140    /// pick; if not, resolution falls back to the ordinary pick so the
141    /// caller can report the advisory as remaining.
142    vulnerable_ranges: BTreeMap<String, Vec<String>>,
143    /// Hosts for which aube performs shallow git clones, mirroring
144    /// pnpm's `git-shallow-hosts`. When a git dep's URL host is in
145    /// this list, the store attempts `git fetch --depth 1 origin
146    /// <sha>` (falling back to a full fetch if the server refuses);
147    /// otherwise it goes straight to a full fetch. Defaults to an
148    /// empty list — `aube` populates it from the generated
149    /// `aube_settings::resolved::git_shallow_hosts` accessor (which
150    /// carries the pnpm-compat default list baked in from
151    /// `settings.toml`) via [`Self::with_git_shallow_hosts`]. Library
152    /// callers who construct a `Resolver` directly must set it
153    /// explicitly if they want the pnpm list; keeping the list in
154    /// one place (`settings.toml`) avoids drift.
155    git_shallow_hosts: Vec<String>,
156    /// pnpm's `peersSuffixMaxLength`. When the peer-ID suffix on a
157    /// `dep_path` (the `(name@version)(…)` portion) would exceed this
158    /// many bytes, the post-pass replaces the whole suffix with
159    /// `_<hex>` where `<hex>` is the first 10 chars of SHA-256 of the
160    /// full suffix. Matches pnpm's lockfile format. Default 1000.
161    peers_suffix_max_length: usize,
162    /// pnpm's `dedupe-peer-dependents`. When true (pnpm's default),
163    /// the peer-context post-pass collapses multiple dep_path variants
164    /// of the same canonical package into a single entry when their
165    /// peer resolutions are pairwise-equivalent. When false, every
166    /// distinct ancestor scope gets its own variant — useful for
167    /// debugging peer-context divergence or mimicking pnpm v6/v7
168    /// behavior.
169    dedupe_peer_dependents: bool,
170    /// pnpm's `dedupe-peers`. When true, peer suffixes in the lockfile
171    /// emit just the resolved version — `(18.2.0)` — instead of the
172    /// full `(react@18.2.0)` form. Shorter dep_paths at the cost of
173    /// peer-name fidelity in the snapshot. Defaults to false.
174    dedupe_peers: bool,
175    /// pnpm's `resolve-peers-from-workspace-root`. When true (pnpm's
176    /// default), an importer's unresolved peer can be satisfied by a
177    /// dependency declared in the root importer's `package.json`, even
178    /// when no ancestor scope carries that dep. Common monorepo knob:
179    /// the workspace root pins shared peers like `react`, and every
180    /// subpackage can peer on it without hoisting the version into
181    /// every sibling.
182    resolve_peers_from_workspace_root: bool,
183    /// pnpm's `registry-supports-time-field`. When true, the resolver
184    /// trusts the abbreviated (corgi) packument to carry the `time:`
185    /// map and keeps using the cheap `fetch_packument_cached` path
186    /// even under time-aware resolution (`TimeBased` or
187    /// `minimumReleaseAge`). Defaults to false — the same assumption
188    /// pnpm and npmjs.org ship with — so the resolver falls back to
189    /// the full-packument fetch to get `time:` reliably. No effect
190    /// when neither time-based resolution nor `minimumReleaseAge` is
191    /// active, since the abbreviated path is already the only one
192    /// running.
193    registry_supports_time_field: bool,
194    /// Use the bundled metadata primer even when the configured
195    /// registry is not npmjs.org. Intended for npm-compatible mirrors
196    /// and controlled benchmarks; tarball URLs are rewritten to the
197    /// active registry before cache seeding so installs still fetch
198    /// package bytes from the configured source.
199    force_metadata_primer: bool,
200    pub(crate) packument_network_concurrency: Option<usize>,
201}
202
203pub(crate) struct ResolveTask {
204    pub(crate) name: String,
205    pub(crate) range: String,
206    dep_type: DepType,
207    is_root: bool,
208    /// The parent dep_path, for wiring up transitive dep references
209    parent: Option<String>,
210    /// Which importer this task belongs to (e.g., "." or "packages/app")
211    pub(crate) importer: String,
212    /// The original specifier from package.json before any rewrites
213    /// (e.g. `"npm:real-pkg@^2.0.0"` for an alias, or `"^4.17.0"` for a normal range).
214    /// Only set for root deps; recorded into the lockfile for drift detection.
215    pub(crate) original_specifier: Option<String>,
216    /// Real registry package name for npm-alias tasks.
217    ///
218    /// When a task arrives with `range` like `"npm:h3@2.0.1-rc.20"`,
219    /// the preprocessing loop strips the prefix and sets this field to
220    /// the real package name (`"h3"`) while *keeping* `name` as the
221    /// user-facing alias (`"h3-v2"`, the key the package.json used).
222    /// Every identity-facing site — dep_path formation, direct-dep
223    /// records, parent `dependencies` wiring, the resolved-versions
224    /// dedupe map — uses `name`, so the alias survives all the way
225    /// to the linker and ends up as `node_modules/<alias>/` with
226    /// `LockedPackage.alias_of = Some(real_name)`. Only registry
227    /// I/O (packument fetch, tarball URL derivation) consults this
228    /// field.
229    ///
230    /// `None` for ordinary (non-aliased) tasks — `name` is already
231    /// the registry name and nothing downstream needs to distinguish.
232    real_name: Option<String>,
233    /// Outermost-first chain of `(name, version)` ancestors above this
234    /// task in the dependency graph, used by `parent>child` override
235    /// selectors. Empty for root/importer deps. Each child-enqueue
236    /// site is responsible for extending its parent's chain with the
237    /// parent's own `(name, version)` frame.
238    pub(crate) ancestors: Vec<(String, String)>,
239}
240
241impl ResolveTask {
242    /// Name to use for registry operations (packument fetch, tarball
243    /// URL). Returns `real_name` for aliased tasks and `name`
244    /// otherwise. Every call site that talks to the registry goes
245    /// through this accessor so alias handling stays localized.
246    fn registry_name(&self) -> &str {
247        self.real_name.as_deref().unwrap_or(&self.name)
248    }
249
250    /// Construct a root-importer task for `(name, range)` under
251    /// `importer`, with the appropriate `dep_type` and no parent/ancestry.
252    /// Every root-dep enqueue site uses this shape; the factory keeps
253    /// the literal in one place so a new field added to `ResolveTask`
254    /// lands consistently across prod/dev/optional loops.
255    fn root(name: String, range: String, dep_type: DepType, importer: String) -> Self {
256        let original = range.clone();
257        Self {
258            name,
259            range,
260            dep_type,
261            is_root: true,
262            parent: None,
263            importer,
264            original_specifier: Some(original),
265            real_name: None,
266            ancestors: Vec::new(),
267        }
268    }
269
270    /// Construct a transitive (non-root) task discovered by walking a
271    /// parent package's dependency map. Carries the parent dep_path
272    /// and inherited ancestor chain for overrides.
273    fn transitive(
274        name: String,
275        range: String,
276        dep_type: DepType,
277        parent: String,
278        importer: String,
279        ancestors: Vec<(String, String)>,
280    ) -> Self {
281        Self {
282            name,
283            range,
284            dep_type,
285            is_root: false,
286            parent: Some(parent),
287            importer,
288            original_specifier: None,
289            real_name: None,
290            ancestors,
291        }
292    }
293}
294
295#[cfg(test)]
296mod tests;