Skip to main content

fallow_config/workspace/
package_json.rs

1use std::collections::BTreeMap;
2
3use serde::{
4    Deserialize, Deserializer, Serialize,
5    de::{Error, IgnoredAny, MapAccess, Visitor},
6};
7
8use super::pnpm_catalog::PnpmCatalogData;
9
10/// Type alias for standard `HashMap` used in serde-deserialized structs.
11/// `rustc-hash` v2 does not have a `serde` feature, so fields deserialized
12/// from JSON must use `std::collections::HashMap`.
13#[expect(
14    clippy::disallowed_types,
15    reason = "rustc-hash v2 lacks serde feature — JSON deserialization needs std HashMap"
16)]
17type StdHashMap<K, V> = std::collections::HashMap<K, V>;
18
19fn deserialize_optional_bool_lenient<'de, D>(deserializer: D) -> Result<Option<bool>, D::Error>
20where
21    D: Deserializer<'de>,
22{
23    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
24    Ok(match value {
25        Some(serde_json::Value::Bool(value)) => Some(value),
26        _ => None,
27    })
28}
29
30fn deserialize_string_array_lenient<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
31where
32    D: Deserializer<'de>,
33{
34    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
35    Ok(match value {
36        Some(serde_json::Value::Array(values)) => values
37            .into_iter()
38            .filter_map(|value| value.as_str().map(str::to_owned))
39            .collect(),
40        _ => Vec::new(),
41    })
42}
43
44fn deserialize_optional_string_lenient<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
45where
46    D: Deserializer<'de>,
47{
48    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
49    Ok(match value {
50        Some(serde_json::Value::String(value)) if !value.trim().is_empty() => Some(value),
51        _ => None,
52    })
53}
54
55fn deserialize_optional_napi_config<'de, D>(deserializer: D) -> Result<Option<NapiConfig>, D::Error>
56where
57    D: Deserializer<'de>,
58{
59    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
60    match value {
61        Some(serde_json::Value::Object(map)) => {
62            serde_json::from_value(serde_json::Value::Object(map))
63                .map(Some)
64                .map_err(D::Error::custom)
65        }
66        _ => Ok(None),
67    }
68}
69
70/// The text of a manifest such as `package.json` or `deno.json`. The file
71/// must be a regular file with a size limit, at a location that
72/// [`manifest_location_allowed`] accepts.
73fn read_manifest(path: &std::path::Path) -> Result<String, String> {
74    read_manifest_in(None, path)
75}
76
77/// [`read_manifest`] with the project scope base `scope` (see
78/// [`crate::project_scope_base`]). `None` takes the scope base from the
79/// location of the manifest.
80pub(super) fn read_manifest_in(
81    scope: Option<&std::path::Path>,
82    path: &std::path::Path,
83) -> Result<String, String> {
84    if path.symlink_metadata().is_ok() && !manifest_location_allowed(scope, path) {
85        return Err(format!(
86            "refusing to read {}: it resolves to a location outside its package",
87            path.display()
88        ));
89    }
90    fallow_types::read_guard::read_to_string_bounded(
91        path,
92        fallow_types::read_guard::DEFAULT_MAX_READ_BYTES,
93    )
94    .map_err(|e| e.to_string())
95}
96
97/// Whether the manifest at `path` resolves to an allowed place. A relative
98/// `path` is taken relative to the current directory.
99///
100/// - Below a `node_modules` directory, the resolved directory that holds the
101///   first such segment and the resolved file must both be inside the
102///   project scope base `scope`. That covers the `.pnpm` and `.bun` stores
103///   of the project, a pnpm link from a workspace package into the store at
104///   the root, and a workspace link such as
105///   `node_modules/@x/pkg -> ../packages/pkg`. A store outside the project,
106///   such as a global store, and a `node_modules` directory above the scope
107///   base are refused.
108/// - Elsewhere, the resolved file must be in the resolved directory of
109///   `path`. When that directory is a link, it must resolve inside `scope`
110///   or inside the directory that holds the link.
111///
112/// When `scope` is `None`, the scope base is the one of the directory that
113/// holds the first `node_modules` segment, or of the directory that holds
114/// the package directory.
115fn manifest_location_allowed(scope: Option<&std::path::Path>, path: &std::path::Path) -> bool {
116    use std::path::Component;
117    let Ok(target) = dunce::canonicalize(path) else {
118        return false;
119    };
120    let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
121    let lexical = fallow_types::path_guard::lexically_normalized(&absolute);
122    let scope_base = |dir: &std::path::Path| {
123        scope.map_or_else(
124            || crate::project_scope_base(dir),
125            std::path::Path::to_path_buf,
126        )
127    };
128    let mut prefix = std::path::PathBuf::new();
129    for component in lexical.components() {
130        if matches!(component, Component::Normal(name) if name == "node_modules") {
131            let base = scope_base(&prefix);
132            return target.starts_with(&base)
133                && dunce::canonicalize(&prefix).is_ok_and(|holder| holder.starts_with(&base));
134        }
135        prefix.push(component);
136    }
137    let Some(dir) = lexical.parent() else {
138        return false;
139    };
140    let Ok(canonical_dir) = dunce::canonicalize(dir) else {
141        return false;
142    };
143    if target.parent() != Some(canonical_dir.as_path()) {
144        return false;
145    }
146    let dir_is_link = dir
147        .symlink_metadata()
148        .is_ok_and(|meta| meta.file_type().is_symlink());
149    if !dir_is_link {
150        return true;
151    }
152    dir.parent().is_some_and(|holder| {
153        target.starts_with(scope_base(holder))
154            || dunce::canonicalize(holder).is_ok_and(|holder| target.starts_with(holder))
155    })
156}
157
158/// The `package.json` keys that hold the inline config of a built-in plugin
159/// ([`PackageJson::inline_tool_config`]).
160pub const INLINE_TOOL_CONFIG_KEYS: &[&str] = &[
161    "babel",
162    "commit-and-tag-version",
163    "eslintConfig",
164    "graphql",
165    "jest",
166    "mocha",
167    "nodemonConfig",
168    "prettier",
169    "release-it",
170    "stylelint",
171    "textlint",
172    "tsd",
173    "tsdown",
174    "tsup",
175];
176
177/// Keeps the value of each [`INLINE_TOOL_CONFIG_KEYS`] key raw. A repeated key
178/// keeps its last value, as `JSON.parse` does, and any value is accepted, so
179/// these keys never fail manifest parsing.
180fn deserialize_inline_tool_configs<'de, D>(
181    deserializer: D,
182) -> Result<BTreeMap<&'static str, serde_json::Value>, D::Error>
183where
184    D: Deserializer<'de>,
185{
186    struct InlineToolConfigs;
187
188    impl<'de> Visitor<'de> for InlineToolConfigs {
189        type Value = BTreeMap<&'static str, serde_json::Value>;
190
191        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
192            formatter.write_str("a package.json object")
193        }
194
195        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
196        where
197            A: MapAccess<'de>,
198        {
199            let mut configs = BTreeMap::new();
200            while let Some(key) = map.next_key::<String>()? {
201                match INLINE_TOOL_CONFIG_KEYS.iter().find(|known| **known == key) {
202                    Some(known) => {
203                        configs.insert(*known, map.next_value()?);
204                    }
205                    None => {
206                        map.next_value::<IgnoredAny>()?;
207                    }
208                }
209            }
210            Ok(configs)
211        }
212    }
213
214    deserializer.deserialize_map(InlineToolConfigs)
215}
216
217#[derive(Debug, Clone, Default, Deserialize, Serialize)]
218pub struct PeerDependencyMeta {
219    #[serde(default)]
220    pub optional: bool,
221}
222
223/// The NAPI-RS `napi` block of a `package.json`, used to recognize the
224/// per-platform artifact packages a native addon generates so they are not
225/// reported as unused dependencies. All fields deserialize leniently: a
226/// wrong-typed value becomes `None`/empty instead of failing manifest parsing.
227#[derive(Debug, Clone, Default, Deserialize, Serialize)]
228pub struct NapiConfig {
229    /// The `binaryName` field: basename of the generated `.node` binary.
230    #[serde(
231        default,
232        rename = "binaryName",
233        deserialize_with = "deserialize_optional_string_lenient"
234    )]
235    pub binary_name: Option<String>,
236    /// The `packageName` field: base npm package name from which per-platform
237    /// artifact package names (`<name>-<triple>`) are derived.
238    #[serde(
239        default,
240        rename = "packageName",
241        deserialize_with = "deserialize_optional_string_lenient"
242    )]
243    pub package_name: Option<String>,
244    /// The `targets` field: platform triples the addon is built for.
245    #[serde(default, deserialize_with = "deserialize_string_array_lenient")]
246    pub targets: Vec<String>,
247}
248
249/// Parsed package.json with fields relevant to fallow.
250#[derive(Debug, Clone, Default, Deserialize, Serialize)]
251pub struct PackageJson {
252    /// The `name` field: the package's npm name, used to identify workspace
253    /// packages and match `public_packages` config entries.
254    #[serde(default)]
255    pub name: Option<String>,
256    /// The `private` field. Non-boolean values become `None` rather than
257    /// failing manifest parsing.
258    #[serde(default, deserialize_with = "deserialize_optional_bool_lenient")]
259    pub private: Option<bool>,
260    /// The `main` field: CommonJS entry-point path, seeded as an entry point.
261    #[serde(default)]
262    pub main: Option<String>,
263    /// The `module` field: ESM entry-point path, seeded as an entry point.
264    #[serde(default)]
265    pub module: Option<String>,
266    /// The `types` field: type-declaration entry-point path.
267    #[serde(default)]
268    pub types: Option<String>,
269    /// The `typings` field: legacy spelling of `types`.
270    #[serde(default)]
271    pub typings: Option<String>,
272    /// The `source` field: unbundled source entry point used by bundler-based
273    /// packages (Parcel convention).
274    #[serde(default)]
275    pub source: Option<String>,
276    /// The `files` field: publish allowlist patterns. Non-array values become
277    /// empty rather than failing manifest parsing.
278    #[serde(default, deserialize_with = "deserialize_string_array_lenient")]
279    pub files: Vec<String>,
280    /// The `browser` field, kept raw because it is either a string entry point
281    /// or a path-remap object.
282    #[serde(default)]
283    pub browser: Option<serde_json::Value>,
284    /// The `bin` field, kept raw because it is either a string path or a
285    /// name-to-path object; every referenced file is an entry point.
286    #[serde(default)]
287    pub bin: Option<serde_json::Value>,
288    /// The `typescript` field, kept raw. Its `contentMapper.exec` command
289    /// names a script that TypeScript runs.
290    #[serde(default)]
291    pub typescript: Option<serde_json::Value>,
292    /// The `exports` field, kept raw because of its many shapes (string,
293    /// conditions object, subpath map); referenced files are entry points and
294    /// the map drives subpath resolution.
295    #[serde(default)]
296    pub exports: Option<serde_json::Value>,
297    /// The `imports` field (`#`-prefixed internal subpath map), kept raw and
298    /// consumed by the module resolver.
299    #[serde(default)]
300    pub imports: Option<serde_json::Value>,
301    /// The `dependencies` map (package name to version range), the base set
302    /// for unused/unlisted-dependency accounting.
303    #[serde(default)]
304    pub dependencies: Option<StdHashMap<String, String>>,
305    /// The `devDependencies` map, checked by `unused-dev-dependencies` and
306    /// `dev-dependency-in-production`.
307    #[serde(default, rename = "devDependencies")]
308    pub dev_dependencies: Option<StdHashMap<String, String>>,
309    /// The `peerDependencies` map. Peers are provided by the consumer, so
310    /// they are exempt from unused-dependency reporting.
311    #[serde(default, rename = "peerDependencies")]
312    pub peer_dependencies: Option<StdHashMap<String, String>>,
313    /// The `peerDependenciesMeta` map, marking which peers are optional.
314    #[serde(default, rename = "peerDependenciesMeta")]
315    pub peer_dependencies_meta: Option<StdHashMap<String, PeerDependencyMeta>>,
316    /// The `optionalDependencies` map, checked by
317    /// `unused-optional-dependencies`.
318    #[serde(default, rename = "optionalDependencies")]
319    pub optional_dependencies: Option<StdHashMap<String, String>>,
320    /// The `scripts` map, scanned so packages invoked from scripts count as
321    /// used tooling dependencies.
322    #[serde(default)]
323    pub scripts: Option<StdHashMap<String, String>>,
324    /// The NAPI-RS `napi` block; see [`NapiConfig`]. Non-object values become
325    /// `None` rather than failing manifest parsing.
326    #[serde(default, deserialize_with = "deserialize_optional_napi_config")]
327    pub napi: Option<NapiConfig>,
328    /// The `workspaces` field, kept raw because it is either a pattern array
329    /// or an object with a `packages` array; drives workspace discovery.
330    #[serde(default)]
331    pub workspaces: Option<serde_json::Value>,
332    /// The `packageManager` field (e.g. `"pnpm@9.1.0"`), used to determine
333    /// the canonical package manager for the project.
334    #[serde(
335        default,
336        rename = "packageManager",
337        deserialize_with = "deserialize_optional_string_lenient"
338    )]
339    pub package_manager: Option<String>,
340    /// The Egg.js `egg` block (for example `framework` and `tscompiler`),
341    /// kept raw so that an unexpected shape does not fail manifest parsing.
342    #[serde(default)]
343    pub egg: Option<serde_json::Value>,
344    /// The Egg.js `eggPlugin` block of a plugin package, kept raw.
345    #[serde(default, rename = "eggPlugin")]
346    pub egg_plugin: Option<serde_json::Value>,
347    /// The tegg `eggModule` block of a module package, kept raw.
348    #[serde(default, rename = "eggModule")]
349    pub egg_module: Option<serde_json::Value>,
350    /// The `n8n` block of an n8n node package (`nodes` and `credentials`),
351    /// kept raw so that an unexpected shape does not fail manifest parsing.
352    #[serde(default)]
353    pub n8n: Option<serde_json::Value>,
354    /// The value of each [`INLINE_TOOL_CONFIG_KEYS`] key that the manifest
355    /// has, kept raw. See [`PackageJson::inline_tool_config`].
356    #[serde(default, flatten, deserialize_with = "deserialize_inline_tool_configs")]
357    pub inline_tool_configs: BTreeMap<&'static str, serde_json::Value>,
358}
359
360/// The package.json field that declares an entry point.
361#[derive(Debug, Clone, Copy, PartialEq, Eq)]
362pub enum PackageEntryField {
363    /// The `main` field.
364    Main,
365    /// The `module` field.
366    Module,
367    /// The `types` field.
368    Types,
369    /// The `typings` field.
370    Typings,
371    /// The `source` field.
372    Source,
373    /// The `browser` field, as a string or as a map of replacement paths.
374    Browser,
375    /// The `bin` field, as a string or as a map of command names.
376    Bin,
377    /// The `exports` field, at any depth of conditions and subpaths.
378    Exports,
379}
380
381impl From<PackageEntryField> for fallow_types::discover::EntryPointSource {
382    fn from(field: PackageEntryField) -> Self {
383        match field {
384            PackageEntryField::Main => Self::PackageJsonMain,
385            PackageEntryField::Module => Self::PackageJsonModule,
386            PackageEntryField::Types => Self::PackageJsonTypes,
387            PackageEntryField::Typings => Self::PackageJsonTypings,
388            PackageEntryField::Source => Self::PackageJsonSource,
389            PackageEntryField::Browser => Self::PackageJsonBrowser,
390            PackageEntryField::Bin => Self::PackageJsonBin,
391            PackageEntryField::Exports => Self::PackageJsonExports,
392        }
393    }
394}
395
396/// Collects the paths of a field that holds one string or a map of strings.
397/// `keep_map_value` filters the map values: a `browser` map also holds bare
398/// package names, which are not files of the package.
399fn push_string_values(
400    entries: &mut Vec<(PackageEntryField, String)>,
401    field: PackageEntryField,
402    value: &serde_json::Value,
403    keep_map_value: impl Fn(&str) -> bool,
404) {
405    match value {
406        serde_json::Value::String(path) => entries.push((field, path.clone())),
407        serde_json::Value::Object(map) => {
408            let paths = map
409                .values()
410                .filter_map(serde_json::Value::as_str)
411                .filter(|path| keep_map_value(path));
412            entries.extend(paths.map(|path| (field, path.to_owned())));
413        }
414        _ => {}
415    }
416}
417
418impl PackageJson {
419    /// The raw value of the tool config key `key`, such as `prettier` or
420    /// `nodemonConfig`. Returns `None` when the manifest has no such key, or
421    /// when `key` is not in [`INLINE_TOOL_CONFIG_KEYS`].
422    #[must_use]
423    pub fn inline_tool_config(&self, key: &str) -> Option<&serde_json::Value> {
424        self.inline_tool_configs.get(key)
425    }
426
427    /// Load from a package.json file.
428    ///
429    /// # Errors
430    ///
431    /// Returns an error string when the file cannot be read or parsed as JSON.
432    ///
433    /// The file must be a regular file of at most
434    /// [`fallow_types::read_guard::DEFAULT_MAX_READ_BYTES`]. A `package.json`
435    /// that is a link must resolve to a file in its own directory or in a
436    /// `node_modules` directory. The parse error names the position, not the
437    /// bad value.
438    pub fn load(path: &std::path::Path) -> Result<Self, String> {
439        let content = read_manifest(path)?;
440        Self::parse_named(path, &content)
441    }
442
443    /// [`Self::load`] for a manifest that dependency resolution finds, such
444    /// as `node_modules/<name>/package.json`, with the project scope base
445    /// `scope` from [`crate::project_scope_base`]. A manifest below
446    /// `node_modules` may resolve anywhere inside `scope`.
447    ///
448    /// # Errors
449    ///
450    /// Returns the same errors as [`Self::load`].
451    pub fn load_in_scope(scope: &std::path::Path, path: &std::path::Path) -> Result<Self, String> {
452        let content = read_manifest_in(Some(scope), path)?;
453        Self::parse_named(path, &content)
454    }
455
456    /// [`Self::load`] for a manifest of the project, for example the root
457    /// `package.json` or the one of a workspace member: the file must
458    /// resolve inside `root`.
459    ///
460    /// # Errors
461    ///
462    /// Returns an error string when the file resolves outside `root`, cannot
463    /// be read, or does not parse.
464    pub fn load_inside(root: &std::path::Path, path: &std::path::Path) -> Result<Self, String> {
465        let content = fallow_types::read_guard::read_to_string_inside(
466            root,
467            path,
468            fallow_types::read_guard::DEFAULT_MAX_READ_BYTES,
469        )
470        .map_err(|e| e.to_string())?;
471        Self::parse_named(path, &content)
472    }
473
474    fn parse_named(path: &std::path::Path, content: &str) -> Result<Self, String> {
475        Self::parse(content).map_err(|e| {
476            format!(
477                "Failed to parse {}: {}",
478                path.display(),
479                crate::parse_error::describe_json(&e)
480            )
481        })
482    }
483
484    /// Read the text of a package.json file without a leading UTF-8 byte
485    /// order mark, for a parser that reads the raw JSON. The mark sits on
486    /// line 1, so line numbers do not change. The read has the same file
487    /// checks as [`Self::load`].
488    ///
489    /// # Errors
490    ///
491    /// Returns the I/O error when the file cannot be read as UTF-8 text, or
492    /// a `PermissionDenied` error when a check refuses the file.
493    pub fn read_source(path: &std::path::Path) -> std::io::Result<String> {
494        Self::read_source_in(None, path)
495    }
496
497    /// [`Self::read_source`] with the project scope base `scope`, as
498    /// [`Self::load_in_scope`] takes it.
499    ///
500    /// # Errors
501    ///
502    /// Returns the same errors as [`Self::read_source`].
503    pub fn read_source_in_scope(
504        scope: &std::path::Path,
505        path: &std::path::Path,
506    ) -> std::io::Result<String> {
507        Self::read_source_in(Some(scope), path)
508    }
509
510    fn read_source_in(
511        scope: Option<&std::path::Path>,
512        path: &std::path::Path,
513    ) -> std::io::Result<String> {
514        let mut source = read_manifest_in(scope, path).map_err(|message| {
515            if path.symlink_metadata().is_err() {
516                std::io::Error::new(std::io::ErrorKind::NotFound, message)
517            } else {
518                std::io::Error::new(std::io::ErrorKind::PermissionDenied, message)
519            }
520        })?;
521        if source.starts_with('\u{FEFF}') {
522            source.drain(..'\u{FEFF}'.len_utf8());
523        }
524        Ok(source)
525    }
526
527    /// Parse package.json source text. A leading UTF-8 byte order mark is
528    /// ignored, as npm and Node.js do.
529    ///
530    /// # Errors
531    ///
532    /// Returns the JSON error when the text is not a valid manifest.
533    pub fn parse(source: &str) -> Result<Self, serde_json::Error> {
534        serde_json::from_str(source.trim_start_matches('\u{FEFF}'))
535    }
536
537    /// Get all dependency names (production + dev + peer + optional).
538    #[must_use]
539    pub fn all_dependency_names(&self) -> Vec<String> {
540        let mut deps = Vec::new();
541        if let Some(d) = &self.dependencies {
542            deps.extend(d.keys().cloned());
543        }
544        if let Some(d) = &self.dev_dependencies {
545            deps.extend(d.keys().cloned());
546        }
547        if let Some(d) = &self.peer_dependencies {
548            deps.extend(d.keys().cloned());
549        }
550        if let Some(d) = &self.optional_dependencies {
551            deps.extend(d.keys().cloned());
552        }
553        deps
554    }
555
556    /// Get production dependency names only.
557    #[must_use]
558    pub fn production_dependency_names(&self) -> Vec<String> {
559        self.dependencies
560            .as_ref()
561            .map(|d| d.keys().cloned().collect())
562            .unwrap_or_default()
563    }
564
565    /// Get dev dependency names only.
566    #[must_use]
567    pub fn dev_dependency_names(&self) -> Vec<String> {
568        self.dev_dependencies
569            .as_ref()
570            .map(|d| d.keys().cloned().collect())
571            .unwrap_or_default()
572    }
573
574    /// Get optional dependency names only.
575    #[must_use]
576    pub fn optional_dependency_names(&self) -> Vec<String> {
577        self.optional_dependencies
578            .as_ref()
579            .map(|d| d.keys().cloned().collect())
580            .unwrap_or_default()
581    }
582
583    /// Get every peer dependency name, required or optional.
584    #[must_use]
585    pub fn peer_dependency_names(&self) -> Vec<String> {
586        self.peer_dependencies
587            .as_ref()
588            .map(|deps| deps.keys().cloned().collect())
589            .unwrap_or_default()
590    }
591
592    /// Whether `peerDependenciesMeta` marks the peer `dep` as optional.
593    #[must_use]
594    pub fn peer_dependency_is_optional(&self, dep: &str) -> bool {
595        self.peer_dependencies_meta
596            .as_ref()
597            .and_then(|meta| meta.get(dep))
598            .is_some_and(|meta| meta.optional)
599    }
600
601    /// Extract entry points from package.json fields.
602    #[must_use]
603    pub fn entry_points(&self) -> Vec<String> {
604        self.entry_points_by_field()
605            .into_iter()
606            .map(|(_, entry)| entry)
607            .collect()
608    }
609
610    /// Extract entry points from package.json fields, each with the field
611    /// that declares it, in field order: `main`, `module`, `types`,
612    /// `typings`, `source`, `browser`, `bin`, `exports`.
613    #[must_use]
614    pub fn entry_points_by_field(&self) -> Vec<(PackageEntryField, String)> {
615        let mut entries = Vec::new();
616
617        for (field, value) in [
618            (PackageEntryField::Main, &self.main),
619            (PackageEntryField::Module, &self.module),
620            (PackageEntryField::Types, &self.types),
621            (PackageEntryField::Typings, &self.typings),
622            (PackageEntryField::Source, &self.source),
623        ] {
624            if let Some(entry) = value {
625                entries.push((field, entry.clone()));
626            }
627        }
628
629        if let Some(browser) = &self.browser {
630            // Like `exports`, a `browser` path with a `..` segment is never
631            // followed out of the package.
632            push_string_values(&mut entries, PackageEntryField::Browser, browser, |path| {
633                path.starts_with("./")
634            });
635            entries.retain(|(field, path)| {
636                *field != PackageEntryField::Browser || !has_dot_dot_segment(path)
637            });
638        }
639
640        if let Some(bin) = &self.bin {
641            push_string_values(&mut entries, PackageEntryField::Bin, bin, |_| true);
642        }
643
644        if let Some(exports) = &self.exports {
645            let mut exported = Vec::new();
646            extract_exports_entries(exports, &mut exported);
647            entries.extend(
648                exported
649                    .into_iter()
650                    .map(|entry| (PackageEntryField::Exports, entry)),
651            );
652        }
653
654        entries
655    }
656
657    /// Extract unique subdirectory names referenced by the `exports` field keys.
658    ///
659    /// For exports like `"./compat": { ... }`, `"./hooks/client": { ... }`,
660    /// this returns `["compat", "hooks"]`. Used to discover sub-packages in
661    /// projects that define their internal package structure via the exports map
662    /// (e.g., preact with `compat/`, `hooks/`, `debug/` sub-packages).
663    #[must_use]
664    pub fn exports_subdirectories(&self) -> Vec<String> {
665        self.exports
666            .as_ref()
667            .map_or_else(Vec::new, extract_exports_subdirectories)
668    }
669
670    /// Extract workspace patterns from package.json.
671    #[must_use]
672    pub fn workspace_patterns(&self) -> Vec<String> {
673        match &self.workspaces {
674            Some(serde_json::Value::Array(arr)) => arr
675                .iter()
676                .filter_map(|v| v.as_str().map(String::from))
677                .collect(),
678            Some(serde_json::Value::Object(obj)) => obj
679                .get("packages")
680                .and_then(|v| v.as_array())
681                .map(|arr| {
682                    arr.iter()
683                        .filter_map(|v| v.as_str().map(String::from))
684                        .collect()
685                })
686                .unwrap_or_default(),
687            _ => Vec::new(),
688        }
689    }
690
691    /// Dependencies with a `link:` or `file:` spec in `dependencies`,
692    /// `devDependencies` or `optionalDependencies`, as `(name, target)` pairs
693    /// sorted by name.
694    ///
695    /// The target is the path as written, relative to this manifest's
696    /// directory. The caller decides which targets are real package
697    /// directories.
698    #[must_use]
699    pub fn local_link_dependencies(&self) -> Vec<(String, String)> {
700        let mut links: Vec<(String, String)> = [
701            &self.dependencies,
702            &self.dev_dependencies,
703            &self.optional_dependencies,
704        ]
705        .into_iter()
706        .flatten()
707        .flatten()
708        .filter_map(|(name, spec)| {
709            let target = spec
710                .strip_prefix("link:")
711                .or_else(|| spec.strip_prefix("file:"))?
712                .trim();
713            (!target.is_empty()).then(|| (name.clone(), target.to_string()))
714        })
715        .collect();
716        links.sort_unstable();
717        links.dedup();
718        links
719    }
720
721    /// The workspace package that the dependency `name` is an alias of.
722    ///
723    /// pnpm installs `"vite": "workspace:@scope/core@*"` as the workspace
724    /// package `@scope/core` under the name `vite`. A `workspace:` spec with
725    /// only a range (`workspace:*`, `workspace:^1.0.0`) or a path
726    /// (`workspace:../core`) is not an alias.
727    #[must_use]
728    pub fn workspace_alias_target(&self, name: &str) -> Option<&str> {
729        [
730            &self.dependencies,
731            &self.dev_dependencies,
732            &self.optional_dependencies,
733            &self.peer_dependencies,
734        ]
735        .into_iter()
736        .flatten()
737        .find_map(|deps| deps.get(name))
738        .and_then(|spec| workspace_alias_name(spec))
739    }
740
741    /// Every dependency that the manifest installs under an npm alias, as
742    /// `(alias, aliased package)` pairs.
743    ///
744    /// `"@typescript/native": "npm:typescript@~7.0.2"` installs the package
745    /// `typescript` in `node_modules/@typescript/native`, so the alias
746    /// provides the binaries of `typescript`.
747    #[must_use]
748    pub fn npm_aliases(&self) -> Vec<(String, String)> {
749        self.npm_aliases_with_catalogs(None)
750    }
751
752    /// Every npm alias of the manifest, as [`Self::npm_aliases`] gives, plus
753    /// every alias that a `catalog:` reference gets from `catalogs`.
754    ///
755    /// `"@typescript/native": "catalog:"` with the catalog entry
756    /// `"@typescript/native": npm:typescript@~7.0.2` installs `typescript`
757    /// under the alias, the same as the inline spec.
758    #[must_use]
759    pub fn npm_aliases_with_catalogs(
760        &self,
761        catalogs: Option<&PnpmCatalogData>,
762    ) -> Vec<(String, String)> {
763        let mut aliases: Vec<(String, String)> = [
764            &self.dependencies,
765            &self.dev_dependencies,
766            &self.optional_dependencies,
767            &self.peer_dependencies,
768        ]
769        .into_iter()
770        .flatten()
771        .flat_map(|deps| deps.iter())
772        .filter_map(|(name, spec)| {
773            let spec = catalogs
774                .and_then(|data| data.resolve_reference(name, spec))
775                .unwrap_or(spec);
776            let target = npm_alias_name(spec)?;
777            (target != name).then(|| (name.clone(), target.to_string()))
778        })
779        .collect();
780        aliases.sort_unstable();
781        aliases.dedup();
782        aliases
783    }
784}
785
786/// The package name in a `workspace:<name>@<range>` dependency spec.
787fn workspace_alias_name(spec: &str) -> Option<&str> {
788    let rest = spec.trim().strip_prefix("workspace:")?;
789    let separator = if let Some(scoped) = rest.strip_prefix('@') {
790        scoped.find('@')? + 1
791    } else {
792        rest.find('@')?
793    };
794    valid_package_name(&rest[..separator])
795}
796
797/// The package name in an `npm:<name>@<range>` or `npm:<name>` dependency
798/// spec.
799fn npm_alias_name(spec: &str) -> Option<&str> {
800    let rest = spec.trim().strip_prefix("npm:")?;
801    let separator = if let Some(scoped) = rest.strip_prefix('@') {
802        scoped.find('@').map_or(rest.len(), |at| at + 1)
803    } else {
804        rest.find('@').unwrap_or(rest.len())
805    };
806    valid_package_name(&rest[..separator])
807}
808
809/// `name` when it has the shape of a package name: `name` or `@scope/name`.
810fn valid_package_name(name: &str) -> Option<&str> {
811    let is_package_name = !name.is_empty()
812        && !name.starts_with('.')
813        && match name.strip_prefix('@') {
814            Some(scoped) => scoped
815                .split_once('/')
816                .is_some_and(|(scope, base)| !scope.is_empty() && !base.is_empty()),
817            None => !name.contains('/'),
818        };
819    is_package_name.then_some(name)
820}
821
822/// True when `name` is exactly one normal path component on every platform.
823fn is_plain_dir_name(name: &str) -> bool {
824    !name.is_empty()
825        && !name.contains(['\\', ':'])
826        && matches!(
827            std::path::Path::new(name)
828                .components()
829                .collect::<Vec<_>>()
830                .as_slice(),
831            [std::path::Component::Normal(_)]
832        )
833}
834
835/// True when a `/` or `\\` separated path has a `..` segment.
836fn has_dot_dot_segment(path: &str) -> bool {
837    path.split(['/', '\\']).any(|segment| segment == "..")
838}
839
840fn extract_exports_subdirectories(exports: &serde_json::Value) -> Vec<String> {
841    let Some(map) = exports.as_object() else {
842        return Vec::new();
843    };
844
845    let skip_dirs = ["dist", "build", "out", "esm", "cjs", "lib", "node_modules"];
846    let mut dirs = rustc_hash::FxHashSet::default();
847
848    for key in map.keys().filter(|key| !has_dot_dot_segment(key)) {
849        // A subpath key starts with `./`. The first segment must be one plain
850        // directory name: no `\`, no `:`, and not empty.
851        let Some(stripped) = key.strip_prefix("./") else {
852            continue;
853        };
854        if let Some(first_segment) = stripped.split('/').next()
855            && is_plain_dir_name(first_segment)
856            && first_segment != "package.json"
857            && !skip_dirs.contains(&first_segment)
858        {
859            dirs.insert(first_segment.to_owned());
860        }
861    }
862
863    dirs.into_iter().collect()
864}
865
866/// Recursively extract file paths from package.json exports field.
867///
868/// Node.js accepts only `./` targets without a `..` segment, so a target
869/// that is `../x` or has a `..` segment is skipped, and so is the value of a
870/// key with a `..` segment. Such a path is never followed out of the
871/// package.
872fn extract_exports_entries(value: &serde_json::Value, entries: &mut Vec<String>) {
873    match value {
874        serde_json::Value::String(s) if s.starts_with("./") && !has_dot_dot_segment(s) => {
875            entries.push(s.clone());
876        }
877        serde_json::Value::Object(map) => {
878            for (key, v) in map {
879                if !has_dot_dot_segment(key) {
880                    extract_exports_entries(v, entries);
881                }
882            }
883        }
884        serde_json::Value::Array(arr) => {
885            for v in arr {
886                extract_exports_entries(v, entries);
887            }
888        }
889        _ => {}
890    }
891}
892
893#[cfg(test)]
894mod tests {
895    use super::*;
896
897    #[cfg(unix)]
898    #[test]
899    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
900    fn a_dependency_link_to_another_node_modules_dir_is_refused() {
901        let dir = tempfile::tempdir().unwrap();
902        crate::project_read::set_test_ceiling(&dunce::canonicalize(dir.path()).unwrap());
903        let other = dir.path().join("other/node_modules/pkg");
904        std::fs::create_dir_all(&other).unwrap();
905        std::fs::write(other.join("package.json"), r#"{"name": "pkg"}"#).unwrap();
906        let project = dir.path().join("project");
907        std::fs::create_dir_all(project.join("node_modules")).unwrap();
908        std::os::unix::fs::symlink(&other, project.join("node_modules/pkg")).unwrap();
909        assert!(PackageJson::load(&project.join("node_modules/pkg/package.json")).is_err());
910    }
911
912    #[cfg(unix)]
913    #[test]
914    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
915    fn a_package_dir_link_out_of_its_parent_is_refused() {
916        let dir = tempfile::tempdir().unwrap();
917        crate::project_read::set_test_ceiling(&dunce::canonicalize(dir.path()).unwrap());
918        let outside = dir.path().join("outside");
919        std::fs::create_dir(&outside).unwrap();
920        std::fs::write(outside.join("package.json"), r#"{"name": "x"}"#).unwrap();
921        let project = dir.path().join("project");
922        std::fs::create_dir_all(project.join("packages")).unwrap();
923        std::os::unix::fs::symlink(&outside, project.join("packages/x")).unwrap();
924        assert!(PackageJson::load(&project.join("packages/x/package.json")).is_err());
925    }
926
927    #[cfg(unix)]
928    #[test]
929    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
930    fn a_manifest_link_in_its_own_dir_and_a_plain_manifest_load() {
931        let dir = tempfile::tempdir().unwrap();
932        std::fs::write(dir.path().join("package.base.json"), r#"{"name": "a"}"#).unwrap();
933        std::os::unix::fs::symlink("package.base.json", dir.path().join("package.json")).unwrap();
934        assert!(PackageJson::load(&dir.path().join("package.json")).is_ok());
935        std::fs::create_dir(dir.path().join("b")).unwrap();
936        std::fs::write(dir.path().join("b/package.json"), r#"{"name": "b"}"#).unwrap();
937        assert!(PackageJson::load(&dir.path().join("b/package.json")).is_ok());
938    }
939
940    #[test]
941    fn exports_subdirectories_take_one_plain_first_segment() {
942        let pkg: PackageJson = serde_json::from_str(
943            r#"{"exports": {
944                "./ok/x": "./ok/x.js",
945                "plain/x": "./plain.js",
946                "./back\\slash/x": "./b.js",
947                "./c:d/x": "./c.js",
948                ".//abs/x": "./e.js",
949                "./": "./f.js",
950                "./g": "./g.js"
951            }}"#,
952        )
953        .unwrap();
954        let mut dirs = pkg.exports_subdirectories();
955        dirs.sort();
956        assert_eq!(dirs, vec!["g", "ok"]);
957    }
958
959    #[test]
960    fn browser_paths_with_dot_dot_segments_are_not_followed() {
961        let pkg: PackageJson = serde_json::from_str(
962            r#"{"browser": {
963                "./a.js": "./a.browser.js",
964                "./b.js": "../outside/b.js",
965                "./c.js": "./x/../../c.js"
966            }}"#,
967        )
968        .unwrap();
969        let entries: Vec<String> = pkg
970            .entry_points_by_field()
971            .into_iter()
972            .map(|(_, entry)| entry)
973            .collect();
974        assert_eq!(entries, vec!["./a.browser.js"]);
975    }
976
977    #[test]
978    fn exports_with_dot_dot_segments_are_not_followed() {
979        let pkg: PackageJson = serde_json::from_str(
980            r#"{"exports": {
981                ".": "./src/index.ts",
982                "./../outside": "./src/a.ts",
983                "./a": "../outside/a.ts",
984                "./b": "./src/../../outside/b.ts",
985                "./c": { "import": "./src/c.ts", "default": "./x/../../y.ts" }
986            }}"#,
987        )
988        .unwrap();
989        let entries: Vec<String> = pkg
990            .entry_points_by_field()
991            .into_iter()
992            .map(|(_, entry)| entry)
993            .collect();
994        assert_eq!(entries, vec!["./src/index.ts", "./src/c.ts"]);
995        let mut dirs = pkg.exports_subdirectories();
996        dirs.sort();
997        assert_eq!(dirs, vec!["a", "b", "c"]);
998    }
999
1000    #[cfg(unix)]
1001    #[test]
1002    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1003    fn a_manifest_link_out_of_its_package_is_refused() {
1004        let dir = tempfile::tempdir().unwrap();
1005        let project = dir.path().join("project");
1006        std::fs::create_dir(&project).unwrap();
1007        std::fs::write(dir.path().join("outside.json"), r#"{"name": "outside"}"#).unwrap();
1008        std::os::unix::fs::symlink(
1009            dir.path().join("outside.json"),
1010            project.join("package.json"),
1011        )
1012        .unwrap();
1013        assert!(PackageJson::load(&project.join("package.json")).is_err());
1014        assert!(PackageJson::read_source(&project.join("package.json")).is_err());
1015        assert!(PackageJson::load_inside(&project, &project.join("package.json")).is_err());
1016    }
1017
1018    #[cfg(unix)]
1019    #[test]
1020    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1021    fn a_dependency_manifest_in_a_node_modules_store_loads() {
1022        let dir = tempfile::tempdir().unwrap();
1023        let store = dir
1024            .path()
1025            .join("node_modules/.pnpm/pkg@1.0.0/node_modules/pkg");
1026        std::fs::create_dir_all(&store).unwrap();
1027        std::fs::write(store.join("package.json"), r#"{"name": "pkg"}"#).unwrap();
1028        let linked = dir.path().join("node_modules/pkg");
1029        std::os::unix::fs::symlink(&store, &linked).unwrap();
1030        let pkg = PackageJson::load(&linked.join("package.json")).unwrap();
1031        assert_eq!(pkg.name.as_deref(), Some("pkg"));
1032    }
1033
1034    #[cfg(unix)]
1035    fn store_package(root: &std::path::Path, store: &str, name: &str) -> std::path::PathBuf {
1036        let dir = root.join(format!(
1037            "node_modules/{store}/{name}@1.0.0/node_modules/{name}"
1038        ));
1039        std::fs::create_dir_all(&dir).unwrap();
1040        std::fs::write(dir.join("package.json"), format!(r#"{{"name": "{name}"}}"#)).unwrap();
1041        dir
1042    }
1043
1044    #[cfg(unix)]
1045    #[test]
1046    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1047    fn workspace_package_links_into_the_root_store_load() {
1048        for store in [".pnpm", ".bun"] {
1049            let dir = tempfile::tempdir().unwrap();
1050            let root = dunce::canonicalize(dir.path()).unwrap();
1051            let stored = store_package(&root, store, "react-dom");
1052            let member = root.join("packages/a/node_modules");
1053            std::fs::create_dir_all(&member).unwrap();
1054            std::os::unix::fs::symlink(&stored, member.join("react-dom")).unwrap();
1055            let manifest = member.join("react-dom/package.json");
1056
1057            let pkg = PackageJson::load_in_scope(&root, &manifest).unwrap();
1058            assert_eq!(pkg.name.as_deref(), Some("react-dom"), "{store}");
1059            std::fs::create_dir(root.join(".git")).unwrap();
1060            assert!(PackageJson::load(&manifest).is_ok(), "{store}");
1061        }
1062    }
1063
1064    #[cfg(unix)]
1065    #[test]
1066    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1067    fn a_workspace_link_in_node_modules_loads() {
1068        let dir = tempfile::tempdir().unwrap();
1069        let root = dunce::canonicalize(dir.path()).unwrap();
1070        std::fs::create_dir_all(root.join("packages/pkg")).unwrap();
1071        std::fs::write(
1072            root.join("packages/pkg/package.json"),
1073            r#"{"name": "@x/pkg"}"#,
1074        )
1075        .unwrap();
1076        std::fs::create_dir_all(root.join("node_modules/@x")).unwrap();
1077        std::os::unix::fs::symlink("../../packages/pkg", root.join("node_modules/@x/pkg")).unwrap();
1078        let manifest = root.join("node_modules/@x/pkg/package.json");
1079
1080        let pkg = PackageJson::load_in_scope(&root, &manifest).unwrap();
1081        assert_eq!(pkg.name.as_deref(), Some("@x/pkg"));
1082        std::fs::create_dir(root.join(".git")).unwrap();
1083        assert!(PackageJson::load(&manifest).is_ok());
1084    }
1085
1086    #[test]
1087    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1088    fn a_relative_manifest_path_loads() {
1089        // A unit test runs in the directory of its crate, two levels below
1090        // the `package.json` of the repository.
1091        let pkg = PackageJson::load(std::path::Path::new("../../package.json")).unwrap();
1092        assert!(pkg.name.is_some());
1093
1094        // A relative path with a leading `..` before `node_modules`.
1095        let dir = tempfile::tempdir().unwrap();
1096        let root = dunce::canonicalize(dir.path()).unwrap();
1097        std::fs::create_dir_all(root.join("node_modules/x")).unwrap();
1098        std::fs::write(root.join("node_modules/x/package.json"), r#"{"name": "x"}"#).unwrap();
1099        let cwd = dunce::canonicalize(std::env::current_dir().unwrap()).unwrap();
1100        let prefix = |path: &std::path::Path| {
1101            path.components()
1102                .find(|part| matches!(part, std::path::Component::Prefix(_)))
1103                .map(|part| part.as_os_str().to_owned())
1104        };
1105        // A relative path cannot change the drive, so the check needs the
1106        // temp dir on the drive of the crate.
1107        if prefix(&cwd) == prefix(&root) {
1108            let mut relative = std::path::PathBuf::new();
1109            for part in cwd.components() {
1110                if matches!(part, std::path::Component::Normal(_)) {
1111                    relative.push("..");
1112                }
1113            }
1114            for part in root.components() {
1115                if let std::path::Component::Normal(name) = part {
1116                    relative.push(name);
1117                }
1118            }
1119            relative.push("node_modules/x/package.json");
1120            let pkg = PackageJson::load(&relative).unwrap();
1121            assert_eq!(pkg.name.as_deref(), Some("x"));
1122        }
1123    }
1124
1125    /// A workspace without a `.git` entry, with the member `packages/a` and
1126    /// the root file `manifest` that lists it.
1127    #[cfg(unix)]
1128    fn workspace_without_git(manifest: (&str, &str)) -> (tempfile::TempDir, std::path::PathBuf) {
1129        let dir = tempfile::tempdir().unwrap();
1130        let root = dunce::canonicalize(dir.path()).unwrap();
1131        crate::project_read::set_test_ceiling(&root);
1132        std::fs::create_dir_all(root.join("packages/a/node_modules")).unwrap();
1133        std::fs::write(root.join(manifest.0), manifest.1).unwrap();
1134        (dir, root)
1135    }
1136
1137    #[cfg(unix)]
1138    #[test]
1139    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1140    fn a_member_root_without_git_loads_the_manifests_of_the_workspace() {
1141        // pnpm: the member links into the store at the workspace root.
1142        let (_dir, root) =
1143            workspace_without_git(("pnpm-workspace.yaml", "packages:\n  - packages/*\n"));
1144        let stored = store_package(&root, ".pnpm", "react");
1145        let member = root.join("packages/a");
1146        std::os::unix::fs::symlink(&stored, member.join("node_modules/react")).unwrap();
1147        let scope = crate::project_scope_base(&member);
1148        let pkg =
1149            PackageJson::load_in_scope(&scope, &member.join("node_modules/react/package.json"));
1150        assert_eq!(pkg.unwrap().name.as_deref(), Some("react"));
1151
1152        // npm: the package is in the `node_modules` of the workspace root.
1153        let (_dir, root) =
1154            workspace_without_git(("package.json", r#"{"workspaces": ["packages/*"]}"#));
1155        std::fs::create_dir_all(root.join("node_modules/react")).unwrap();
1156        std::fs::write(
1157            root.join("node_modules/react/package.json"),
1158            r#"{"name": "react"}"#,
1159        )
1160        .unwrap();
1161        let scope = crate::project_scope_base(&root.join("packages/a"));
1162        let pkg = PackageJson::load_in_scope(&scope, &root.join("node_modules/react/package.json"));
1163        assert_eq!(pkg.unwrap().name.as_deref(), Some("react"));
1164    }
1165
1166    #[test]
1167    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1168    fn a_node_modules_dir_outside_the_scope_is_refused() {
1169        let dir = tempfile::tempdir().unwrap();
1170        let outer = dunce::canonicalize(dir.path()).unwrap();
1171        let root = outer.join("project");
1172        std::fs::create_dir_all(root.join(".git")).unwrap();
1173        std::fs::create_dir_all(outer.join("node_modules/x")).unwrap();
1174        std::fs::write(
1175            outer.join("node_modules/x/package.json"),
1176            r#"{"name": "x"}"#,
1177        )
1178        .unwrap();
1179        let manifest = outer.join("node_modules/x/package.json");
1180
1181        assert!(PackageJson::load_in_scope(&root, &manifest).is_err());
1182        assert!(PackageJson::load_in_scope(&outer, &manifest).is_ok());
1183    }
1184
1185    #[cfg(unix)]
1186    #[test]
1187    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1188    fn a_node_modules_link_out_of_the_scope_is_refused() {
1189        let dir = tempfile::tempdir().unwrap();
1190        let outer = dunce::canonicalize(dir.path()).unwrap();
1191        let elsewhere = outer.join("elsewhere/node_modules/x");
1192        std::fs::create_dir_all(&elsewhere).unwrap();
1193        std::fs::write(elsewhere.join("package.json"), r#"{"name": "x"}"#).unwrap();
1194        let root = outer.join("project");
1195        std::fs::create_dir_all(root.join(".git")).unwrap();
1196        std::fs::create_dir_all(root.join("node_modules")).unwrap();
1197        std::os::unix::fs::symlink(&elsewhere, root.join("node_modules/x")).unwrap();
1198        let manifest = root.join("node_modules/x/package.json");
1199
1200        assert!(PackageJson::load_in_scope(&root, &manifest).is_err());
1201        assert!(PackageJson::load(&manifest).is_err());
1202        assert!(PackageJson::read_source_in_scope(&root, &manifest).is_err());
1203    }
1204
1205    #[test]
1206    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1207    fn manifest_parse_errors_name_the_position_only() {
1208        let dir = tempfile::tempdir().unwrap();
1209        let path = dir.path().join("package.json");
1210        std::fs::write(&path, "{\n  \"dependencies\": {\"a\": 7654321}\n}").unwrap();
1211        let err = PackageJson::load(&path).unwrap_err();
1212        assert!(!err.contains("7654321"), "{err}");
1213        assert!(err.contains("line 2"), "{err}");
1214    }
1215
1216    #[test]
1217    fn inline_tool_config_keeps_the_last_value_of_a_repeated_key() {
1218        let pkg: PackageJson = serde_json::from_str(
1219            r#"{"name": "app", "jest": {}, "devDependencies": {"jest": "1"}, "jest": {"x": 1}}"#,
1220        )
1221        .unwrap();
1222        assert_eq!(
1223            pkg.inline_tool_config("jest"),
1224            Some(&serde_json::json!({ "x": 1 }))
1225        );
1226        assert_eq!(pkg.name.as_deref(), Some("app"));
1227        assert_eq!(pkg.dev_dependency_names(), vec!["jest"]);
1228    }
1229
1230    #[test]
1231    fn repeated_unknown_key_parses() {
1232        let pkg: PackageJson =
1233            serde_json::from_str(r#"{"name": "app", "custom": 1, "custom": {"y": 2}}"#).unwrap();
1234        assert_eq!(pkg.name.as_deref(), Some("app"));
1235        assert!(pkg.inline_tool_configs.is_empty());
1236    }
1237
1238    #[test]
1239    fn inline_tool_config_keeps_any_value_shape() {
1240        let pkg: PackageJson = serde_json::from_str(
1241            r#"{"prettier": "@acme/prettier-config", "jest": 5, "mocha": null, "tsup": [1, "a"]}"#,
1242        )
1243        .unwrap();
1244        assert_eq!(
1245            pkg.inline_tool_config("prettier"),
1246            Some(&serde_json::json!("@acme/prettier-config"))
1247        );
1248        assert_eq!(pkg.inline_tool_config("jest"), Some(&serde_json::json!(5)));
1249        assert_eq!(
1250            pkg.inline_tool_config("mocha"),
1251            Some(&serde_json::Value::Null)
1252        );
1253        assert_eq!(
1254            pkg.inline_tool_config("tsup"),
1255            Some(&serde_json::json!([1, "a"]))
1256        );
1257        assert_eq!(pkg.inline_tool_config("custom"), None);
1258    }
1259
1260    #[test]
1261    fn package_json_workspace_patterns_array() {
1262        let pkg: PackageJson =
1263            serde_json::from_str(r#"{"workspaces": ["packages/*", "apps/*"]}"#).unwrap();
1264        let patterns = pkg.workspace_patterns();
1265        assert_eq!(patterns, vec!["packages/*", "apps/*"]);
1266    }
1267
1268    #[test]
1269    fn read_source_strips_a_leading_byte_order_mark() {
1270        let dir = tempfile::tempdir().expect("tempdir");
1271        let path = dir.path().join("package.json");
1272        std::fs::write(&path, "\u{FEFF}{\"name\":\"a\"}\n").expect("write");
1273        assert_eq!(
1274            PackageJson::read_source(&path).expect("read"),
1275            "{\"name\":\"a\"}\n"
1276        );
1277    }
1278
1279    #[test]
1280    fn parse_ignores_a_leading_byte_order_mark() {
1281        let pkg = PackageJson::parse("\u{FEFF}{\"dependencies\":{\"react\":\"^18.0.0\"}}")
1282            .expect("a BOM-prefixed manifest is valid");
1283        assert_eq!(pkg.all_dependency_names(), ["react"]);
1284    }
1285
1286    #[test]
1287    fn package_json_workspace_patterns_object() {
1288        let pkg: PackageJson =
1289            serde_json::from_str(r#"{"workspaces": {"packages": ["packages/*"]}}"#).unwrap();
1290        let patterns = pkg.workspace_patterns();
1291        assert_eq!(patterns, vec!["packages/*"]);
1292    }
1293
1294    #[test]
1295    fn package_json_workspace_patterns_none() {
1296        let pkg: PackageJson = serde_json::from_str(r#"{"name": "test"}"#).unwrap();
1297        let patterns = pkg.workspace_patterns();
1298        assert!(patterns.is_empty());
1299    }
1300
1301    #[test]
1302    fn package_json_workspace_patterns_empty_array() {
1303        let pkg: PackageJson = serde_json::from_str(r#"{"workspaces": []}"#).unwrap();
1304        let patterns = pkg.workspace_patterns();
1305        assert!(patterns.is_empty());
1306    }
1307
1308    #[test]
1309    fn package_json_load_valid() {
1310        let temp_dir = std::env::temp_dir().join("fallow-test-pkg-json");
1311        let _ = std::fs::create_dir_all(&temp_dir);
1312        let pkg_path = temp_dir.join("package.json");
1313        std::fs::write(&pkg_path, r#"{"name": "test", "main": "index.js"}"#).unwrap();
1314
1315        let pkg = PackageJson::load(&pkg_path).unwrap();
1316        assert_eq!(pkg.name, Some("test".to_string()));
1317        assert_eq!(pkg.main, Some("index.js".to_string()));
1318
1319        let _ = std::fs::remove_dir_all(&temp_dir);
1320    }
1321
1322    #[test]
1323    fn package_json_private_non_bool_values_are_ignored() {
1324        for raw in [
1325            r#"{"private": "true"}"#,
1326            r#"{"private": 1}"#,
1327            r#"{"private": null}"#,
1328        ] {
1329            let pkg: PackageJson = serde_json::from_str(raw).unwrap();
1330            assert_eq!(pkg.private, None);
1331        }
1332
1333        let pkg: PackageJson = serde_json::from_str(r#"{"private": true}"#).unwrap();
1334        assert_eq!(pkg.private, Some(true));
1335
1336        let pkg: PackageJson = serde_json::from_str(r#"{"private": false}"#).unwrap();
1337        assert_eq!(pkg.private, Some(false));
1338    }
1339
1340    #[test]
1341    fn package_json_files_preserves_string_array_values() {
1342        let pkg: PackageJson =
1343            serde_json::from_str(r#"{"files": ["index.js", "template-*", "dist"]}"#).unwrap();
1344        assert_eq!(pkg.files, vec!["index.js", "template-*", "dist"]);
1345    }
1346
1347    #[test]
1348    fn package_json_files_missing_or_unexpected_shapes_are_ignored() {
1349        let pkg: PackageJson = serde_json::from_str(r#"{"name": "pkg"}"#).unwrap();
1350        assert!(pkg.files.is_empty());
1351
1352        let pkg: PackageJson = serde_json::from_str(r#"{"files": "dist"}"#).unwrap();
1353        assert!(pkg.files.is_empty());
1354
1355        let pkg: PackageJson =
1356            serde_json::from_str(r#"{"files": ["template-*", 42, false, null]}"#).unwrap();
1357        assert_eq!(pkg.files, vec!["template-*"]);
1358    }
1359
1360    #[test]
1361    fn package_json_napi_config_preserves_current_string_fields() {
1362        let pkg: PackageJson = serde_json::from_str(
1363            r#"{
1364                "napi": {
1365                    "binaryName": "srcmap-codec",
1366                    "packageName": "@srcmap/codec",
1367                    "targets": [
1368                        "aarch64-apple-darwin",
1369                        "x86_64-unknown-linux-gnu"
1370                    ]
1371                }
1372            }"#,
1373        )
1374        .unwrap();
1375
1376        let napi = pkg.napi.expect("napi config");
1377        assert_eq!(napi.binary_name.as_deref(), Some("srcmap-codec"));
1378        assert_eq!(napi.package_name.as_deref(), Some("@srcmap/codec"));
1379        assert_eq!(
1380            napi.targets,
1381            vec![
1382                "aarch64-apple-darwin".to_string(),
1383                "x86_64-unknown-linux-gnu".to_string()
1384            ]
1385        );
1386    }
1387
1388    #[test]
1389    fn package_json_napi_config_ignores_unexpected_shapes() {
1390        let pkg: PackageJson = serde_json::from_str(r#"{"napi": "enabled"}"#).unwrap();
1391        assert!(pkg.napi.is_none());
1392
1393        let pkg: PackageJson = serde_json::from_str(
1394            r#"{
1395                "napi": {
1396                    "binaryName": 42,
1397                    "packageName": "",
1398                    "targets": ["x86_64-apple-darwin", false, null]
1399                }
1400            }"#,
1401        )
1402        .unwrap();
1403
1404        let napi = pkg.napi.expect("napi config");
1405        assert!(napi.binary_name.is_none());
1406        assert!(napi.package_name.is_none());
1407        assert_eq!(napi.targets, vec!["x86_64-apple-darwin"]);
1408    }
1409
1410    #[test]
1411    fn package_json_load_missing_file() {
1412        let result = PackageJson::load(std::path::Path::new("/nonexistent/package.json"));
1413        assert!(result.is_err());
1414    }
1415
1416    #[test]
1417    fn package_json_entry_points_combined() {
1418        let pkg: PackageJson = serde_json::from_str(
1419            r#"{
1420            "main": "dist/index.js",
1421            "module": "dist/index.mjs",
1422            "types": "dist/index.d.ts",
1423            "typings": "dist/types.d.ts"
1424        }"#,
1425        )
1426        .unwrap();
1427        let entries = pkg.entry_points();
1428        assert_eq!(entries.len(), 4);
1429        assert!(entries.contains(&"dist/index.js".to_string()));
1430        assert!(entries.contains(&"dist/index.mjs".to_string()));
1431        assert!(entries.contains(&"dist/index.d.ts".to_string()));
1432        assert!(entries.contains(&"dist/types.d.ts".to_string()));
1433    }
1434
1435    #[test]
1436    fn package_json_exports_nested() {
1437        let pkg: PackageJson = serde_json::from_str(
1438            r#"{
1439            "exports": {
1440                ".": {
1441                    "import": "./dist/index.mjs",
1442                    "require": "./dist/index.cjs"
1443                },
1444                "./utils": {
1445                    "import": "./dist/utils.mjs"
1446                }
1447            }
1448        }"#,
1449        )
1450        .unwrap();
1451        let entries = pkg.entry_points();
1452        assert!(entries.contains(&"./dist/index.mjs".to_string()));
1453        assert!(entries.contains(&"./dist/index.cjs".to_string()));
1454        assert!(entries.contains(&"./dist/utils.mjs".to_string()));
1455    }
1456
1457    #[test]
1458    fn package_json_exports_array() {
1459        let pkg: PackageJson = serde_json::from_str(
1460            r#"{
1461            "exports": {
1462                ".": ["./dist/index.mjs", "./dist/index.cjs"]
1463            }
1464        }"#,
1465        )
1466        .unwrap();
1467        let entries = pkg.entry_points();
1468        assert!(entries.contains(&"./dist/index.mjs".to_string()));
1469        assert!(entries.contains(&"./dist/index.cjs".to_string()));
1470    }
1471
1472    #[test]
1473    fn extract_exports_ignores_non_relative() {
1474        let pkg: PackageJson = serde_json::from_str(
1475            r#"{
1476            "exports": {
1477                ".": "not-a-relative-path"
1478            }
1479        }"#,
1480        )
1481        .unwrap();
1482        let entries = pkg.entry_points();
1483        assert!(entries.is_empty());
1484    }
1485
1486    #[test]
1487    fn package_json_source_field() {
1488        let pkg: PackageJson = serde_json::from_str(
1489            r#"{
1490            "main": "dist/index.js",
1491            "source": "src/index.ts"
1492        }"#,
1493        )
1494        .unwrap();
1495        let entries = pkg.entry_points();
1496        assert!(entries.contains(&"src/index.ts".to_string()));
1497        assert!(entries.contains(&"dist/index.js".to_string()));
1498    }
1499
1500    #[test]
1501    fn package_json_browser_field_string() {
1502        let pkg: PackageJson = serde_json::from_str(
1503            r#"{
1504            "browser": "./dist/browser.js"
1505        }"#,
1506        )
1507        .unwrap();
1508        let entries = pkg.entry_points();
1509        assert!(entries.contains(&"./dist/browser.js".to_string()));
1510    }
1511
1512    #[test]
1513    fn package_json_browser_field_object() {
1514        let pkg: PackageJson = serde_json::from_str(
1515            r#"{
1516            "browser": {
1517                "./server.js": "./browser.js",
1518                "module-name": false
1519            }
1520        }"#,
1521        )
1522        .unwrap();
1523        let entries = pkg.entry_points();
1524        assert!(entries.contains(&"./browser.js".to_string()));
1525        assert_eq!(entries.len(), 1);
1526    }
1527
1528    #[test]
1529    fn package_json_exports_string() {
1530        let pkg: PackageJson = serde_json::from_str(r#"{"exports": "./dist/index.js"}"#).unwrap();
1531        let entries = pkg.entry_points();
1532        assert_eq!(entries, vec!["./dist/index.js"]);
1533    }
1534
1535    #[test]
1536    fn package_json_workspace_patterns_object_with_nohoist() {
1537        let pkg: PackageJson = serde_json::from_str(
1538            r#"{
1539            "workspaces": {
1540                "packages": ["packages/*", "apps/*"],
1541                "nohoist": ["**/react-native"]
1542            }
1543        }"#,
1544        )
1545        .unwrap();
1546        let patterns = pkg.workspace_patterns();
1547        assert_eq!(patterns, vec!["packages/*", "apps/*"]);
1548    }
1549
1550    #[test]
1551    fn package_json_missing_optional_fields() {
1552        let pkg: PackageJson = serde_json::from_str(r"{}").unwrap();
1553        assert!(pkg.name.is_none());
1554        assert!(pkg.main.is_none());
1555        assert!(pkg.module.is_none());
1556        assert!(pkg.types.is_none());
1557        assert!(pkg.typings.is_none());
1558        assert!(pkg.source.is_none());
1559        assert!(pkg.browser.is_none());
1560        assert!(pkg.bin.is_none());
1561        assert!(pkg.exports.is_none());
1562        assert!(pkg.dependencies.is_none());
1563        assert!(pkg.dev_dependencies.is_none());
1564        assert!(pkg.peer_dependencies.is_none());
1565        assert!(pkg.peer_dependencies_meta.is_none());
1566        assert!(pkg.optional_dependencies.is_none());
1567        assert!(pkg.scripts.is_none());
1568        assert!(pkg.workspaces.is_none());
1569        assert!(pkg.entry_points().is_empty());
1570        assert!(pkg.workspace_patterns().is_empty());
1571        assert!(pkg.all_dependency_names().is_empty());
1572    }
1573
1574    #[test]
1575    fn package_json_all_dependency_names() {
1576        let pkg: PackageJson = serde_json::from_str(
1577            r#"{
1578            "dependencies": {"react": "^18", "react-dom": "^18"},
1579            "devDependencies": {"typescript": "^5"},
1580            "peerDependencies": {"node": ">=18"},
1581            "optionalDependencies": {"fsevents": "^2"}
1582        }"#,
1583        )
1584        .unwrap();
1585        let deps = pkg.all_dependency_names();
1586        assert_eq!(deps.len(), 5);
1587        assert!(deps.contains(&"react".to_string()));
1588        assert!(deps.contains(&"react-dom".to_string()));
1589        assert!(deps.contains(&"typescript".to_string()));
1590        assert!(deps.contains(&"node".to_string()));
1591        assert!(deps.contains(&"fsevents".to_string()));
1592    }
1593
1594    #[test]
1595    fn package_json_production_dependency_names() {
1596        let pkg: PackageJson = serde_json::from_str(
1597            r#"{
1598            "dependencies": {"react": "^18"},
1599            "devDependencies": {"typescript": "^5"}
1600        }"#,
1601        )
1602        .unwrap();
1603        let prod = pkg.production_dependency_names();
1604        assert_eq!(prod, vec!["react"]);
1605        let dev = pkg.dev_dependency_names();
1606        assert_eq!(dev, vec!["typescript"]);
1607    }
1608
1609    #[test]
1610    fn package_json_bin_field_string() {
1611        let pkg: PackageJson = serde_json::from_str(r#"{"bin": "./cli.js"}"#).unwrap();
1612        let entries = pkg.entry_points();
1613        assert!(entries.contains(&"./cli.js".to_string()));
1614    }
1615
1616    #[test]
1617    fn package_json_bin_field_object() {
1618        let pkg: PackageJson = serde_json::from_str(
1619            r#"{"bin": {"my-cli": "./bin/cli.js", "my-tool": "./bin/tool.js"}}"#,
1620        )
1621        .unwrap();
1622        let entries = pkg.entry_points();
1623        assert!(entries.contains(&"./bin/cli.js".to_string()));
1624        assert!(entries.contains(&"./bin/tool.js".to_string()));
1625    }
1626
1627    #[test]
1628    fn package_json_exports_deeply_nested() {
1629        let pkg: PackageJson = serde_json::from_str(
1630            r#"{
1631            "exports": {
1632                ".": {
1633                    "node": {
1634                        "import": "./dist/node.mjs",
1635                        "require": "./dist/node.cjs"
1636                    },
1637                    "browser": {
1638                        "import": "./dist/browser.mjs"
1639                    }
1640                }
1641            }
1642        }"#,
1643        )
1644        .unwrap();
1645        let entries = pkg.entry_points();
1646        assert_eq!(entries.len(), 3);
1647        assert!(entries.contains(&"./dist/node.mjs".to_string()));
1648        assert!(entries.contains(&"./dist/node.cjs".to_string()));
1649        assert!(entries.contains(&"./dist/browser.mjs".to_string()));
1650    }
1651
1652    #[test]
1653    fn package_json_peer_deps_only() {
1654        let pkg: PackageJson =
1655            serde_json::from_str(r#"{"peerDependencies": {"react": "^18", "react-dom": "^18"}}"#)
1656                .unwrap();
1657        let all = pkg.all_dependency_names();
1658        assert_eq!(all.len(), 2);
1659        assert!(all.contains(&"react".to_string()));
1660        assert!(all.contains(&"react-dom".to_string()));
1661
1662        assert!(pkg.production_dependency_names().is_empty());
1663        assert!(pkg.dev_dependency_names().is_empty());
1664    }
1665
1666    #[test]
1667    fn package_json_peer_dependency_names_include_optional_peers() {
1668        let pkg: PackageJson = serde_json::from_str(
1669            r#"{
1670            "peerDependencies": {"react": "^18", "typescript": "^5"},
1671            "peerDependenciesMeta": {"typescript": {"optional": true}}
1672        }"#,
1673        )
1674        .unwrap();
1675        let mut names = pkg.peer_dependency_names();
1676        names.sort_unstable();
1677        assert_eq!(names, vec!["react", "typescript"]);
1678    }
1679
1680    #[test]
1681    fn package_json_optional_deps_in_all_names() {
1682        let pkg: PackageJson =
1683            serde_json::from_str(r#"{"optionalDependencies": {"fsevents": "^2"}}"#).unwrap();
1684        let all = pkg.all_dependency_names();
1685        assert!(all.contains(&"fsevents".to_string()));
1686    }
1687
1688    #[test]
1689    fn package_json_browser_array_ignored() {
1690        let pkg: PackageJson =
1691            serde_json::from_str(r#"{"browser": ["./a.js", "./b.js"]}"#).unwrap();
1692        let entries = pkg.entry_points();
1693        assert!(
1694            entries.is_empty(),
1695            "array browser field should not produce entries"
1696        );
1697    }
1698
1699    #[test]
1700    fn package_json_browser_object_non_relative_skipped() {
1701        let pkg: PackageJson = serde_json::from_str(
1702            r#"{"browser": {"crypto": false, "./local.js": "./browser-local.js"}}"#,
1703        )
1704        .unwrap();
1705        let entries = pkg.entry_points();
1706        assert_eq!(entries.len(), 1);
1707        assert!(entries.contains(&"./browser-local.js".to_string()));
1708    }
1709
1710    #[test]
1711    fn package_json_exports_null_value() {
1712        let pkg: PackageJson =
1713            serde_json::from_str(r#"{"exports": {".": "./dist/index.js", "./internal": null}}"#)
1714                .unwrap();
1715        let entries = pkg.entry_points();
1716        assert_eq!(entries.len(), 1);
1717        assert!(entries.contains(&"./dist/index.js".to_string()));
1718    }
1719
1720    #[test]
1721    fn package_json_exports_empty_object() {
1722        let pkg: PackageJson = serde_json::from_str(r#"{"exports": {}}"#).unwrap();
1723        let entries = pkg.entry_points();
1724        assert!(entries.is_empty());
1725    }
1726
1727    #[test]
1728    fn package_json_workspace_patterns_string_value_ignored() {
1729        let pkg: PackageJson = serde_json::from_str(r#"{"workspaces": "packages/*"}"#).unwrap();
1730        let patterns = pkg.workspace_patterns();
1731        assert!(patterns.is_empty());
1732    }
1733
1734    #[test]
1735    fn package_json_workspace_patterns_object_missing_packages() {
1736        let pkg: PackageJson =
1737            serde_json::from_str(r#"{"workspaces": {"nohoist": ["**/react-native"]}}"#).unwrap();
1738        let patterns = pkg.workspace_patterns();
1739        assert!(patterns.is_empty());
1740    }
1741
1742    #[test]
1743    fn package_json_load_invalid_json() {
1744        let temp_dir = std::env::temp_dir().join("fallow-test-invalid-pkg-json");
1745        let _ = std::fs::create_dir_all(&temp_dir);
1746        let pkg_path = temp_dir.join("package.json");
1747        std::fs::write(&pkg_path, "{ not valid json }").unwrap();
1748
1749        let result = PackageJson::load(&pkg_path);
1750        assert!(result.is_err());
1751        let err = result.unwrap_err();
1752        assert!(err.contains("Failed to parse"), "got: {err}");
1753
1754        let _ = std::fs::remove_dir_all(&temp_dir);
1755    }
1756
1757    #[test]
1758    fn package_json_bin_object_non_string_values_skipped() {
1759        let pkg: PackageJson =
1760            serde_json::from_str(r#"{"bin": {"cli": "./bin/cli.js", "bad": 42}}"#).unwrap();
1761        let entries = pkg.entry_points();
1762        assert_eq!(entries.len(), 1);
1763        assert!(entries.contains(&"./bin/cli.js".to_string()));
1764    }
1765
1766    #[test]
1767    fn package_json_default() {
1768        let pkg = PackageJson::default();
1769        assert!(pkg.name.is_none());
1770        assert!(pkg.main.is_none());
1771        assert!(pkg.entry_points().is_empty());
1772        assert!(pkg.all_dependency_names().is_empty());
1773        assert!(pkg.workspace_patterns().is_empty());
1774    }
1775
1776    #[test]
1777    fn exports_subdirectories_preact_style() {
1778        let pkg: PackageJson = serde_json::from_str(
1779            r#"{
1780            "exports": {
1781                ".": "./dist/index.js",
1782                "./compat": { "import": "./compat/dist/compat.mjs" },
1783                "./hooks": { "import": "./hooks/dist/hooks.mjs" },
1784                "./debug": { "import": "./debug/dist/debug.mjs" },
1785                "./jsx-runtime": { "import": "./jsx-runtime/dist/jsx.mjs" },
1786                "./package.json": "./package.json"
1787            }
1788        }"#,
1789        )
1790        .unwrap();
1791        let mut dirs = pkg.exports_subdirectories();
1792        dirs.sort();
1793        assert_eq!(dirs, vec!["compat", "debug", "hooks", "jsx-runtime"]);
1794    }
1795
1796    #[test]
1797    fn exports_subdirectories_skips_dist_dirs() {
1798        let pkg: PackageJson = serde_json::from_str(
1799            r#"{
1800            "exports": {
1801                "./dist/index.js": "./dist/index.js",
1802                "./build/bundle.js": "./build/bundle.js",
1803                "./lib/utils": "./lib/utils.js",
1804                "./compat": "./compat/index.js"
1805            }
1806        }"#,
1807        )
1808        .unwrap();
1809        let dirs = pkg.exports_subdirectories();
1810        assert_eq!(dirs, vec!["compat"]);
1811    }
1812
1813    #[test]
1814    fn exports_subdirectories_no_exports() {
1815        let pkg: PackageJson = serde_json::from_str(r#"{"main": "index.js"}"#).unwrap();
1816        assert!(pkg.exports_subdirectories().is_empty());
1817    }
1818
1819    #[test]
1820    fn exports_subdirectories_dot_only() {
1821        let pkg: PackageJson =
1822            serde_json::from_str(r#"{"exports": {".": "./dist/index.js"}}"#).unwrap();
1823        assert!(pkg.exports_subdirectories().is_empty());
1824    }
1825
1826    #[test]
1827    fn npm_aliases_read_the_aliased_package_name() {
1828        let pkg: PackageJson = serde_json::from_str(
1829            r#"{
1830                "dependencies": {"plain": "npm:left-pad@^1.3.0", "range": "^1.0.0"},
1831                "devDependencies": {
1832                    "@typescript/native": "npm:typescript@~7.0.2",
1833                    "typescript": "npm:@typescript/typescript6@^6.0.2",
1834                    "bare": "npm:eslint",
1835                    "same": "npm:same@1.0.0",
1836                    "path": "npm:./local",
1837                    "bad-scope": "npm:@scope@1.0.0",
1838                    "workspace": "workspace:@scope/core@*"
1839                }
1840            }"#,
1841        )
1842        .unwrap();
1843        assert_eq!(
1844            pkg.npm_aliases(),
1845            [
1846                ("@typescript/native", "typescript"),
1847                ("bare", "eslint"),
1848                ("plain", "left-pad"),
1849                ("typescript", "@typescript/typescript6"),
1850            ]
1851            .map(|(alias, target)| (alias.to_string(), target.to_string()))
1852        );
1853    }
1854
1855    #[test]
1856    fn npm_aliases_with_catalogs_resolves_catalog_references() {
1857        let catalogs = super::super::pnpm_catalog::parse_pnpm_catalog_data(
1858            "catalog:\n  \"@typescript/native\": npm:typescript@~7.0.2\n  react: ^18.2.0\ncatalogs:\n  tools:\n    vite-next: npm:vite@^7.0.0\n",
1859        )
1860        .unwrap();
1861        let pkg: PackageJson = serde_json::from_str(
1862            r#"{
1863                "devDependencies": {
1864                    "@typescript/native": "catalog:",
1865                    "react": "catalog:default",
1866                    "vite-next": "catalog:tools",
1867                    "missing": "catalog:tools",
1868                    "inline": "npm:left-pad@1"
1869                }
1870            }"#,
1871        )
1872        .unwrap();
1873        assert_eq!(
1874            pkg.npm_aliases_with_catalogs(Some(&catalogs)),
1875            [
1876                ("@typescript/native", "typescript"),
1877                ("inline", "left-pad"),
1878                ("vite-next", "vite"),
1879            ]
1880            .map(|(alias, target)| (alias.to_string(), target.to_string()))
1881        );
1882        assert_eq!(
1883            pkg.npm_aliases(),
1884            [("inline".to_string(), "left-pad".to_string())]
1885        );
1886    }
1887
1888    #[test]
1889    fn workspace_alias_target_reads_the_aliased_package_name() {
1890        let pkg: PackageJson = serde_json::from_str(
1891            r#"{
1892                "dependencies": {
1893                    "vite": "workspace:@scope/core@*",
1894                    "plain": "workspace:other@^1.0.0",
1895                    "range": "workspace:*",
1896                    "caret": "workspace:^1.0.0",
1897                    "path": "workspace:../core",
1898                    "npm": "npm:@scope/core@1.0.0",
1899                    "bad-scope": "workspace:@scope@1.0.0"
1900                },
1901                "devDependencies": {"tool": "workspace:@scope/tool@workspace:*"}
1902            }"#,
1903        )
1904        .unwrap();
1905        assert_eq!(pkg.workspace_alias_target("vite"), Some("@scope/core"));
1906        assert_eq!(pkg.workspace_alias_target("plain"), Some("other"));
1907        assert_eq!(pkg.workspace_alias_target("tool"), Some("@scope/tool"));
1908        for name in ["range", "caret", "path", "npm", "bad-scope", "missing"] {
1909            assert_eq!(pkg.workspace_alias_target(name), None, "{name}");
1910        }
1911    }
1912}