Skip to main content

npm_utils/package_json/
lock.rs

1//! `package-lock.json` (lockfileVersion 2 or 3) parsing, per
2//! <https://docs.npmjs.com/cli/v8/configuring-npm/package-lock-json>.
3//!
4//! [`Lockfile::parse`] reads the flat `packages` map into faithful [`LockedPackage`] data.
5//! [`render_v3`] is the inverse: it emits a `lockfileVersion`-3 document for a flat resolved set
6//! (what `cargo npm-utils add`/`upgrade` write). Both are pure — they touch no filesystem and
7//! resolve no paths: a caller turns a [`LockedPackage::key`] into an install path itself, so this
8//! parser stays pure and the path-safety check lives with the installer. lockfileVersion 1 (the
9//! legacy hierarchical `dependencies` tree, with no `packages` map) is unsupported.
10
11use std::path::Path;
12
13use serde_json::{Map, Value};
14
15use super::{manifest, spec};
16use crate::registry::Registry;
17
18/// A parsed `package-lock.json`.
19#[derive(Debug, Clone)]
20pub struct Lockfile {
21    /// The `lockfileVersion` (always ≥ 2 here).
22    pub version: u64,
23    /// Every entry of the `packages` map, sorted by key — so install order, and thus
24    /// `.bin` name-collision resolution, is deterministic. Includes the root `""` entry.
25    pub packages: Vec<LockedPackage>,
26}
27
28/// One entry of the `packages` map.
29#[derive(Debug, Clone)]
30pub struct LockedPackage {
31    /// The map key: `""` for the root project, else a `node_modules/…`-relative path.
32    pub key: String,
33    /// The package name — the segment after the last `node_modules/` (empty for the root).
34    pub name: String,
35    /// `version` from the entry (empty for the root or a pure link).
36    pub version: String,
37    /// `resolved` — the registry URL, git source, or `file:` path; `None` if absent.
38    pub resolved: Option<String>,
39    /// `integrity` — the Subresource-Integrity string (`sha512-…`); `None` if absent.
40    pub integrity: Option<String>,
41    /// `license` — the package's declared SPDX license string, when the lockfile records one
42    /// (npm writes it per package; so does this crate's [`render_v3`]). `None` if absent.
43    /// Read so SBOM/compliance output ([`crate::sbom`]) can carry it.
44    pub license: Option<String>,
45    /// `dev` — strictly in the devDependencies tree.
46    pub dev: bool,
47    /// `optional` — strictly in the optionalDependencies tree.
48    pub optional: bool,
49    /// `devOptional` — both a dev and an optional dependency.
50    pub dev_optional: bool,
51    /// `link: true` — a symlink to a local path; nothing is fetched.
52    pub link: bool,
53    /// `os` constraints (npm spelling — `darwin`, `linux`, `win32`; `!`-negation allowed).
54    pub os: Vec<String>,
55    /// `cpu` constraints (npm spelling — `x64`, `arm64`, `ia32`; `!`-negation allowed).
56    pub cpu: Vec<String>,
57    /// `bin` as `(name, path-within-package)` pairs.
58    pub bin: Vec<(String, String)>,
59}
60
61impl Lockfile {
62    /// Parse a `package-lock.json` document (lockfileVersion 2 or 3).
63    pub fn parse(s: &str) -> Result<Lockfile, Box<dyn std::error::Error>> {
64        let json: Value = serde_json::from_str(s)?;
65        let version = json
66            .get("lockfileVersion")
67            .and_then(Value::as_u64)
68            .unwrap_or(0);
69        if version < 2 {
70            return Err(format!(
71                "package-lock.json lockfileVersion {version} is unsupported \
72                 (need 2 or 3, which carry the `packages` map)"
73            )
74            .into());
75        }
76        let packages = json
77            .get("packages")
78            .and_then(Value::as_object)
79            .ok_or("package-lock.json has no `packages` map")?;
80        let mut out: Vec<LockedPackage> = packages
81            .iter()
82            .filter_map(|(key, entry)| {
83                entry
84                    .as_object()
85                    .map(|entry| LockedPackage::from_entry(key, entry))
86            })
87            .collect();
88        out.sort_by(|a, b| a.key.cmp(&b.key));
89        Ok(Lockfile {
90            version,
91            packages: out,
92        })
93    }
94
95    /// The entries an npm-tarball installer fetches on the given host: real (non-root)
96    /// `node_modules/…` packages that aren't links and whose `os`/`cpu` match. `host_os` and
97    /// `host_arch` are Rust's `std::env::consts::{OS, ARCH}` spellings. Whether each entry's
98    /// `resolved` is actually an http(s) registry tarball is left to the caller — see
99    /// [`LockedPackage::is_registry_tarball`].
100    pub fn installable(&self, host_os: &str, host_arch: &str) -> Vec<&LockedPackage> {
101        self.packages
102            .iter()
103            .filter(|p| p.key.starts_with("node_modules/") && !p.link)
104            .filter(|p| p.matches_platform(host_os, host_arch))
105            .collect()
106    }
107}
108
109/// A resolved package to record in a generated lockfile — the write-side input mirroring a parsed
110/// [`LockedPackage`], kept to the flat-tree fields [`render_v3`] emits.
111#[derive(Debug, Clone)]
112pub struct LockEntry {
113    /// Package name (the `node_modules/<name>` key segment).
114    pub name: String,
115    /// Exact resolved version.
116    pub version: String,
117    /// The registry tarball URL — the entry's `resolved`.
118    pub resolved: String,
119    /// The `sha512-…` Subresource-Integrity, when the registry advertised one.
120    pub integrity: Option<String>,
121    /// The package's declared SPDX license, recorded for license/compliance tooling
122    /// (npm's own lockfiles carry it too).
123    pub license: Option<String>,
124}
125
126/// Render a `lockfileVersion`-3 `package-lock.json` for a **flat** dependency tree: a root `""`
127/// entry (the project `name`/`version` and its direct dependency ranges) plus one
128/// `node_modules/<name>` entry per resolved package. Keys are emitted in npm's order
129/// (`name`, `version`, `lockfileVersion`, `requires`, `packages`) thanks to `serde_json`'s
130/// `preserve_order`.
131///
132/// Scope (documented, intentional): this is an **npm-compatible v3 lock for the registry/prod
133/// tree** that round-trips through [`Lockfile::parse`] and installs via
134/// [`crate::install::from_lockfile`] — it is *not* a byte-for-byte npm reproduction. The flat set
135/// from [`crate::registry::Registry::resolve_tree`] carries no dev/optional classification, so no
136/// `dev`/`optional` flags are emitted, and `peerDependencies`/`bundleDependencies` and per-package
137/// `dependencies` back-references are omitted.
138pub fn render_v3(
139    root_name: &str,
140    root_version: &str,
141    direct: &[(String, String)],
142    entries: &[LockEntry],
143) -> String {
144    use serde_json::json;
145
146    let mut packages = Map::new();
147
148    // The root project entry, keyed "".
149    let mut root = Map::new();
150    root.insert("name".into(), json!(root_name));
151    root.insert("version".into(), json!(root_version));
152    if !direct.is_empty() {
153        let mut deps = Map::new();
154        for (name, range) in direct {
155            deps.insert(name.clone(), json!(range));
156        }
157        root.insert("dependencies".into(), Value::Object(deps));
158    }
159    packages.insert(String::new(), Value::Object(root));
160
161    // One node_modules/<name> entry per resolved package, in the order given (resolve_tree
162    // returns them sorted by name).
163    for entry in entries {
164        let mut pkg = Map::new();
165        pkg.insert("version".into(), json!(entry.version));
166        pkg.insert("resolved".into(), json!(entry.resolved));
167        if let Some(integrity) = &entry.integrity {
168            pkg.insert("integrity".into(), json!(integrity));
169        }
170        if let Some(license) = &entry.license {
171            pkg.insert("license".into(), json!(license));
172        }
173        packages.insert(format!("node_modules/{}", entry.name), Value::Object(pkg));
174    }
175
176    let doc = json!({
177        "name": root_name,
178        "version": root_version,
179        "lockfileVersion": 3,
180        "requires": true,
181        "packages": Value::Object(packages),
182    });
183    let mut out = serde_json::to_string_pretty(&doc).expect("serialize package-lock.json");
184    out.push('\n');
185    out
186}
187
188/// Resolve a `package.json`-shaped manifest's **registry** dependencies into a flat tree and
189/// render it as a `lockfileVersion`-3 `package-lock.json` string (with per-package `license`).
190/// Talks to `registry` over the network but touches no filesystem and installs no
191/// `node_modules/` — the lockfile-only half of `add`/`upgrade`. Non-registry deps (git /
192/// `file:`) are skipped: recorded in the manifest, but not resolvable to a registry tarball.
193pub fn render_v3_from_manifest(
194    doc: &Value,
195    registry: &Registry,
196) -> Result<String, Box<dyn std::error::Error>> {
197    let direct = manifest::dependencies(doc);
198    let roots: Vec<(String, spec::Range)> = direct
199        .iter()
200        .filter(|(_, range)| spec::Spec::parse(range).is_registry())
201        .map(
202            |(name, range)| -> Result<(String, spec::Range), Box<dyn std::error::Error>> {
203                Ok((name.clone(), spec::Range::parse(range)?))
204            },
205        )
206        .collect::<Result<Vec<_>, _>>()?;
207
208    let entries: Vec<LockEntry> = registry
209        .resolve_tree(&roots)?
210        .into_iter()
211        .map(|r| LockEntry {
212            name: r.name,
213            version: r.version.to_string(),
214            resolved: r.tarball_url,
215            integrity: r.integrity,
216            license: r.license,
217        })
218        .collect();
219
220    let name = doc.get("name").and_then(Value::as_str).unwrap_or("");
221    let version = doc
222        .get("version")
223        .and_then(Value::as_str)
224        .unwrap_or("0.0.0");
225    Ok(render_v3(name, version, &direct, &entries))
226}
227
228/// Read a `package.json`-shaped manifest and (re)write its `package-lock.json` from the
229/// registry — pure Rust, no Node, no npm, no `node_modules/`. This is the "update the
230/// lockfile" primitive for build scripts and vendoring flows (where the lock is a manifest of
231/// resolved versions + licenses, not an install); [`render_v3_from_manifest`] is the in-memory
232/// core. Resolves against the public npm registry.
233pub fn write_from_manifest(
234    manifest_path: &Path,
235    lockfile_path: &Path,
236) -> Result<(), Box<dyn std::error::Error>> {
237    let text = std::fs::read_to_string(manifest_path)
238        .map_err(|e| format!("reading {}: {e}", manifest_path.display()))?;
239    let doc: Value = serde_json::from_str(&text)
240        .map_err(|e| format!("parsing {}: {e}", manifest_path.display()))?;
241    let lockfile = render_v3_from_manifest(&doc, &Registry::npm())?;
242    std::fs::write(lockfile_path, lockfile)
243        .map_err(|e| format!("writing {}: {e}", lockfile_path.display()))?;
244    Ok(())
245}
246
247impl LockedPackage {
248    fn from_entry(key: &str, entry: &Map<String, Value>) -> LockedPackage {
249        let name = key
250            .rsplit_once("node_modules/")
251            .map(|(_, n)| n)
252            .unwrap_or(key)
253            .to_string();
254        LockedPackage {
255            bin: bin_entries(entry, &name),
256            key: key.to_string(),
257            name,
258            version: string_field(entry, "version"),
259            resolved: opt_string(entry, "resolved"),
260            integrity: opt_string(entry, "integrity"),
261            license: opt_string(entry, "license"),
262            dev: bool_field(entry, "dev"),
263            optional: bool_field(entry, "optional"),
264            dev_optional: bool_field(entry, "devOptional"),
265            link: bool_field(entry, "link"),
266            os: string_list(entry, "os"),
267            cpu: string_list(entry, "cpu"),
268        }
269    }
270
271    /// Whether `resolved` is an http(s) registry tarball — the only source `npm-utils` fetches.
272    pub fn is_registry_tarball(&self) -> bool {
273        self.resolved
274            .as_deref()
275            .is_some_and(|r| r.starts_with("https://") || r.starts_with("http://"))
276    }
277
278    /// Whether the host satisfies this entry's `os`/`cpu`. `host_os`/`host_arch` are Rust's
279    /// `std::env::consts::{OS, ARCH}`; they are mapped to npm's spelling before comparing.
280    pub fn matches_platform(&self, host_os: &str, host_arch: &str) -> bool {
281        constraint_allows(&self.os, node_os(host_os))
282            && constraint_allows(&self.cpu, node_cpu(host_arch))
283    }
284}
285
286/// npm `os`/`cpu` matching: a positive list must include `host`; a `!`-prefixed value excludes
287/// it; an empty constraint allows everything.
288pub fn constraint_allows(constraint: &[String], host: &str) -> bool {
289    let mut has_positive = false;
290    let mut matched_positive = false;
291    for item in constraint {
292        if let Some(excluded) = item.strip_prefix('!') {
293            if excluded == host {
294                return false;
295            }
296        } else {
297            has_positive = true;
298            if item == host {
299                matched_positive = true;
300            }
301        }
302    }
303    !has_positive || matched_positive
304}
305
306const OS_MAP: &[(&str, &str)] = &[("macos", "darwin"), ("windows", "win32")];
307const CPU_MAP: &[(&str, &str)] = &[("x86_64", "x64"), ("aarch64", "arm64"), ("x86", "ia32")];
308
309/// Map a Rust `std::env::consts::OS` value to npm's `os` spelling (`linux` is shared).
310fn node_os(rust: &str) -> &str {
311    map_value(rust, OS_MAP)
312}
313
314/// Map a Rust `std::env::consts::ARCH` value to npm's `cpu` spelling.
315fn node_cpu(rust: &str) -> &str {
316    map_value(rust, CPU_MAP)
317}
318
319fn map_value<'a>(rust: &'a str, map: &[(&'static str, &'static str)]) -> &'a str {
320    map.iter()
321        .find(|(r, _)| *r == rust)
322        .map(|(_, n)| *n)
323        .unwrap_or(rust)
324}
325
326fn string_field(entry: &Map<String, Value>, key: &str) -> String {
327    entry
328        .get(key)
329        .and_then(Value::as_str)
330        .unwrap_or_default()
331        .to_string()
332}
333
334fn opt_string(entry: &Map<String, Value>, key: &str) -> Option<String> {
335    entry.get(key).and_then(Value::as_str).map(str::to_string)
336}
337
338fn bool_field(entry: &Map<String, Value>, key: &str) -> bool {
339    entry.get(key).and_then(Value::as_bool).unwrap_or(false)
340}
341
342fn string_list(entry: &Map<String, Value>, key: &str) -> Vec<String> {
343    entry
344        .get(key)
345        .and_then(Value::as_array)
346        .map(|a| {
347            a.iter()
348                .filter_map(Value::as_str)
349                .map(str::to_string)
350                .collect()
351        })
352        .unwrap_or_default()
353}
354
355/// The `(bin-name, path-in-package)` pairs an entry exposes. npm allows either an object
356/// (`{"foo": "cli.js"}`) or a bare string (the bin takes the package's unscoped name).
357fn bin_entries(entry: &Map<String, Value>, name: &str) -> Vec<(String, String)> {
358    match entry.get("bin") {
359        Some(Value::String(path)) => {
360            let bin_name = name.rsplit('/').next().unwrap_or(name).to_string();
361            vec![(bin_name, path.clone())]
362        }
363        Some(Value::Object(map)) => map
364            .iter()
365            .filter_map(|(n, v)| v.as_str().map(|p| (n.clone(), p.to_string())))
366            .collect(),
367        _ => Vec::new(),
368    }
369}
370
371#[cfg(test)]
372mod tests {
373    use super::*;
374
375    // A lockfileVersion-3 fixture exercising the field variety: a runtime dep, a scoped dep,
376    // a dev dep with a `bin` map, an off-platform optional native dep, and a `file:` link.
377    const SAMPLE_LOCK: &str = r#"{
378      "name": "harness",
379      "lockfileVersion": 3,
380      "packages": {
381        "": { "name": "harness", "devDependencies": { "typescript": "^5" } },
382        "node_modules/@scope/pkg": {
383          "version": "1.2.3",
384          "resolved": "https://registry.npmjs.org/@scope/pkg/-/pkg-1.2.3.tgz",
385          "integrity": "sha512-BBBB"
386        },
387        "node_modules/typescript": {
388          "version": "5.9.3",
389          "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
390          "integrity": "sha512-AAAA",
391          "dev": true,
392          "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" }
393        },
394        "node_modules/fsevents": {
395          "version": "2.3.2",
396          "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
397          "integrity": "sha512-CCCC",
398          "dev": true,
399          "optional": true,
400          "os": ["darwin"]
401        },
402        "node_modules/local-link": { "resolved": "file:../local", "link": true }
403      }
404    }"#;
405
406    fn names(packages: &[&LockedPackage]) -> Vec<String> {
407        packages.iter().map(|p| p.name.clone()).collect()
408    }
409
410    #[test]
411    fn parses_fields_and_selects_installable_per_host() {
412        let lock = Lockfile::parse(SAMPLE_LOCK).unwrap();
413        assert_eq!(lock.version, 3);
414
415        // On linux/x86_64: the scoped dep + typescript. The darwin-only optional is skipped;
416        // the root "" and the `file:` link are never installable.
417        assert_eq!(
418            names(&lock.installable("linux", "x86_64")),
419            ["@scope/pkg", "typescript"]
420        );
421        // On macos/aarch64 the darwin-only fsevents joins (sorted by key).
422        assert_eq!(
423            names(&lock.installable("macos", "aarch64")),
424            ["@scope/pkg", "fsevents", "typescript"]
425        );
426
427        // Fields parsed: dev flag, integrity, the full bin map.
428        let ts = lock
429            .packages
430            .iter()
431            .find(|p| p.name == "typescript")
432            .unwrap();
433        assert!(ts.dev);
434        assert_eq!(ts.integrity.as_deref(), Some("sha512-AAAA"));
435        assert!(ts.bin.iter().any(|(n, p)| n == "tsc" && p == "bin/tsc"));
436        assert!(ts.bin.iter().any(|(n, _)| n == "tsserver"));
437        // The link entry is parsed (faithful) but excluded from installable.
438        assert!(lock.packages.iter().any(|p| p.link));
439    }
440
441    #[test]
442    fn distinguishes_registry_tarballs_from_other_sources() {
443        let lock = Lockfile::parse(SAMPLE_LOCK).unwrap();
444        let ts = lock
445            .packages
446            .iter()
447            .find(|p| p.name == "typescript")
448            .unwrap();
449        assert!(
450            ts.is_registry_tarball(),
451            "https resolved is a registry tarball"
452        );
453        let link = lock.packages.iter().find(|p| p.link).unwrap();
454        assert!(!link.is_registry_tarball(), "a file: link is not");
455    }
456
457    #[test]
458    fn rejects_lockfile_version_1() {
459        // v1 has no `packages` map — the hierarchical `dependencies` tree is unsupported.
460        assert!(Lockfile::parse(r#"{"lockfileVersion":1,"dependencies":{}}"#).is_err());
461    }
462
463    #[test]
464    fn constraint_allows_follows_npm_os_cpu_rules() {
465        let v = |xs: &[&str]| xs.iter().map(|s| s.to_string()).collect::<Vec<_>>();
466        assert!(constraint_allows(&[], "linux"), "no constraint allows all");
467        assert!(constraint_allows(&v(&["linux"]), "linux"));
468        assert!(!constraint_allows(&v(&["darwin"]), "linux"));
469        assert!(constraint_allows(&v(&["darwin", "linux"]), "linux"));
470        assert!(constraint_allows(&v(&["!win32"]), "linux"));
471        assert!(!constraint_allows(&v(&["!linux"]), "linux"));
472    }
473
474    #[test]
475    fn matches_platform_maps_rust_host_to_npm_spelling() {
476        let lock = Lockfile::parse(SAMPLE_LOCK).unwrap();
477        let fsevents = lock.packages.iter().find(|p| p.name == "fsevents").unwrap();
478        // os:["darwin"] — excluded on a linux host, allowed on macos (rust "macos" → "darwin").
479        assert!(!fsevents.matches_platform("linux", "x86_64"));
480        assert!(fsevents.matches_platform("macos", "aarch64"));
481    }
482
483    #[test]
484    fn render_v3_emits_npm_order_and_round_trips_through_parse() {
485        let entries = vec![
486            LockEntry {
487                name: "ms".into(),
488                version: "2.1.3".into(),
489                resolved: "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz".into(),
490                integrity: Some("sha512-MS".into()),
491                license: Some("MIT".into()),
492            },
493            LockEntry {
494                name: "@scope/pkg".into(),
495                version: "1.0.0".into(),
496                resolved: "https://registry.npmjs.org/@scope/pkg/-/pkg-1.0.0.tgz".into(),
497                integrity: Some("sha512-SP".into()),
498                license: None,
499            },
500        ];
501        let direct = vec![("ms".to_string(), "^2".to_string())];
502        let json = render_v3("fixture", "1.0.0", &direct, &entries);
503
504        // Top-level keys come out in npm's order (preserve_order), not alphabetized.
505        let doc: Value = serde_json::from_str(&json).unwrap();
506        let keys: Vec<&str> = doc
507            .as_object()
508            .unwrap()
509            .keys()
510            .map(String::as_str)
511            .collect();
512        assert_eq!(
513            keys,
514            ["name", "version", "lockfileVersion", "requires", "packages"]
515        );
516        // The root "" entry records the direct dependency ranges from package.json.
517        assert_eq!(doc["packages"][""]["dependencies"]["ms"], "^2");
518
519        // A declared license is emitted per package; omitted when None.
520        assert_eq!(doc["packages"]["node_modules/ms"]["license"], "MIT");
521        assert!(doc["packages"]["node_modules/@scope/pkg"]
522            .get("license")
523            .is_none());
524
525        // It parses back as a v3 lock; the two registry entries are installable (root "" and
526        // any link excluded), sorted by key, with integrity + resolved threaded through.
527        let lock = Lockfile::parse(&json).unwrap();
528        assert_eq!(lock.version, 3);
529        let names: Vec<&str> = lock
530            .installable("linux", "x86_64")
531            .iter()
532            .map(|p| p.name.as_str())
533            .collect();
534        assert_eq!(names, ["@scope/pkg", "ms"]);
535        let ms = lock.packages.iter().find(|p| p.name == "ms").unwrap();
536        assert_eq!(ms.integrity.as_deref(), Some("sha512-MS"));
537        assert!(
538            ms.is_registry_tarball(),
539            "resolved is an https registry tarball"
540        );
541    }
542}