Skip to main content

npm_utils/package_json/
mod.rs

1//! Pure-Rust npm manifest + lockfile schemas, modeled on the npm specs:
2//!
3//! - <https://docs.npmjs.com/cli/v8/configuring-npm/package-lock-json>
4//! - <https://docs.npmjs.com/cli/v8/using-npm/package-spec>
5//!
6//! A module of `npm-utils` (`npm_utils::package_json`). It parses, resolves, and renders —
7//! manifests and lockfiles as pure `Value`/string transforms — but never writes files, hits the
8//! network, or resolves untrusted paths, which keeps its strict spec-conformance tests pure and
9//! self-contained (the CLI does the file IO).
10//!
11//! Four pieces:
12//!
13//! - this module root: `package.json` — its `dependencies` specs and a browser-favoring
14//!   conditional-`exports` resolver (enough of Node's algorithm to build an ES-module
15//!   import map).
16//! - [`spec`] — the npm "package spec" dependency grammar ([`spec::Spec`]) and
17//!   [`spec::version_req`].
18//! - [`lock`] — `package-lock.json` (v2/v3) parsing into a faithful [`lock::Lockfile`], and
19//!   [`lock::render_v3`] for emitting one.
20//! - [`manifest`] — pure write-side `package.json` transforms (scaffold / upsert a dependency)
21//!   for the CLI's `init`/`add`.
22
23pub mod lock;
24pub mod manifest;
25pub mod spec;
26
27use serde_json::Value;
28use std::collections::HashMap;
29use std::fs;
30use std::path::Path;
31
32/// Normalize a `license` declaration to a single SPDX-ish string. Handles npm's modern `license`
33/// string, the legacy `{ "type": … }` object, and the legacy `licenses: [{ "type": … }]` array
34/// (joined with `" OR "`); `None` when none is declared. Shared by the registry (reading a
35/// packument) and the [`License`] readers (a manifest or a lockfile entry).
36pub(crate) fn normalize_license(value: &Value) -> Option<String> {
37    match value.get("license") {
38        Some(Value::String(s)) => return Some(s.clone()),
39        Some(Value::Object(o)) => {
40            if let Some(t) = o.get("type").and_then(Value::as_str) {
41                return Some(t.to_string());
42            }
43        }
44        _ => {}
45    }
46    let types: Vec<String> = value
47        .get("licenses")
48        .and_then(Value::as_array)
49        .map(|arr| {
50            arr.iter()
51                .filter_map(|l| l.get("type").and_then(Value::as_str).map(str::to_string))
52                .collect()
53        })
54        .unwrap_or_default();
55    (!types.is_empty()).then(|| types.join(" OR "))
56}
57
58/// Programmatic access to a declared license, from either a parsed `package.json`
59/// ([`PackageJson`]) or a parsed lockfile entry ([`lock::LockedPackage`]). Lets a consumer source
60/// a package's license from whichever it has — the lockfile when it records one, the manifest
61/// otherwise.
62pub trait License {
63    /// The declared SPDX-ish license string, if any.
64    fn license(&self) -> Option<String>;
65}
66
67/// A dependency parsed from a `package.json` `dependencies` map.
68#[derive(Debug, Clone)]
69pub struct Dependency {
70    pub name: String,
71    pub version: String,
72    /// True when the spec points at a git/GitHub source rather than a registry
73    /// version (e.g. `github:owner/repo#ref`).
74    pub is_git: bool,
75}
76
77/// Parse the `dependencies` section of a `package.json`.
78pub fn parse_dependencies(
79    package_json_path: &Path,
80) -> Result<HashMap<String, Dependency>, Box<dyn std::error::Error + Send + Sync>> {
81    let content = fs::read_to_string(package_json_path)?;
82    let json: Value = serde_json::from_str(&content)?;
83
84    let deps = json
85        .get("dependencies")
86        .and_then(|d| d.as_object())
87        .ok_or("no dependencies section found in package.json")?;
88
89    let mut dependencies = HashMap::new();
90    for (name, value) in deps {
91        if let Some(version_str) = value.as_str() {
92            let is_git = version_str.contains("github.com") || version_str.starts_with("git");
93            let version = extract_version(version_str);
94            validate_package_name(name)?;
95            validate_version(&version)?;
96            dependencies.insert(
97                name.clone(),
98                Dependency {
99                    name: name.clone(),
100                    version,
101                    is_git,
102                },
103            );
104        }
105    }
106
107    Ok(dependencies)
108}
109
110/// Reject npm package names whose characters could escape a path or URL — a path-safety allowlist,
111/// not a spec validator. Allowed: ASCII alphanumerics plus `.`, `_`, `-`, `@`, and `/` (scoped);
112/// empty, over-long, and any `..` are rejected. Case is intentionally *not* restricted: npm steers
113/// new packages to lowercase, but the registry still hosts legacy mixed-case names, and a truly
114/// invalid name simply 404s — enforcing case here would only reject valid installs. Anything
115/// outside the allowlist is a typo or a crafted entry meant to traverse a path later — fail loudly.
116/// `pub(crate)` so the CLI's source grammar screens spec names through the same allowlist.
117pub(crate) fn validate_package_name(
118    name: &str,
119) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
120    if name.is_empty() || name.len() > 200 {
121        return Err(format!("package name {name:?} has invalid length").into());
122    }
123    if name.contains("..") {
124        return Err(format!("package name {name:?} contains '..'").into());
125    }
126    if !name
127        .bytes()
128        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b'@' | b'/'))
129    {
130        return Err(format!("package name {name:?} contains disallowed characters").into());
131    }
132    Ok(())
133}
134
135/// Reject versions outside the semver-adjacent alphabet, before the value ends
136/// up in a URL, a cache filename, or a marker — none of which should contain a
137/// path separator.
138fn validate_version(version: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
139    if version.is_empty() || version.len() > 100 {
140        return Err(format!("version {version:?} has invalid length").into());
141    }
142    if version.contains("..") {
143        return Err(format!("version {version:?} contains '..'").into());
144    }
145    if !version
146        .bytes()
147        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'+' | b'_'))
148    {
149        return Err(format!("version {version:?} contains disallowed characters").into());
150    }
151    Ok(())
152}
153
154/// Extract a bare version from a spec string. Handles `"1.2.3"`, `"^1.2.3"`,
155/// `"~1.2.3"`, and git URLs (`"...#ref"` → `ref`).
156fn extract_version(value: &str) -> String {
157    if value.contains("github.com") || value.starts_with("git") {
158        if let Some(hash_pos) = value.rfind('#') {
159            return value[hash_pos + 1..].to_string();
160        }
161    }
162    value
163        .trim_start_matches('^')
164        .trim_start_matches('~')
165        .to_string()
166}
167
168/// The `"type"` field of a `package.json` (Node defaults to CommonJS).
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub enum PackageType {
171    Module,
172    CommonJs,
173}
174
175/// An import-map-worthy entry derived from a package's `package.json`.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub enum Entry {
178    /// The bare specifier (`name`) → a target relative path (the `.` export).
179    Bare(String),
180    /// A concrete subpath (`name/<subpath>`) → a target relative path.
181    Subpath { subpath: String, target: String },
182    /// A subpath *pattern* (`"./…/*"` export). `subpath` is the prefix before `*`
183    /// (e.g. `"helpers/"` or `""`), `dir` the target directory before `*` (e.g.
184    /// `"dist/"`).
185    Prefix { subpath: String, dir: String },
186}
187
188/// Browser-favoring conditional-`exports` resolver over a parsed `package.json`.
189///
190/// Resolves the bare entry and subpaths to relative file paths using the
191/// condition order browsers want — `browser` → `module` → `import` → `default`
192/// (never `node`/`require`) — with a `module` → `browser` → `main` fallback when
193/// there is no `exports` field. Enough of the Node resolution algorithm to
194/// generate an ES-module import map; not a general-purpose resolver.
195#[derive(Debug, Clone)]
196pub struct PackageJson {
197    raw: Value,
198}
199
200impl License for PackageJson {
201    /// The manifest's declared license (`license` string, or the legacy object / `licenses[]` array).
202    fn license(&self) -> Option<String> {
203        normalize_license(&self.raw)
204    }
205}
206
207/// Conditions tried, in order, for a browser ES-module import map.
208const BROWSER_CONDITIONS: &[&str] = &["browser", "module", "import", "default"];
209
210impl PackageJson {
211    /// Read and parse a `package.json` from disk.
212    pub fn from_path(path: &Path) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
213        Self::from_json(&fs::read_to_string(path)?)
214    }
215
216    /// Parse a `package.json` from a JSON string (e.g. read out of a tarball).
217    pub fn from_json(s: &str) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
218        Ok(Self::from_value(serde_json::from_str(s)?))
219    }
220
221    /// Wrap an already-parsed JSON document.
222    pub fn from_value(raw: Value) -> Self {
223        Self { raw }
224    }
225
226    /// The `"name"` field, if present.
227    pub fn name(&self) -> Option<&str> {
228        self.raw.get("name").and_then(Value::as_str)
229    }
230
231    /// The `"version"` field, if present.
232    pub fn version(&self) -> Option<&str> {
233        self.raw.get("version").and_then(Value::as_str)
234    }
235
236    /// `Module` when `"type": "module"`, else `CommonJs` (Node's default).
237    pub fn package_type(&self) -> PackageType {
238        match self.raw.get("type").and_then(Value::as_str) {
239            Some("module") => PackageType::Module,
240            _ => PackageType::CommonJs,
241        }
242    }
243
244    /// Resolve the bare entry (the `.` export) to a relative path, for the browser.
245    pub fn resolve_main(&self) -> Option<String> {
246        if let Some(exports) = self.raw.get("exports") {
247            if let Some(s) = exports.as_str() {
248                return safe_target(s);
249            }
250            if let Some(obj) = exports.as_object() {
251                return if is_subpath_map(obj) {
252                    obj.get(".")
253                        .and_then(select_condition)
254                        .and_then(|s| safe_target(&s))
255                } else {
256                    select_condition(exports).and_then(|s| safe_target(&s))
257                };
258            }
259        }
260        // No usable `exports`: fall back to module → browser → main.
261        if let Some(s) = self.raw.get("module").and_then(Value::as_str) {
262            return safe_target(s);
263        }
264        if let Some(browser) = self.raw.get("browser") {
265            if let Some(s) = browser.as_str() {
266                return safe_target(s);
267            }
268            if let (Some(map), Some(main)) = (
269                browser.as_object(),
270                self.raw.get("main").and_then(Value::as_str),
271            ) {
272                let main = safe_target(main)?;
273                for (key, value) in map {
274                    if safe_target(key).as_deref() == Some(main.as_str()) {
275                        if let Some(s) = value.as_str() {
276                            return safe_target(s);
277                        }
278                    }
279                }
280            }
281        }
282        self.raw
283            .get("main")
284            .and_then(Value::as_str)
285            .and_then(safe_target)
286    }
287
288    /// Resolve a subpath (e.g. `"./helpers/decorate"`; leading `./` optional) via
289    /// the `exports` map — exact key first, then the longest `"./…/*"` pattern.
290    pub fn resolve_subpath(&self, subpath: &str) -> Option<String> {
291        let key = normalize_subpath_key(subpath);
292        let exports = self.raw.get("exports")?.as_object()?;
293        if !is_subpath_map(exports) {
294            return None;
295        }
296        if let Some(value) = exports.get(&key) {
297            return select_condition(value).and_then(|s| safe_target(&s));
298        }
299        let mut best_len = 0usize;
300        let mut best: Option<String> = None;
301        for (pattern, value) in exports {
302            let Some(star) = pattern.find('*') else {
303                continue;
304            };
305            let (prefix, suffix) = (&pattern[..star], &pattern[star + 1..]);
306            if key.len() >= prefix.len() + suffix.len()
307                && key.starts_with(prefix)
308                && key.ends_with(suffix)
309            {
310                let matched = &key[prefix.len()..key.len() - suffix.len()];
311                if let Some(target) = select_condition(value) {
312                    if let Some(resolved) = safe_target(&target.replace('*', matched)) {
313                        if best.is_none() || prefix.len() > best_len {
314                            best_len = prefix.len();
315                            best = Some(resolved);
316                        }
317                    }
318                }
319            }
320        }
321        best
322    }
323
324    /// Enumerate the import-map-worthy entries: the bare entry, concrete subpaths,
325    /// and `"./*"`-pattern prefixes.
326    pub fn entries(&self) -> Vec<Entry> {
327        let mut entries = Vec::new();
328        match self.raw.get("exports") {
329            Some(Value::Object(obj)) if is_subpath_map(obj) => {
330                for (key, value) in obj {
331                    if key == "." {
332                        if let Some(t) = select_condition(value).and_then(|s| safe_target(&s)) {
333                            entries.push(Entry::Bare(t));
334                        }
335                    } else if let Some(sub) = key.strip_prefix("./") {
336                        if let Some(star) = sub.find('*') {
337                            if let Some(dir) = select_condition(value).and_then(|t| target_dir(&t))
338                            {
339                                entries.push(Entry::Prefix {
340                                    subpath: sub[..star].to_string(),
341                                    dir,
342                                });
343                            }
344                        } else if let Some(t) =
345                            select_condition(value).and_then(|s| safe_target(&s))
346                        {
347                            entries.push(Entry::Subpath {
348                                subpath: sub.to_string(),
349                                target: t,
350                            });
351                        }
352                    }
353                }
354            }
355            // exports as a string or a pure conditions object, or no exports:
356            // only the bare entry (via resolve_main's logic + fallbacks).
357            _ => {
358                if let Some(t) = self.resolve_main() {
359                    entries.push(Entry::Bare(t));
360                }
361            }
362        }
363        entries
364    }
365
366    /// Every relative path the resolution references (concrete targets + pattern
367    /// directories) — used to keep the right files when vendoring, even under `src/`.
368    pub fn referenced_paths(&self) -> Vec<String> {
369        self.entries()
370            .into_iter()
371            .map(|e| match e {
372                Entry::Bare(t) | Entry::Subpath { target: t, .. } => t,
373                Entry::Prefix { dir, .. } => dir,
374            })
375            .collect()
376    }
377}
378
379/// Whether an `exports` object is a subpath map (keys like `"."`, `"./x"`) rather
380/// than a bare conditions map (keys like `"import"`, `"default"`).
381fn is_subpath_map(obj: &serde_json::Map<String, Value>) -> bool {
382    obj.keys().any(|k| k.starts_with('.'))
383}
384
385/// Pick the first target matching the browser condition order, recursing into
386/// nested condition objects and `exports` arrays (ordered fallbacks).
387fn select_condition(node: &Value) -> Option<String> {
388    match node {
389        Value::String(s) => Some(s.clone()),
390        Value::Array(arr) => arr.iter().find_map(select_condition),
391        Value::Object(map) => BROWSER_CONDITIONS
392            .iter()
393            .find_map(|cond| map.get(*cond).and_then(select_condition)),
394        _ => None,
395    }
396}
397
398/// Normalize a target: strip a leading `./`, reject `..`/empty (path traversal).
399fn safe_target(s: &str) -> Option<String> {
400    let t = s.strip_prefix("./").unwrap_or(s).trim_start_matches('/');
401    if t.is_empty() || t.split('/').any(|seg| seg == "..") {
402        return None;
403    }
404    Some(t.to_string())
405}
406
407/// `"./helpers/foo"` / `"helpers/foo"` → the canonical `"./helpers/foo"` key.
408fn normalize_subpath_key(subpath: &str) -> String {
409    if subpath.starts_with("./") {
410        subpath.to_string()
411    } else {
412        format!("./{}", subpath.trim_start_matches('/'))
413    }
414}
415
416/// The directory portion of a pattern target before `*` (e.g. `"./dist/*.js"` →
417/// `"dist/"`, `"./*.js"` → `""`). `None` if it would escape.
418fn target_dir(target: &str) -> Option<String> {
419    let star = target.find('*')?;
420    let before = target[..star].strip_prefix("./").unwrap_or(&target[..star]);
421    if before.split('/').any(|seg| seg == "..") {
422        return None;
423    }
424    Some(before.trim_start_matches('/').to_string())
425}
426
427#[cfg(test)]
428mod tests {
429    use super::*;
430    use tempfile::tempdir;
431
432    #[test]
433    fn parses_pinned_caret_and_git_specs() {
434        let tmp = tempdir().unwrap();
435        let p = tmp.path().join("package.json");
436        fs::write(
437            &p,
438            r#"{ "dependencies": {
439                "lit": "3.3.3",
440                "bootstrap": "^5.3.8",
441                "forked": "github:owner/repo#abc123"
442            } }"#,
443        )
444        .unwrap();
445
446        let deps = parse_dependencies(&p).unwrap();
447        assert_eq!(deps["lit"].version, "3.3.3");
448        assert!(!deps["lit"].is_git);
449        assert_eq!(deps["bootstrap"].version, "5.3.8");
450        assert_eq!(deps["forked"].version, "abc123");
451        assert!(deps["forked"].is_git);
452    }
453
454    #[test]
455    fn resolve_main_from_exports_and_fallbacks() {
456        // exports."." with conditions -> default.
457        let a = PackageJson::from_json(
458            r#"{"exports":{".":{"types":"./dev.d.ts","default":"./index.js"},"./decorators.js":{"default":"./decorators.js"}}}"#,
459        )
460        .unwrap();
461        assert_eq!(a.resolve_main().as_deref(), Some("index.js"));
462        assert_eq!(
463            a.resolve_subpath("./decorators.js").as_deref(),
464            Some("decorators.js")
465        );
466
467        // nested browser condition map under ".".
468        let b = PackageJson::from_json(
469            r#"{"type":"module","exports":{".":{"browser":{"development":"./development/lit-html.js","default":"./lit-html.js"},"default":"./lit-html.js"}}}"#,
470        )
471        .unwrap();
472        assert_eq!(b.resolve_main().as_deref(), Some("lit-html.js"));
473
474        // no exports -> module wins over main.
475        let c = PackageJson::from_json(
476            r#"{"main":"dist/js/bootstrap.js","module":"dist/js/bootstrap.esm.js"}"#,
477        )
478        .unwrap();
479        assert_eq!(
480            c.resolve_main().as_deref(),
481            Some("dist/js/bootstrap.esm.js")
482        );
483    }
484
485    #[test]
486    fn resolve_subpath_picks_import_condition_for_cjs_package() {
487        // CommonJS package, no ".", helper subpaths whose "import" condition is the
488        // ESM build under src/helpers/esm/.
489        let rt = PackageJson::from_json(
490            r#"{"type":"commonjs","exports":{"./helpers/decorate":[{"node":"./src/helpers/decorate.js","import":"./src/helpers/esm/decorate.js","default":"./src/helpers/decorate.js"}]}}"#,
491        )
492        .unwrap();
493        assert_eq!(rt.package_type(), PackageType::CommonJs);
494        assert!(rt.resolve_main().is_none());
495        assert_eq!(
496            rt.resolve_subpath("./helpers/decorate").as_deref(),
497            Some("src/helpers/esm/decorate.js")
498        );
499        assert_eq!(
500            rt.resolve_subpath("helpers/decorate").as_deref(),
501            Some("src/helpers/esm/decorate.js")
502        );
503        assert!(rt
504            .referenced_paths()
505            .iter()
506            .any(|p| p == "src/helpers/esm/decorate.js"));
507    }
508
509    #[test]
510    fn condition_order_prefers_browser_and_import_never_node() {
511        let x = PackageJson::from_json(
512            r#"{"exports":{".":{"node":"./n.js","require":"./r.js","import":"./esm.js","default":"./def.js"}}}"#,
513        )
514        .unwrap();
515        assert_eq!(x.resolve_main().as_deref(), Some("esm.js"));
516
517        let y = PackageJson::from_json(
518            r#"{"exports":{".":{"module":"./m.js","browser":"./b.js","default":"./d.js"}}}"#,
519        )
520        .unwrap();
521        assert_eq!(y.resolve_main().as_deref(), Some("b.js"));
522    }
523
524    #[test]
525    fn subpath_pattern_becomes_prefix_entry() {
526        let pkg = PackageJson::from_json(r#"{"exports":{".":"./index.js","./*":"./dist/*.js"}}"#)
527            .unwrap();
528        assert_eq!(pkg.resolve_subpath("./foo").as_deref(), Some("dist/foo.js"));
529        assert!(pkg.entries().iter().any(
530            |e| matches!(e, Entry::Prefix { subpath, dir } if subpath.is_empty() && dir == "dist/")
531        ));
532        assert!(pkg
533            .entries()
534            .iter()
535            .any(|e| matches!(e, Entry::Bare(t) if t == "index.js")));
536    }
537
538    #[test]
539    fn rejects_path_traversal_targets() {
540        let evil = PackageJson::from_json(r#"{"exports":{".":"../escape.js"}}"#).unwrap();
541        assert!(evil.resolve_main().is_none());
542    }
543}