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