npm-utils 0.6.1

Pure-Rust npm toolkit: resolve, download, install/ci, add/remove/upgrade, search, SBOM (CycloneDX/SPDX), and vulnerability audit (npm + OSV) — no Node.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
//! The `npm-utils` / `cargo npm-utils` command-line tool (feature `cli`).
//!
//! Pure-Rust npm verbs over the crate's primitives — it mirrors npm's vocabulary for the subset it
//! supports and is deliberately **not** a full npm drop-in. Each verb lives in its own submodule;
//! the shared helpers they lean on (manifest read/write, the lock+install `sync` that `add` and
//! `upgrade` both run, install reporting) live in the `common` submodule, and the stderr progress
//! rendering behind the global `--progress` (with `-q`/`--quiet` as its `none` shorthand) lives
//! in `progress`.
//!
//! - `install` — record any given package sources (`name` / `name@range` / `name=range`) in
//!   `package.json`, then resolve its `dependencies`, write `package-lock.json`, and install
//!   `node_modules/` (= `npm install [pkg…]`); `--lockfile-only` / `--no-lockfile` toggle each half.
//! - `ci` — install the exact tree a `package-lock.json` pins (= `npm ci`).
//! - `add` — resolve package(s), record them in `package.json`, write `package-lock.json`, install.
//! - `remove` — drop package(s) from `package.json`, refresh the lock, reinstall (= `npm remove`).
//! - `init` — scaffold a `package.json` (= `npm init -y`).
//! - `upgrade` — re-resolve within ranges, refresh the lock, install (= `npm update`).
//! - `resolve` / `download` — thin registry probes (print a resolution / fetch a tarball).
//! - `search` — query the registry and print matching packages (= `npm search`).
//!
//! The library does the heavy lifting ([`crate::registry`], [`crate::install`], [`crate::project`],
//! and the [`crate::package_json`] manifest/lock writers); this module is the argument parsing + the
//! file IO those pure transforms leave to the caller. Both bins (`npm-utils`, `cargo-npm-utils`) are
//! thin shells over [`main_with`].

use std::ffi::OsString;
use std::path::PathBuf;
use std::process::ExitCode;

use clap::{Args, Parser, Subcommand};

use crate::registry::PackumentDetail;

mod add;
mod audit;
mod ci;
mod common;
mod download;
mod init;
mod install;
mod progress;
mod remove;
mod resolve;
mod sbom;
mod search;
mod source;
mod upgrade;

/// This module's ubiquitous fallible return — `()` by default, over the crate [`crate::Error`].
pub(crate) type Res<T = ()> = crate::Result<T>;

#[derive(Parser)]
#[command(
    name = "npm-utils",
    version,
    about = "Pure-Rust npm registry tools: install · ci · add · remove · init · upgrade · search · sbom · audit"
)]
struct Cli {
    /// Per-fetch timeout in seconds (default 120) — caps each registry/tarball request, not the whole run
    #[arg(
        long,
        global = true,
        value_name = "SECS",
        conflicts_with = "no_timeout"
    )]
    timeout: Option<u64>,
    /// Disable download timeouts entirely (no per-fetch or connect bound)
    #[arg(long, global = true)]
    no_timeout: bool,
    #[command(flatten)]
    display: progress::DisplayOptions,
    #[command(subcommand)]
    command: Command,
}

/// The shared `--skip-license` / `--no-skip-license` knob for the lockfile-writing verbs
/// (`install`, `add`, `remove`, `upgrade`). The default skips license — the faster abbreviated
/// packument — and `npm-utils sbom` recovers license from each package's package.json;
/// `--no-skip-license` records it in the lockfile via the full packument.
#[derive(Args)]
struct LicenseOpts {
    /// Record each package's license in package-lock.json (fetches the full packument)
    #[arg(long, conflicts_with = "skip_license")]
    no_skip_license: bool,
    /// Skip per-package license in package-lock.json for faster resolution (abbreviated packument); the default
    #[arg(long)]
    skip_license: bool,
}

impl LicenseOpts {
    /// Which packument detail the lockfile writer should use. The default (and explicit
    /// `--skip-license`) uses the abbreviated packument; `--no-skip-license` records license via the
    /// full one.
    fn detail(&self) -> PackumentDetail {
        if self.no_skip_license && !self.skip_license {
            PackumentDetail::Full
        } else {
            PackumentDetail::Abbreviated
        }
    }
}

#[derive(Subcommand)]
enum Command {
    /// Resolve dependencies, write package-lock.json, install node_modules/ (npm install)
    Install {
        /// Packages to add first, as name, name@range, or name=range (e.g. ms, ms=^2); with no SOURCES, install the project's existing dependencies
        sources: Vec<String>,
        /// Project directory containing package.json
        #[arg(long, default_value = ".")]
        dir: PathBuf,
        /// Write package-lock.json but don't install node_modules/ (npm --package-lock-only, pnpm --lockfile-only)
        #[arg(
            long,
            visible_alias = "package-lock-only",
            conflicts_with = "no_lockfile"
        )]
        lockfile_only: bool,
        /// Install node_modules/ without writing package-lock.json (yarn --no-lockfile, npm --no-package-lock)
        #[arg(long, visible_alias = "no-package-lock")]
        no_lockfile: bool,
        #[command(flatten)]
        license: LicenseOpts,
    },
    /// Install the exact tree package-lock.json pins (npm ci)
    Ci {
        /// Project directory containing package-lock.json
        #[arg(default_value = ".")]
        dir: PathBuf,
    },
    /// Add packages to package.json, write the lock, and install (npm add)
    Add {
        /// Packages as name, name@range, or name=range (e.g. lit, lit@^3, lit=^3, @lit/context@^1)
        #[arg(required = true)]
        packages: Vec<String>,
        /// Project directory
        #[arg(long, default_value = ".")]
        dir: PathBuf,
        #[command(flatten)]
        license: LicenseOpts,
    },
    /// Remove packages from package.json, refresh the lock, reinstall (npm remove)
    Remove {
        /// Packages to remove (names)
        #[arg(required = true)]
        packages: Vec<String>,
        /// Project directory
        #[arg(long, default_value = ".")]
        dir: PathBuf,
        #[command(flatten)]
        license: LicenseOpts,
    },
    /// Create a package.json (npm init -y)
    Init {
        /// Project directory
        #[arg(long, default_value = ".")]
        dir: PathBuf,
        /// Package name (defaults to the directory name)
        #[arg(long)]
        name: Option<String>,
    },
    /// Re-resolve within ranges, refresh the lock, and install (npm update)
    Upgrade {
        /// Packages to upgrade; empty means all dependencies
        packages: Vec<String>,
        /// Project directory
        #[arg(long, default_value = ".")]
        dir: PathBuf,
        #[command(flatten)]
        license: LicenseOpts,
    },
    /// Print the newest version matching a range (version, tarball, integrity)
    Resolve {
        /// Package name
        name: String,
        /// Semver range (default: any)
        #[arg(default_value = "*")]
        range: String,
    },
    /// Download a package tarball — resolve and fetch, no install
    Download {
        /// Package name
        name: String,
        /// Semver range (default: any)
        #[arg(default_value = "*")]
        range: String,
        /// Write the .tgz here (default: <name>-<version>.tgz in the current dir)
        #[arg(long)]
        out: Option<PathBuf>,
    },
    /// Search the registry for packages (npm search)
    Search {
        /// Search text (package name or keywords)
        #[arg(required = true)]
        query: Vec<String>,
        /// Maximum number of results (1–250)
        #[arg(long, default_value_t = 20)]
        limit: usize,
    },
    /// Bill of materials from package-lock.json: license summary, CycloneDX, or SPDX
    Sbom {
        /// Project directory containing package-lock.json
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// Output format
        #[arg(long, default_value = "summary")]
        format: sbom::Format,
        /// Name for the SBOM's root component / document (default: the directory name)
        #[arg(long)]
        name: Option<String>,
        /// Where to read each package's license: auto (lockfile, else the installed package.json), lockfile, or package
        #[arg(long, default_value = "auto")]
        license_source: sbom::LicenseSource,
    },
    /// Check packages against vulnerability advisories (npm audit)
    Audit {
        /// What to audit: a project directory (its package-lock.json, else its package.json), a package.json / package-lock.json path, or a spec name=range (e.g. lit=^3) — manifests and specs resolve in memory, no lock is written
        #[arg(default_value = ".")]
        source: String,
        /// Minimum severity that makes the command exit non-zero (default: low — any vuln fails)
        #[arg(long, value_enum, default_value = "low")]
        audit_level: audit::AuditLevel,
        /// Output format
        #[arg(long, value_enum, default_value = "summary")]
        format: audit::Format,
        /// Advisory sources to query, comma-separated (default: npm,osv)
        #[arg(long, value_enum, value_delimiter = ',')]
        sources: Option<Vec<audit::SourceKind>>,
        /// Registry base URL for the npm advisory source and for resolving a package.json / name=range source (default: https://registry.npmjs.org)
        #[arg(long)]
        registry: Option<String>,
        /// Exit 0 even when the audit is incomplete — every advisory source failed, or some dependencies could not be audited (opt into fail-open)
        #[arg(long)]
        allow_incomplete: bool,
    },
}

/// Parse `argv` and dispatch to the verb's submodule. `argv` is taken explicitly (not
/// `std::env::args_os()`) so the `cargo-npm-utils` shim can strip the re-passed subcommand name
/// before handing off.
pub fn run(argv: impl IntoIterator<Item = OsString>) -> Res {
    let cli = Cli::parse_from(argv);
    // Apply the download-timeout flags before any fetch happens.
    crate::download::set_timeouts(crate::download::Timeouts::from_cli(
        cli.timeout,
        cli.no_timeout,
    ));
    // Build the renderer once and reroute the library's warnings through it before any work
    // begins — a live region must never be torn by a raw eprintln (even from worker threads).
    let progress = progress::Progress::new(&cli.display);
    progress.install_warn_sink();
    match cli.command {
        Command::Install {
            sources,
            dir,
            lockfile_only,
            no_lockfile,
            license,
        } => install::run(
            &sources,
            &dir,
            lockfile_only,
            no_lockfile,
            license.detail(),
            &progress,
        ),
        Command::Ci { dir } => ci::run(&dir, &progress),
        Command::Add {
            packages,
            dir,
            license,
        } => add::run(&packages, &dir, license.detail(), &progress),
        Command::Remove {
            packages,
            dir,
            license,
        } => remove::run(&packages, &dir, license.detail(), &progress),
        Command::Init { dir, name } => init::run(&dir, name.as_deref()),
        Command::Upgrade {
            packages,
            dir,
            license,
        } => upgrade::run(&packages, &dir, license.detail(), &progress),
        Command::Resolve { name, range } => resolve::run(&name, &range),
        Command::Download { name, range, out } => {
            download::run(&name, &range, out.as_deref(), &progress)
        }
        Command::Search { query, limit } => search::run(&query.join(" "), limit),
        Command::Sbom {
            dir,
            format,
            name,
            license_source,
        } => sbom::run(&dir, format, name.as_deref(), license_source),
        Command::Audit {
            source,
            audit_level,
            format,
            sources,
            registry,
            allow_incomplete,
        } => audit::run(
            &source,
            audit_level,
            format,
            sources.as_deref(),
            registry.as_deref(),
            allow_incomplete,
            &progress,
        ),
    }
}

/// Bin entry point: run, then map an error to a tidy message + nonzero exit (instead of the
/// `Result`-returning-`main` `Error: …` Debug dump).
pub fn main_with(argv: impl IntoIterator<Item = OsString>) -> ExitCode {
    match run(argv) {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("npm-utils: {e}");
            ExitCode::FAILURE
        }
    }
}

/// `cargo-npm-utils` entry point: cargo invokes the bin as `cargo-npm-utils npm-utils <verb> …`,
/// re-passing the subcommand name as `argv[1]`; strip it so clap sees the real verb.
pub fn run_as_cargo_subcommand(argv: impl IntoIterator<Item = OsString>) -> ExitCode {
    main_with(strip_cargo_prefix(argv.into_iter().collect()))
}

/// Drop a leading `npm-utils` token at `argv[1]` (cargo's re-passed subcommand name). A no-op when
/// the bin is run directly (`cargo-npm-utils install` → `argv[1]` is the verb, left alone).
fn strip_cargo_prefix(mut args: Vec<OsString>) -> Vec<OsString> {
    if args.get(1).is_some_and(|a| a == "npm-utils") {
        args.remove(1);
    }
    args
}

#[cfg(test)]
mod tests {
    use super::*;

    fn osv(args: &[&str]) -> Vec<OsString> {
        args.iter().map(OsString::from).collect()
    }

    #[test]
    fn strip_cargo_prefix_drops_the_repassed_subcommand_name() {
        // `cargo npm-utils add lit` → cargo execs us with the subcommand name re-passed.
        assert_eq!(
            strip_cargo_prefix(osv(&["cargo-npm-utils", "npm-utils", "add", "lit"])),
            osv(&["cargo-npm-utils", "add", "lit"])
        );
        // Run directly: argv[1] is the real verb, untouched.
        assert_eq!(
            strip_cargo_prefix(osv(&["cargo-npm-utils", "install"])),
            osv(&["cargo-npm-utils", "install"])
        );
        // Degenerate argv (no args) is left as-is.
        assert_eq!(
            strip_cargo_prefix(osv(&["cargo-npm-utils"])),
            osv(&["cargo-npm-utils"])
        );
    }

    #[test]
    fn cli_parses_the_verb_set() {
        // A smoke test that the clap grammar accepts each verb (no dispatch/network).
        for argv in [
            osv(&["npm-utils", "install"]),
            osv(&["npm-utils", "install", "--dir", "web", "--lockfile-only"]),
            osv(&["npm-utils", "install", "ms=^2", "lit", "--dir", "/tmp/x"]),
            osv(&["npm-utils", "install", "--no-lockfile"]),
            osv(&["npm-utils", "ci", "/tmp/x"]),
            osv(&["npm-utils", "add", "lit@^3", "--dir", "/tmp/x"]),
            osv(&["npm-utils", "remove", "lit", "--dir", "/tmp/x"]),
            osv(&["npm-utils", "init", "--name", "demo"]),
            osv(&["npm-utils", "upgrade"]),
            osv(&["npm-utils", "resolve", "lit", "^3"]),
            osv(&["npm-utils", "download", "ms", "--out", "/tmp/ms.tgz"]),
            osv(&["npm-utils", "search", "lodash"]),
            osv(&["npm-utils", "search", "react", "router", "--limit", "5"]),
            osv(&["npm-utils", "sbom", "/tmp/x", "--format", "cyclonedx"]),
            osv(&["npm-utils", "sbom", "--format", "spdx", "--name", "demo"]),
            osv(&["npm-utils", "audit", "/tmp/x"]),
            osv(&["npm-utils", "audit", "lit=^3", "--audit-level", "high"]),
            osv(&["npm-utils", "audit", "/tmp/x/package.json"]),
            osv(&[
                "npm-utils",
                "audit",
                "--audit-level",
                "high",
                "--format",
                "json",
            ]),
            osv(&[
                "npm-utils",
                "audit",
                "--sources",
                "npm,osv",
                "--registry",
                "https://r.example",
            ]),
        ] {
            assert!(Cli::try_parse_from(argv).is_ok());
        }
        // `audit` rejects an unknown severity level and an unknown source.
        assert!(
            Cli::try_parse_from(osv(&["npm-utils", "audit", "--audit-level", "fatal"])).is_err()
        );
        assert!(Cli::try_parse_from(osv(&["npm-utils", "audit", "--sources", "snyk"])).is_err());
        // `add`, `remove`, and `search` each require at least one argument.
        assert!(Cli::try_parse_from(osv(&["npm-utils", "add"])).is_err());
        assert!(Cli::try_parse_from(osv(&["npm-utils", "remove"])).is_err());
        assert!(Cli::try_parse_from(osv(&["npm-utils", "search"])).is_err());
        // `install` can't both write only the lock and skip the lock.
        assert!(Cli::try_parse_from(osv(&[
            "npm-utils",
            "install",
            "--lockfile-only",
            "--no-lockfile"
        ]))
        .is_err());
    }

    #[test]
    fn cli_accepts_global_timeout_flags() {
        // `--timeout <secs>` and `--no-timeout` are global: accepted before or after the verb.
        assert!(Cli::try_parse_from(osv(&["npm-utils", "--timeout", "5", "install"])).is_ok());
        assert!(Cli::try_parse_from(osv(&["npm-utils", "install", "--no-timeout"])).is_ok());
        assert!(Cli::try_parse_from(osv(&["npm-utils", "--no-timeout", "ci", "/tmp/x"])).is_ok());
        // The two flags conflict, and `--timeout` requires a numeric value.
        assert!(Cli::try_parse_from(osv(&[
            "npm-utils",
            "--timeout",
            "5",
            "--no-timeout",
            "install"
        ]))
        .is_err());
        assert!(Cli::try_parse_from(osv(&["npm-utils", "--timeout", "soon", "install"])).is_err());
    }

    #[test]
    fn cli_accepts_global_quiet_flag() {
        // `-q`/`--quiet` is global: accepted before or after the verb, on any verb.
        assert!(Cli::try_parse_from(osv(&["npm-utils", "-q", "audit", "/tmp/x"])).is_ok());
        assert!(Cli::try_parse_from(osv(&["npm-utils", "audit", "lit=^3", "--quiet"])).is_ok());
        assert!(Cli::try_parse_from(osv(&["npm-utils", "install", "-q"])).is_ok());
        // The flag actually lands, and defaults to off.
        let quiet = |args: &[&str]| Cli::try_parse_from(osv(args)).unwrap().display.quiet;
        assert!(quiet(&["npm-utils", "-q", "audit"]));
        assert!(!quiet(&["npm-utils", "audit"]));
    }

    #[test]
    fn cli_accepts_global_progress_flag() {
        use progress::ProgressMode;
        let mode = |args: &[&str]| Cli::try_parse_from(osv(args)).unwrap().display.progress;
        // Global: accepted before or after the verb; defaults to auto.
        assert_eq!(mode(&["npm-utils", "audit"]), ProgressMode::Auto);
        assert_eq!(
            mode(&["npm-utils", "--progress", "verbose", "ci", "/tmp/x"]),
            ProgressMode::Verbose
        );
        assert_eq!(
            mode(&["npm-utils", "install", "--progress=none"]),
            ProgressMode::Off
        );
        // The user-facing aliases: 1/yes/true → on, 0/off/false/no → none.
        for on in ["on", "1", "yes", "true"] {
            assert_eq!(
                mode(&["npm-utils", "audit", "--progress", on]),
                ProgressMode::On
            );
        }
        for off in ["none", "0", "off", "false", "no"] {
            assert_eq!(
                mode(&["npm-utils", "audit", "--progress", off]),
                ProgressMode::Off
            );
        }
        // An unknown mode is a parse error.
        assert!(Cli::try_parse_from(osv(&["npm-utils", "audit", "--progress", "loud"])).is_err());
        // `-q` alone is fine — a clap default value never participates in a conflict (the
        // validator only considers explicitly provided args). An explicit --progress on the
        // same side of the verb as -q errors; split across the verb boundary, clap's
        // global-arg propagation doesn't connect the two and quiet wins in the resolver.
        assert!(Cli::try_parse_from(osv(&["npm-utils", "-q", "audit"])).is_ok());
        assert!(Cli::try_parse_from(osv(&["npm-utils", "-q", "--progress=on", "audit"])).is_err());
        assert!(Cli::try_parse_from(osv(&["npm-utils", "audit", "-q", "--progress=on"])).is_err());
        assert!(Cli::try_parse_from(osv(&["npm-utils", "--progress=none", "audit", "-q"])).is_ok());
    }

    #[test]
    fn cli_accepts_license_flags() {
        // --skip-license / --no-skip-license are accepted on the lockfile-writing verbs.
        assert!(Cli::try_parse_from(osv(&["npm-utils", "install", "--skip-license"])).is_ok());
        assert!(
            Cli::try_parse_from(osv(&["npm-utils", "add", "lit", "--no-skip-license"])).is_ok()
        );
        assert!(Cli::try_parse_from(osv(&["npm-utils", "upgrade", "--skip-license"])).is_ok());
        // The two conflict.
        assert!(Cli::try_parse_from(osv(&[
            "npm-utils",
            "install",
            "--skip-license",
            "--no-skip-license"
        ]))
        .is_err());
    }

    #[test]
    fn license_opts_map_to_packument_detail() {
        let detail = |skip: bool, no_skip: bool| {
            LicenseOpts {
                skip_license: skip,
                no_skip_license: no_skip,
            }
            .detail()
        };
        // The default skips license (abbreviated); --no-skip-license records it (full packument).
        assert_eq!(detail(false, false), PackumentDetail::Abbreviated);
        assert_eq!(detail(false, true), PackumentDetail::Full);
        assert_eq!(detail(true, false), PackumentDetail::Abbreviated);
    }
}