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.
116fn validate_package_name(name: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
117    if name.is_empty() || name.len() > 200 {
118        return Err(format!("package name {name:?} has invalid length").into());
119    }
120    if name.contains("..") {
121        return Err(format!("package name {name:?} contains '..'").into());
122    }
123    if !name
124        .bytes()
125        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b'@' | b'/'))
126    {
127        return Err(format!("package name {name:?} contains disallowed characters").into());
128    }
129    Ok(())
130}
131
132/// Reject versions outside the semver-adjacent alphabet, before the value ends
133/// up in a URL, a cache filename, or a marker — none of which should contain a
134/// path separator.
135fn validate_version(version: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
136    if version.is_empty() || version.len() > 100 {
137        return Err(format!("version {version:?} has invalid length").into());
138    }
139    if version.contains("..") {
140        return Err(format!("version {version:?} contains '..'").into());
141    }
142    if !version
143        .bytes()
144        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'+' | b'_'))
145    {
146        return Err(format!("version {version:?} contains disallowed characters").into());
147    }
148    Ok(())
149}
150
151/// Extract a bare version from a spec string. Handles `"1.2.3"`, `"^1.2.3"`,
152/// `"~1.2.3"`, and git URLs (`"...#ref"` → `ref`).
153fn extract_version(value: &str) -> String {
154    if value.contains("github.com") || value.starts_with("git") {
155        if let Some(hash_pos) = value.rfind('#') {
156            return value[hash_pos + 1..].to_string();
157        }
158    }
159    value
160        .trim_start_matches('^')
161        .trim_start_matches('~')
162        .to_string()
163}
164
165/// The `"type"` field of a `package.json` (Node defaults to CommonJS).
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub enum PackageType {
168    Module,
169    CommonJs,
170}
171
172/// An import-map-worthy entry derived from a package's `package.json`.
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub enum Entry {
175    /// The bare specifier (`name`) → a target relative path (the `.` export).
176    Bare(String),
177    /// A concrete subpath (`name/<subpath>`) → a target relative path.
178    Subpath { subpath: String, target: String },
179    /// A subpath *pattern* (`"./…/*"` export). `subpath` is the prefix before `*`
180    /// (e.g. `"helpers/"` or `""`), `dir` the target directory before `*` (e.g.
181    /// `"dist/"`).
182    Prefix { subpath: String, dir: String },
183}
184
185/// Browser-favoring conditional-`exports` resolver over a parsed `package.json`.
186///
187/// Resolves the bare entry and subpaths to relative file paths using the
188/// condition order browsers want — `browser` → `module` → `import` → `default`
189/// (never `node`/`require`) — with a `module` → `browser` → `main` fallback when
190/// there is no `exports` field. Enough of the Node resolution algorithm to
191/// generate an ES-module import map; not a general-purpose resolver.
192#[derive(Debug, Clone)]
193pub struct PackageJson {
194    raw: Value,
195}
196
197impl License for PackageJson {
198    /// The manifest's declared license (`license` string, or the legacy object / `licenses[]` array).
199    fn license(&self) -> Option<String> {
200        normalize_license(&self.raw)
201    }
202}
203
204/// Conditions tried, in order, for a browser ES-module import map.
205const BROWSER_CONDITIONS: &[&str] = &["browser", "module", "import", "default"];
206
207impl PackageJson {
208    /// Read and parse a `package.json` from disk.
209    pub fn from_path(path: &Path) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
210        Self::from_json(&fs::read_to_string(path)?)
211    }
212
213    /// Parse a `package.json` from a JSON string (e.g. read out of a tarball).
214    pub fn from_json(s: &str) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
215        Ok(Self::from_value(serde_json::from_str(s)?))
216    }
217
218    /// Wrap an already-parsed JSON document.
219    pub fn from_value(raw: Value) -> Self {
220        Self { raw }
221    }
222
223    /// The `"name"` field, if present.
224    pub fn name(&self) -> Option<&str> {
225        self.raw.get("name").and_then(Value::as_str)
226    }
227
228    /// The `"version"` field, if present.
229    pub fn version(&self) -> Option<&str> {
230        self.raw.get("version").and_then(Value::as_str)
231    }
232
233    /// `Module` when `"type": "module"`, else `CommonJs` (Node's default).
234    pub fn package_type(&self) -> PackageType {
235        match self.raw.get("type").and_then(Value::as_str) {
236            Some("module") => PackageType::Module,
237            _ => PackageType::CommonJs,
238        }
239    }
240
241    /// Resolve the bare entry (the `.` export) to a relative path, for the browser.
242    pub fn resolve_main(&self) -> Option<String> {
243        if let Some(exports) = self.raw.get("exports") {
244            if let Some(s) = exports.as_str() {
245                return safe_target(s);
246            }
247            if let Some(obj) = exports.as_object() {
248                return if is_subpath_map(obj) {
249                    obj.get(".")
250                        .and_then(select_condition)
251                        .and_then(|s| safe_target(&s))
252                } else {
253                    select_condition(exports).and_then(|s| safe_target(&s))
254                };
255            }
256        }
257        // No usable `exports`: fall back to module → browser → main.
258        if let Some(s) = self.raw.get("module").and_then(Value::as_str) {
259            return safe_target(s);
260        }
261        if let Some(browser) = self.raw.get("browser") {
262            if let Some(s) = browser.as_str() {
263                return safe_target(s);
264            }
265            if let (Some(map), Some(main)) = (
266                browser.as_object(),
267                self.raw.get("main").and_then(Value::as_str),
268            ) {
269                let main = safe_target(main)?;
270                for (key, value) in map {
271                    if safe_target(key).as_deref() == Some(main.as_str()) {
272                        if let Some(s) = value.as_str() {
273                            return safe_target(s);
274                        }
275                    }
276                }
277            }
278        }
279        self.raw
280            .get("main")
281            .and_then(Value::as_str)
282            .and_then(safe_target)
283    }
284
285    /// Resolve a subpath (e.g. `"./helpers/decorate"`; leading `./` optional) via
286    /// the `exports` map — exact key first, then the longest `"./…/*"` pattern.
287    pub fn resolve_subpath(&self, subpath: &str) -> Option<String> {
288        let key = normalize_subpath_key(subpath);
289        let exports = self.raw.get("exports")?.as_object()?;
290        if !is_subpath_map(exports) {
291            return None;
292        }
293        if let Some(value) = exports.get(&key) {
294            return select_condition(value).and_then(|s| safe_target(&s));
295        }
296        let mut best_len = 0usize;
297        let mut best: Option<String> = None;
298        for (pattern, value) in exports {
299            let Some(star) = pattern.find('*') else {
300                continue;
301            };
302            let (prefix, suffix) = (&pattern[..star], &pattern[star + 1..]);
303            if key.len() >= prefix.len() + suffix.len()
304                && key.starts_with(prefix)
305                && key.ends_with(suffix)
306            {
307                let matched = &key[prefix.len()..key.len() - suffix.len()];
308                if let Some(target) = select_condition(value) {
309                    if let Some(resolved) = safe_target(&target.replace('*', matched)) {
310                        if best.is_none() || prefix.len() > best_len {
311                            best_len = prefix.len();
312                            best = Some(resolved);
313                        }
314                    }
315                }
316            }
317        }
318        best
319    }
320
321    /// Enumerate the import-map-worthy entries: the bare entry, concrete subpaths,
322    /// and `"./*"`-pattern prefixes.
323    pub fn entries(&self) -> Vec<Entry> {
324        let mut entries = Vec::new();
325        match self.raw.get("exports") {
326            Some(Value::Object(obj)) if is_subpath_map(obj) => {
327                for (key, value) in obj {
328                    if key == "." {
329                        if let Some(t) = select_condition(value).and_then(|s| safe_target(&s)) {
330                            entries.push(Entry::Bare(t));
331                        }
332                    } else if let Some(sub) = key.strip_prefix("./") {
333                        if let Some(star) = sub.find('*') {
334                            if let Some(dir) = select_condition(value).and_then(|t| target_dir(&t))
335                            {
336                                entries.push(Entry::Prefix {
337                                    subpath: sub[..star].to_string(),
338                                    dir,
339                                });
340                            }
341                        } else if let Some(t) =
342                            select_condition(value).and_then(|s| safe_target(&s))
343                        {
344                            entries.push(Entry::Subpath {
345                                subpath: sub.to_string(),
346                                target: t,
347                            });
348                        }
349                    }
350                }
351            }
352            // exports as a string or a pure conditions object, or no exports:
353            // only the bare entry (via resolve_main's logic + fallbacks).
354            _ => {
355                if let Some(t) = self.resolve_main() {
356                    entries.push(Entry::Bare(t));
357                }
358            }
359        }
360        entries
361    }
362
363    /// Every relative path the resolution references (concrete targets + pattern
364    /// directories) — used to keep the right files when vendoring, even under `src/`.
365    pub fn referenced_paths(&self) -> Vec<String> {
366        self.entries()
367            .into_iter()
368            .map(|e| match e {
369                Entry::Bare(t) | Entry::Subpath { target: t, .. } => t,
370                Entry::Prefix { dir, .. } => dir,
371            })
372            .collect()
373    }
374}
375
376/// Whether an `exports` object is a subpath map (keys like `"."`, `"./x"`) rather
377/// than a bare conditions map (keys like `"import"`, `"default"`).
378fn is_subpath_map(obj: &serde_json::Map<String, Value>) -> bool {
379    obj.keys().any(|k| k.starts_with('.'))
380}
381
382/// Pick the first target matching the browser condition order, recursing into
383/// nested condition objects and `exports` arrays (ordered fallbacks).
384fn select_condition(node: &Value) -> Option<String> {
385    match node {
386        Value::String(s) => Some(s.clone()),
387        Value::Array(arr) => arr.iter().find_map(select_condition),
388        Value::Object(map) => BROWSER_CONDITIONS
389            .iter()
390            .find_map(|cond| map.get(*cond).and_then(select_condition)),
391        _ => None,
392    }
393}
394
395/// Normalize a target: strip a leading `./`, reject `..`/empty (path traversal).
396fn safe_target(s: &str) -> Option<String> {
397    let t = s.strip_prefix("./").unwrap_or(s).trim_start_matches('/');
398    if t.is_empty() || t.split('/').any(|seg| seg == "..") {
399        return None;
400    }
401    Some(t.to_string())
402}
403
404/// `"./helpers/foo"` / `"helpers/foo"` → the canonical `"./helpers/foo"` key.
405fn normalize_subpath_key(subpath: &str) -> String {
406    if subpath.starts_with("./") {
407        subpath.to_string()
408    } else {
409        format!("./{}", subpath.trim_start_matches('/'))
410    }
411}
412
413/// The directory portion of a pattern target before `*` (e.g. `"./dist/*.js"` →
414/// `"dist/"`, `"./*.js"` → `""`). `None` if it would escape.
415fn target_dir(target: &str) -> Option<String> {
416    let star = target.find('*')?;
417    let before = target[..star].strip_prefix("./").unwrap_or(&target[..star]);
418    if before.split('/').any(|seg| seg == "..") {
419        return None;
420    }
421    Some(before.trim_start_matches('/').to_string())
422}
423
424#[cfg(test)]
425mod tests {
426    use super::*;
427    use tempfile::tempdir;
428
429    #[test]
430    fn parses_pinned_caret_and_git_specs() {
431        let tmp = tempdir().unwrap();
432        let p = tmp.path().join("package.json");
433        fs::write(
434            &p,
435            r#"{ "dependencies": {
436                "lit": "3.3.3",
437                "bootstrap": "^5.3.8",
438                "forked": "github:owner/repo#abc123"
439            } }"#,
440        )
441        .unwrap();
442
443        let deps = parse_dependencies(&p).unwrap();
444        assert_eq!(deps["lit"].version, "3.3.3");
445        assert!(!deps["lit"].is_git);
446        assert_eq!(deps["bootstrap"].version, "5.3.8");
447        assert_eq!(deps["forked"].version, "abc123");
448        assert!(deps["forked"].is_git);
449    }
450
451    #[test]
452    fn resolve_main_from_exports_and_fallbacks() {
453        // exports."." with conditions -> default.
454        let a = PackageJson::from_json(
455            r#"{"exports":{".":{"types":"./dev.d.ts","default":"./index.js"},"./decorators.js":{"default":"./decorators.js"}}}"#,
456        )
457        .unwrap();
458        assert_eq!(a.resolve_main().as_deref(), Some("index.js"));
459        assert_eq!(
460            a.resolve_subpath("./decorators.js").as_deref(),
461            Some("decorators.js")
462        );
463
464        // nested browser condition map under ".".
465        let b = PackageJson::from_json(
466            r#"{"type":"module","exports":{".":{"browser":{"development":"./development/lit-html.js","default":"./lit-html.js"},"default":"./lit-html.js"}}}"#,
467        )
468        .unwrap();
469        assert_eq!(b.resolve_main().as_deref(), Some("lit-html.js"));
470
471        // no exports -> module wins over main.
472        let c = PackageJson::from_json(
473            r#"{"main":"dist/js/bootstrap.js","module":"dist/js/bootstrap.esm.js"}"#,
474        )
475        .unwrap();
476        assert_eq!(
477            c.resolve_main().as_deref(),
478            Some("dist/js/bootstrap.esm.js")
479        );
480    }
481
482    #[test]
483    fn resolve_subpath_picks_import_condition_for_cjs_package() {
484        // CommonJS package, no ".", helper subpaths whose "import" condition is the
485        // ESM build under src/helpers/esm/.
486        let rt = PackageJson::from_json(
487            r#"{"type":"commonjs","exports":{"./helpers/decorate":[{"node":"./src/helpers/decorate.js","import":"./src/helpers/esm/decorate.js","default":"./src/helpers/decorate.js"}]}}"#,
488        )
489        .unwrap();
490        assert_eq!(rt.package_type(), PackageType::CommonJs);
491        assert!(rt.resolve_main().is_none());
492        assert_eq!(
493            rt.resolve_subpath("./helpers/decorate").as_deref(),
494            Some("src/helpers/esm/decorate.js")
495        );
496        assert_eq!(
497            rt.resolve_subpath("helpers/decorate").as_deref(),
498            Some("src/helpers/esm/decorate.js")
499        );
500        assert!(rt
501            .referenced_paths()
502            .iter()
503            .any(|p| p == "src/helpers/esm/decorate.js"));
504    }
505
506    #[test]
507    fn condition_order_prefers_browser_and_import_never_node() {
508        let x = PackageJson::from_json(
509            r#"{"exports":{".":{"node":"./n.js","require":"./r.js","import":"./esm.js","default":"./def.js"}}}"#,
510        )
511        .unwrap();
512        assert_eq!(x.resolve_main().as_deref(), Some("esm.js"));
513
514        let y = PackageJson::from_json(
515            r#"{"exports":{".":{"module":"./m.js","browser":"./b.js","default":"./d.js"}}}"#,
516        )
517        .unwrap();
518        assert_eq!(y.resolve_main().as_deref(), Some("b.js"));
519    }
520
521    #[test]
522    fn subpath_pattern_becomes_prefix_entry() {
523        let pkg = PackageJson::from_json(r#"{"exports":{".":"./index.js","./*":"./dist/*.js"}}"#)
524            .unwrap();
525        assert_eq!(pkg.resolve_subpath("./foo").as_deref(), Some("dist/foo.js"));
526        assert!(pkg.entries().iter().any(
527            |e| matches!(e, Entry::Prefix { subpath, dir } if subpath.is_empty() && dir == "dist/")
528        ));
529        assert!(pkg
530            .entries()
531            .iter()
532            .any(|e| matches!(e, Entry::Bare(t) if t == "index.js")));
533    }
534
535    #[test]
536    fn rejects_path_traversal_targets() {
537        let evil = PackageJson::from_json(r#"{"exports":{".":"../escape.js"}}"#).unwrap();
538        assert!(evil.resolve_main().is_none());
539    }
540}