Repository navigation
Expand file tree
/
Copy pathcli.js
More file actions
837 lines (791 loc) · 33.7 KB
/
Copy pathcli.js
File metadata and controls
837 lines (791 loc) · 33.7 KB
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
#!/usr/bin/env node
// depsift — "should i install <pkg>?"
// Resolves a package's (or your whole project's) dependency tree straight from
// the npm registry — no install, no node_modules — and prints a scorecard:
// how many packages you'd really add, how much disk, how many maintainers you'd
// be trusting, how stale they are, and the literal install scripts that run
// code on your machine. Zero runtime dependencies.
import { readFileSync, existsSync, realpathSync } from "node:fs";
import { resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
const REGISTRY = process.env.DEPSIFT_REGISTRY || "https://registry.npmjs.org";
// Full packument — carries maintainers, publish times, and scripts, which the
// abbreviated form drops. One request per unique package covers every metric.
const ACCEPT = "application/json";
const CONCURRENCY = 12;
const YEAR_MS = 365 * 24 * 60 * 60 * 1000;
const STALE_MS = 2 * YEAR_MS; // last publish older than this = stale
// ===================== semver (zero-dep, npm-accurate subset) =====================
function svParse(v) {
if (typeof v !== "string") return null;
const m = v
.trim()
.replace(/^[v=]+/, "")
.match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);
if (!m) return null;
return { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ? m[4].split(".") : [] };
}
function cmpPre(a, b) {
if (!a.length && !b.length) return 0;
if (!a.length) return 1;
if (!b.length) return -1;
for (let i = 0; i < Math.max(a.length, b.length); i++) {
const x = a[i], y = b[i];
if (x === undefined) return -1;
if (y === undefined) return 1;
const nx = /^\d+$/.test(x), ny = /^\d+$/.test(y);
if (nx && ny) { if (+x !== +y) return +x < +y ? -1 : 1; }
else if (nx !== ny) return nx ? -1 : 1;
else if (x !== y) return x < y ? -1 : 1;
}
return 0;
}
function svCmp(a, b) {
for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] < b[k] ? -1 : 1;
return cmpPre(a.pre, b.pre);
}
function comparators(part) {
part = part.trim();
if (part === "" || part === "*" || part === "x" || part === "X")
return [{ op: ">=", v: svParse("0.0.0") }];
const out = [];
for (const t of part.split(/\s+/)) {
const opm = t.match(/^(>=|<=|>|<|=|\^|~)?\s*(.*)$/);
let op = opm[1] || "=";
let ver = opm[2].replace(/^[v=]+/, "");
const xm = ver.match(/^(\d+|\*|x|X)?(?:\.(\d+|\*|x|X))?(?:\.(\d+|\*|x|X))?(?:-([0-9A-Za-z.-]+))?$/) || [];
const isX = (s) => s === undefined || s === "" || s === "*" || s === "x" || s === "X";
if (op === "^" || op === "~") {
const major = +xm[1] || 0;
const minor = isX(xm[2]) ? 0 : +xm[2];
const patch = isX(xm[3]) ? 0 : +xm[3];
const pre = xm[4] ? xm[4].split(".") : [];
const lower = { major, minor, patch, pre };
let upper;
if (op === "~") {
upper = isX(xm[2])
? { major: major + 1, minor: 0, patch: 0, pre: [] }
: { major, minor: minor + 1, patch: 0, pre: [] };
} else if (major > 0 || isX(xm[2])) upper = { major: major + 1, minor: 0, patch: 0, pre: [] };
else if (minor > 0 || isX(xm[3])) upper = { major: 0, minor: minor + 1, patch: 0, pre: [] };
else upper = { major: 0, minor: 0, patch: patch + 1, pre: [] };
out.push({ op: ">=", v: lower }, { op: "<", v: upper });
continue;
}
if (isX(xm[1])) { out.push({ op: ">=", v: svParse("0.0.0") }); continue; }
if (isX(xm[2])) {
const M = +xm[1];
out.push({ op: ">=", v: { major: M, minor: 0, patch: 0, pre: [] } });
out.push({ op: "<", v: { major: M + 1, minor: 0, patch: 0, pre: [] } });
continue;
}
if (isX(xm[3])) {
const M = +xm[1], mn = +xm[2];
out.push({ op: ">=", v: { major: M, minor: mn, patch: 0, pre: [] } });
out.push({ op: "<", v: { major: M, minor: mn + 1, patch: 0, pre: [] } });
continue;
}
const pv = svParse(ver);
if (!pv) return null;
out.push({ op, v: pv });
}
return out;
}
function satisfiesPart(version, part) {
const hy = part.match(/^\s*(.+?)\s+-\s+(.+?)\s*$/);
let comps;
if (hy) {
const loC = comparators(hy[1]);
const lo = svParse(hy[1]) || (loC && loC[0].v);
const hiC = comparators(hy[2]);
const hi = svParse(hy[2]) || (hiC && hiC[hiC.length - 1].v);
if (!lo || !hi) return false;
comps = [{ op: ">=", v: lo }, { op: "<=", v: hi }];
} else comps = comparators(part);
if (!comps) return false;
if (version.pre.length) {
const allow = comps.some(
(c) => c.v.pre.length && c.v.major === version.major && c.v.minor === version.minor && c.v.patch === version.patch
);
if (!allow) return false;
}
for (const c of comps) {
const r = svCmp(version, c.v);
if (c.op === ">=" && !(r >= 0)) return false;
if (c.op === ">" && !(r > 0)) return false;
if (c.op === "<=" && !(r <= 0)) return false;
if (c.op === "<" && !(r < 0)) return false;
if (c.op === "=" && r !== 0) return false;
}
return true;
}
function satisfies(version, range) {
const v = typeof version === "string" ? svParse(version) : version;
if (!v) return false;
if (range == null || range === "" || range === "*" || range === "latest") return v.pre.length === 0;
return String(range).split("||").some((part) => satisfiesPart(v, part));
}
function maxSatisfying(versions, range) {
let best = null, bestP = null;
for (const ver of versions) {
const p = svParse(ver);
if (!p || !satisfies(p, range)) continue;
if (!bestP || svCmp(p, bestP) > 0) { best = ver; bestP = p; }
}
return best;
}
// ===================== tiny ANSI (no deps) =====================
const useColor = process.stdout.isTTY && !process.env.NO_COLOR && process.env.TERM !== "dumb";
const c = (code) => (s) => (useColor ? `\x1b[${code}m${s}\x1b[0m` : `${s}`);
const bold = c("1"), dim = c("2"), red = c("31"), green = c("32"),
yellow = c("33"), cyan = c("36"), gray = c("90");
// ===================== helpers =====================
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function parseArg(spec) {
let name = spec, version = "";
const at = spec.lastIndexOf("@");
if (at > 0) { name = spec.slice(0, at); version = spec.slice(at + 1); }
return { name, version };
}
function bytes(n) {
if (!n) return "?";
const u = ["B", "KB", "MB", "GB"];
let i = 0;
while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
return `${n.toFixed(n < 10 && i > 0 ? 1 : 0)} ${u[i]}`;
}
function age(iso) {
if (!iso) return "?";
const ms = Date.now() - Date.parse(iso);
if (Number.isNaN(ms)) return "?";
const y = ms / YEAR_MS;
if (y >= 1) return `${y.toFixed(y < 10 ? 1 : 0)}y`;
const mo = ms / (30 * 24 * 60 * 60 * 1000);
if (mo >= 1) return `${Math.round(mo)}mo`;
const w = ms / (7 * 24 * 60 * 60 * 1000);
if (w >= 1) return `${Math.round(w)}w`;
return "days";
}
const INSTALL_PHASES = ["preinstall", "install", "postinstall"];
function installCommands(meta) {
const s = meta.scripts || {};
return INSTALL_PHASES.filter((p) => s[p]).map((p) => ({ phase: p, cmd: s[p] }));
}
// Heuristic scan of an install command for behavior you rarely want running
// unattended on your machine. Conservative patterns, labelled by kind.
const DANGER = [
[/\b(curl|wget|fetch)\b|https?:\/\//i, "network"],
[/\|\s*(sh|bash|zsh|node|python)\b/i, "pipe-to-shell"],
[/\b(base64|atob|xxd)\b/i, "obfuscation"],
[/\beval\b|node\s+-e\b|new Function/i, "dynamic-exec"],
[/process\.env|printenv|[$]\{?[A-Z_]+\}?.*(curl|http|nc )/i, "reads-env"],
[/\brm\s+-rf\b|>\s*\/dev\/|mkfifo|nc\s+-/i, "destructive/recon"],
];
function scanDanger(cmd) {
const hits = [];
for (const [re, label] of DANGER) if (re.test(cmd)) hits.push(label);
return hits;
}
async function fetchPackument(name, attempt = 0) {
const url = `${REGISTRY}/${name.replace("/", "%2f")}`;
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), 15000);
try {
const res = await fetch(url, { headers: { accept: ACCEPT }, signal: ac.signal });
if (res.status === 404) throw new Error(`package not found: ${name}`);
if ((res.status === 429 || res.status >= 500) && attempt < 3) {
await sleep(300 * (attempt + 1) * (attempt + 1));
return fetchPackument(name, attempt + 1);
}
if (!res.ok) throw new Error(`registry ${res.status} for ${name}`);
return await res.json();
} catch (e) {
if ((e.name === "AbortError" || e.code === "ECONNRESET") && attempt < 3) {
await sleep(300 * (attempt + 1));
return fetchPackument(name, attempt + 1);
}
throw e;
} finally {
clearTimeout(timer);
}
}
// Query npm's free bulk advisory endpoint (the same data `npm audit` uses — no
// Snyk, no account, no AI) and attach matching CVEs to each resolved record.
// Authoritative and deterministic: real vulnerable-version ranges, not guesses.
async function fetchAdvisories(records) {
const payload = {};
for (const r of records) (payload[r.name] ||= new Set()).add(r.version);
for (const k of Object.keys(payload)) payload[k] = [...payload[k]];
let data = {};
try {
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), 15000);
const res = await fetch(`${REGISTRY}/-/npm/v1/security/advisories/bulk`, {
method: "POST",
headers: { "content-type": "application/json", accept: "application/json" },
body: JSON.stringify(payload),
signal: ac.signal,
});
clearTimeout(timer);
if (res.ok) data = await res.json();
} catch {
/* advisory lookup is best-effort; the card still renders without it */
}
for (const r of records) {
const advs = data[r.name] || [];
r.vulns = advs
.filter((a) => satisfies(r.version, a.vulnerable_versions))
.map((a) => ({ severity: a.severity, title: a.title, url: a.url }));
}
return Object.keys(data).length > 0;
}
// pick the concrete version a spec resolves to, the way npm would: exact match,
// dist-tag, or highest version satisfying a range. Non-semver specs
// (git/url/workspace/file) fall back to latest.
function resolveSpec(pkg, spec) {
const versions = Object.keys(pkg.versions || {});
const tags = pkg["dist-tags"] || {};
if (!spec || spec === "latest" || spec === "*")
return tags.latest || maxSatisfying(versions, "*") || versions[versions.length - 1];
if (pkg.versions && pkg.versions[spec]) return spec;
if (tags[spec]) return tags[spec];
const ms = maxSatisfying(versions, spec);
return ms || tags.latest || versions[versions.length - 1];
}
// Build a scorecard record for an exact name@version from its full packument.
// Shared by the range resolver (resolveSeeds) and the lockfile resolver
// (resolveLocked) so both produce identical record shapes.
function buildRecord(name, version, depth, pkg) {
const meta = (pkg.versions || {})[version] || {};
return {
key: `${name}@${version}`,
name,
version,
depth,
size: (meta.dist && meta.dist.unpackedSize) || 0,
installCmds: installCommands(meta),
installScript: installCommands(meta).length > 0,
deprecated: !!meta.deprecated,
maintainers: (pkg.maintainers || meta.maintainers || [])
.map((m) => (typeof m === "string" ? m : m && m.name))
.filter(Boolean),
publishedAt: (pkg.time && pkg.time[version]) || null,
};
}
// ===================== resolver (version-accurate, deduped by name@version) =====================
async function resolveSeeds(seeds) {
const packs = new Map(); // name -> Promise<packument>
const getPack = (name) => {
if (!packs.has(name)) packs.set(name, fetchPackument(name));
return packs.get(name);
};
const seen = new Map(); // "name@version" -> record (null while reserved)
const errors = [];
let frontier = seeds.slice();
while (frontier.length) {
const batch = frontier.splice(0, CONCURRENCY);
const next = [];
await Promise.all(
batch.map(async (req) => {
let pkg;
try {
pkg = await getPack(req.name);
} catch (e) {
errors.push(`${req.name}: ${e.message}`);
return;
}
const v = resolveSpec(pkg, req.spec);
if (!v) { errors.push(`${req.name}: no version for ${req.spec}`); return; }
const key = `${req.name}@${v}`;
// no await between this check and the reserve below → race-free
if (seen.has(key)) return;
seen.set(key, null);
const meta = (pkg.versions || {})[v] || {};
seen.set(key, buildRecord(req.name, v, req.depth, pkg));
for (const [dn, dr] of Object.entries(meta.dependencies || {}))
next.push({ name: dn, spec: dr, depth: req.depth + 1 });
})
);
frontier.push(...next);
}
return { records: [...seen.values()].filter(Boolean), errors };
}
// ===================== lockfile resolver (exact installed versions) =====================
// Given the pinned name@version set a lockfile already resolved, fetch each
// unique package's metadata and build records — no range math, no tree walk.
// This reflects what's actually on disk, version-for-version.
async function resolveLocked(entries) {
const uniq = new Map(); // "name@version" -> entry (shallowest depth wins)
for (const e of entries) {
const key = `${e.name}@${e.version}`;
const cur = uniq.get(key);
if (!cur || e.depth < cur.depth) uniq.set(key, e);
}
const list = [...uniq.values()];
const packs = new Map(); // name -> Promise<packument> (one request per name)
const getPack = (name) => {
if (!packs.has(name)) packs.set(name, fetchPackument(name));
return packs.get(name);
};
const records = [];
const errors = [];
let idx = 0;
const worker = async () => {
while (idx < list.length) {
const e = list[idx++];
let pkg;
try {
pkg = await getPack(e.name);
} catch (err) {
errors.push(`${e.name}: ${err.message}`);
continue;
}
if (!(pkg.versions && pkg.versions[e.version])) {
errors.push(`${e.name}@${e.version}: not on registry`);
continue;
}
records.push(buildRecord(e.name, e.version, e.depth, pkg));
}
};
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, list.length) }, worker));
return { records, errors };
}
// ===================== lockfile parsers (zero-dep) =====================
// Tolerant JSON: strips // and /* */ comments and trailing commas while
// respecting string literals (so https:// inside a value survives). Enough to
// read bun's text lockfile (bun.lock), which is JSONC, not strict JSON.
function parseJsonc(text) {
let out = "";
let i = 0;
const n = text.length;
let inStr = false, esc = false;
const skipWsComments = (j) => {
while (j < n) {
const c = text[j];
if (c === " " || c === "\t" || c === "\r" || c === "\n") { j++; continue; }
if (c === "/" && text[j + 1] === "/") { j += 2; while (j < n && text[j] !== "\n") j++; continue; }
if (c === "/" && text[j + 1] === "*") { j += 2; while (j < n && !(text[j] === "*" && text[j + 1] === "/")) j++; j += 2; continue; }
break;
}
return j;
};
while (i < n) {
const ch = text[i];
if (inStr) {
out += ch;
if (esc) esc = false;
else if (ch === "\\") esc = true;
else if (ch === '"') inStr = false;
i++;
continue;
}
if (ch === '"') { inStr = true; out += ch; i++; continue; }
if (ch === "/" && text[i + 1] === "/") { i += 2; while (i < n && text[i] !== "\n") i++; continue; }
if (ch === "/" && text[i + 1] === "*") { i += 2; while (i < n && !(text[i] === "*" && text[i + 1] === "/")) i++; i += 2; continue; }
if (ch === ",") {
const j = skipWsComments(i + 1);
if (j < n && (text[j] === "}" || text[j] === "]")) { i++; continue; } // drop trailing comma
out += ch; i++; continue;
}
out += ch; i++;
}
return JSON.parse(out);
}
// npm package-lock.json / npm-shrinkwrap.json (lockfileVersion 1, 2, 3).
function parsePackageLock(json) {
const out = [];
if (json.packages && typeof json.packages === "object") {
for (const [path, entry] of Object.entries(json.packages)) {
if (path === "" || !entry || entry.link) continue; // root + workspace links
const version = entry.version;
if (!version || !svParse(version)) continue; // skip git/file/non-semver
const marker = path.lastIndexOf("node_modules/");
const name = marker === -1 ? entry.name || path : path.slice(marker + "node_modules/".length);
if (name) out.push({ name, version });
}
return out;
}
const walk = (deps) => {
for (const [name, info] of Object.entries(deps || {})) {
if (info && info.version && svParse(info.version)) out.push({ name, version: info.version });
if (info && info.dependencies) walk(info.dependencies);
}
};
walk(json.dependencies);
return out;
}
// One pnpm depPath key -> { name, version }. Handles v5 (/name/ver_peer),
// v6 (/name@ver(peer)) and v9 (name@ver(peer)). Peer suffixes are dropped;
// non-semver resolutions (git/tarball/link) return null and are skipped.
function parsePnpmId(id, major) {
id = id.replace(/^['"]|['"]$/g, "");
const paren = id.indexOf("(");
if (paren !== -1) id = id.slice(0, paren); // strip v6/v9 peer suffix
id = id.replace(/^\//, "");
if (major < 6) {
const slash = id.lastIndexOf("/");
if (slash <= 0) return null;
let version = id.slice(slash + 1);
const us = version.indexOf("_"); // v5 peer separator follows the version
if (us !== -1) version = version.slice(0, us);
const name = id.slice(0, slash);
return svParse(version) ? { name, version } : null;
}
const at = id.lastIndexOf("@");
if (at <= 0) return null;
const name = id.slice(0, at);
const version = id.slice(at + 1);
return svParse(version) ? { name, version } : null;
}
// pnpm-lock.yaml: scan the `packages:` block (its keys are the resolved tree).
// Indentation-only parse — no YAML dependency.
function parsePnpmLock(text) {
const lvm = text.match(/^lockfileVersion:\s*['"]?([\d.]+)/m);
const major = lvm ? parseInt(lvm[1], 10) : 9;
const out = [];
let inPkgs = false;
for (const line of text.split(/\r?\n/)) {
if (/^packages:\s*$/.test(line)) { inPkgs = true; continue; }
if (!inPkgs) continue;
if (/^\S/.test(line)) break; // next top-level section ends the block
const m = line.match(/^ (\S.*?):\s*$/); // exactly 2-space indent = a package key
if (!m) continue;
const parsed = parsePnpmId(m[1], major);
if (parsed) out.push(parsed);
}
return out;
}
// bun.lock (text JSONC). packages[key] = [ "name@version", source, {meta}, hash ].
function parseBunLock(json) {
const out = [];
const pkgs = json.packages || {};
for (const key of Object.keys(pkgs)) {
const entry = pkgs[key];
const id = Array.isArray(entry) ? entry[0] : entry && entry.id;
if (typeof id !== "string") continue;
const at = id.lastIndexOf("@");
if (at <= 0) continue;
const name = id.slice(0, at);
const version = id.slice(at + 1);
if (svParse(version)) out.push({ name, version });
}
return out;
}
// yarn.lock (classic v1 and berry v2+). Each block is one or more comma-joined
// descriptors followed by an indented `version` line. The descriptor's range
// part flags non-registry sources (workspace/git/file/...), whose synthetic
// versions (0.0.0-use.local) would otherwise pass the semver filter.
const YARN_NON_REGISTRY = /^(workspace|link|portal|file|patch|exec|git|github|bitbucket|gitlab|https?):/i;
function parseYarnLock(text) {
const out = [];
let entry = null; // { name, skip }
for (const line of text.split(/\r?\n/)) {
if (/^[^\s#]/.test(line)) {
const first = line.replace(/:\s*$/, "").split(",")[0].trim().replace(/^"|"$/g, "");
const at = first.lastIndexOf("@");
const name = at <= 0 ? first : first.slice(0, at);
const range = at <= 0 ? "" : first.slice(at + 1);
entry = { name, skip: YARN_NON_REGISTRY.test(range) };
} else if (entry) {
const m = line.match(/^\s+"?version"?:?\s+"?([^"\s]+)"?/);
if (m) {
if (!entry.skip && svParse(m[1])) out.push({ name: entry.name, version: m[1] });
entry = null;
}
}
}
return out;
}
// Pick the lockfile to trust, newest-ecosystem first. Binary bun.lockb can't be
// read without bun, so it's flagged rather than parsed.
function detectLockfile(cwd) {
const at = (n) => resolvePath(cwd, n);
const tryParse = (source, file, parse) => {
if (!existsSync(at(file))) return null;
try { return { source, entries: parse(readFileSync(at(file), "utf8")) }; }
catch { return null; }
};
return (
tryParse("pnpm-lock.yaml", "pnpm-lock.yaml", parsePnpmLock) ||
tryParse("bun.lock", "bun.lock", (t) => parseBunLock(parseJsonc(t))) ||
tryParse("package-lock.json", "package-lock.json", (t) => parsePackageLock(JSON.parse(t))) ||
tryParse("npm-shrinkwrap.json", "npm-shrinkwrap.json", (t) => parsePackageLock(JSON.parse(t))) ||
tryParse("yarn.lock", "yarn.lock", parseYarnLock) ||
(existsSync(at("bun.lockb")) ? { source: "bun.lockb", entries: null, binary: true } : null)
);
}
// ===================== scoring =====================
function score(records, { excludeKey = null, asked = 1 } = {}) {
const counted = excludeKey ? records.filter((r) => r.key !== excludeKey) : records;
const total = counted.length;
const size = records.reduce((a, r) => a + r.size, 0);
const installScripts = records.filter((r) => r.installScript);
const deprecated = records.filter((r) => r.deprecated);
const direct = records.filter((r) => r.depth === 1).length;
const names = new Set(records.map((r) => r.name)).size;
for (const r of installScripts) {
const labels = new Set();
for (const cmd of r.installCmds) for (const l of scanDanger(cmd.cmd)) labels.add(l);
r.danger = [...labels];
}
const dangerous = installScripts.filter((r) => r.danger.length);
const maintainerSet = new Set();
for (const r of records) for (const m of r.maintainers) maintainerSet.add(m);
const maintainers = maintainerSet.size;
const dated = records.filter((r) => r.publishedAt);
const now = Date.now();
let oldest = null;
for (const r of dated)
if (!oldest || Date.parse(r.publishedAt) < Date.parse(oldest.publishedAt)) oldest = r;
const stale = dated.filter((r) => now - Date.parse(r.publishedAt) > STALE_MS);
// known CVEs across the resolved tree (from npm's advisory data)
const vulnList = records.flatMap((r) =>
(r.vulns || []).map((v) => ({ ...v, pkg: r.name, version: r.version }))
);
const sevCount = (sv) => vulnList.filter((v) => v.severity === sv).length;
const vulns = {
critical: sevCount("critical"),
high: sevCount("high"),
moderate: sevCount("moderate"),
low: sevCount("low"),
total: vulnList.length,
list: vulnList,
};
// Calibration: F is reserved for genuine danger — a known critical CVE or an
// install script that phones home / evals — not merely a big tree. Size,
// count, and staleness are bloat signals that only nudge the grade.
let pts = 100;
pts -= Math.min(50, vulns.critical * 25); // a critical CVE alone can force F
pts -= Math.min(36, vulns.high * 12);
pts -= Math.min(16, vulns.moderate * 4);
pts -= Math.min(8, vulns.low * 1);
pts -= Math.min(20, installScripts.length * 5); // benign native build = mild
const dangerPenalty = dangerous.reduce((a, r) => a + Math.min(40, r.danger.length * 15), 0);
pts -= Math.min(60, dangerPenalty); // the real threat — can sink to F alone
pts -= Math.min(20, deprecated.length * 5);
pts -= Math.min(12, stale.length * 2);
if (size > 100e6) pts -= 12;
else if (size > 30e6) pts -= 7;
else if (size > 10e6) pts -= 3;
if (total > 1000) pts -= 15;
else if (total > 400) pts -= 8;
else if (total > 150) pts -= 4;
else if (total > 50) pts -= 2;
pts = Math.max(0, pts);
const grade = pts >= 90 ? "A" : pts >= 80 ? "B" : pts >= 70 ? "C" : pts >= 55 ? "D" : "F";
const oldestYears = oldest ? (now - Date.parse(oldest.publishedAt)) / YEAR_MS : 0;
let quip;
if (vulns.critical || vulns.high) {
const n = vulns.critical + vulns.high;
const detail = [vulns.critical && vulns.critical + " critical", vulns.high && vulns.high + " high"].filter(Boolean).join(", ");
quip = `${n} serious known vulnerabilit${n > 1 ? "ies" : "y"} in the tree (${detail}) — patch or avoid.`;
}
else if (dangerous.length)
quip = `an install script is flagged for ${dangerous[0].danger.join(", ")} — read the command above before you trust it.`;
else if (installScripts.length)
quip = `${installScripts.length} package${installScripts.length > 1 ? "s" : ""} run${installScripts.length > 1 ? "" : "s"} code on your machine at install — review before trusting.`;
else if (deprecated.length) quip = "ships deprecated packages — may rot soon.";
else if (oldestYears >= 4 && pts < 88) quip = "some deps haven't shipped in years — may be unmaintained.";
else if (total > 200) quip = "heavy. one import, a whole neighborhood moves in.";
else if (total === 0) quip = "zero dependencies. install with confidence.";
else if (total <= 10) quip = "lean. safe to add.";
else quip = "fine — typical for its size.";
return { total, names, size, installScripts, deprecated, direct, dangerous, vulns, maintainers, oldest, stale, asked, grade, quip, pts };
}
// ===================== render =====================
function render({ subject, version, project, resolution, source }, s, errCount) {
const line = gray(" " + "─".repeat(46));
const gradeColor = s.grade === "A" || s.grade === "B" ? green : s.grade === "C" ? yellow : red;
const out = [""];
if (project)
out.push(` ${dim("should i trust")} ${bold(cyan(subject))}${dim("'s dependencies ?")}`);
else
out.push(` ${dim("should i install")} ${bold(cyan(subject))}${version ? dim("@" + version) : ""} ${dim("?")}`);
out.push("");
const dupNote = s.names < s.total ? dim(` · ${s.names} unique names`) : "";
out.push(
` 📦 ${bold(String(s.total))} packages ${project ? "in the tree" : "added"} ${dim(
project ? `(${s.asked} direct deps)` : `(${s.direct} direct, you asked for ${s.asked})`
)}${dupNote}`
);
out.push(` 👤 ${bold(String(s.maintainers))} maintainer${s.maintainers === 1 ? "" : "s"} you'd be trusting`);
out.push(` 💾 ${bold(bytes(s.size))} on disk`);
if (s.vulns.total) {
const v = s.vulns;
const parts = [
v.critical && `${v.critical} critical`,
v.high && `${v.high} high`,
v.moderate && `${v.moderate} moderate`,
v.low && `${v.low} low`,
].filter(Boolean);
out.push(` ${red("🛡")} ${bold(red(String(v.total)))} ${red(`known vulnerabilit${v.total > 1 ? "ies" : "y"} (${parts.join(", ")})`)}`);
const rank = { critical: 0, high: 1, moderate: 2, low: 3 };
const top = [...v.list].sort((a, b) => rank[a.severity] - rank[b.severity]).slice(0, 4);
for (const x of top)
out.push(` ${red("[" + x.severity + "]")} ${dim(x.pkg + "@" + x.version)} ${x.title.slice(0, 52)}`);
} else {
out.push(` ${green("✓")} no known vulnerabilities`);
}
if (s.installScripts.length) {
const n = s.installScripts.length;
out.push(` ${red("⚠")} ${bold(red(String(n)))} ${red(`package${n > 1 ? "s" : ""} run${n > 1 ? "" : "s"} code on your machine at install:`)}`);
const shown = [...s.installScripts].sort((a, b) => (b.danger?.length || 0) - (a.danger?.length || 0)).slice(0, 6);
for (const r of shown) {
const flag = r.danger?.length ? ` ${red("🚨 " + r.danger.join(", "))}` : "";
out.push(` ${bold(r.name)}${flag}`);
for (const cmd of r.installCmds) {
const danger = scanDanger(cmd.cmd).length > 0;
let txt = cmd.cmd.replace(/\s+/g, " ").trim();
if (txt.length > 72) txt = txt.slice(0, 71) + "…";
out.push(` ${dim(cmd.phase + ":")} ${danger ? red(txt) : gray(txt)}`);
}
}
if (n > 6) out.push(dim(` +${n - 6} more`));
} else {
out.push(` ${green("✓")} no install scripts`);
}
if (s.deprecated.length) out.push(` 🪦 ${bold(String(s.deprecated.length))} deprecated package(s)`);
if (s.oldest) {
const a = age(s.oldest.publishedAt);
const staleTag = s.stale.length ? dim(` (${s.stale.length} stale, 2y+)`) : "";
out.push(` 🕰 oldest dep last shipped ${bold(a)} ago${a === "?" ? "" : dim(" — " + s.oldest.name)}${staleTag}`);
}
out.push(line);
out.push(` ${bold("GRADE")} ${bold(gradeColor(s.grade))} ${dim('"' + s.quip + '"')}`);
if (errCount) out.push(gray(` note: ${errCount} package(s) could not be resolved`));
out.push(
gray(
resolution === "lockfile"
? ` resolved from ${source} — exact installed versions`
: " resolved like npm — highest version satisfying each range"
)
);
out.push("");
console.log(out.join("\n"));
}
// ===================== shutdown =====================
// Close undici's keepalive dispatcher and let the loop drain via exitCode,
// instead of process.exit() which can trip a libuv assertion on Windows Node 24.
async function shutdown(code) {
try {
const d = globalThis[Symbol.for("undici.globalDispatcher.1")];
if (d && typeof d.close === "function") await d.close();
} catch {}
process.exitCode = code;
}
// ===================== main =====================
function usage() {
console.log(
`\n ${bold("depsift")} ${dim("— should i install this?")}\n\n` +
` ${cyan("npx depsift <package>")} ${dim("audit one package before you add it")}\n` +
` ${cyan("npx depsift")} ${dim("audit your installed tree (uses the lockfile if present)")}\n\n` +
` ${dim("lockfiles: pnpm-lock.yaml, bun.lock, package-lock.json — auto-detected.")}\n` +
` ${dim("pass")} ${cyan("--no-lock")} ${dim("to re-resolve package.json ranges from the registry instead.")}\n\n` +
` e.g. ${dim("npx depsift express")}\n`
);
}
function readProjectDeps() {
const file = resolvePath(process.cwd(), "package.json");
if (!existsSync(file)) return null;
let json;
try { json = JSON.parse(readFileSync(file, "utf8")); } catch { return null; }
const fields = ["dependencies", "devDependencies", "optionalDependencies"];
const seeds = [];
const seen = new Set();
for (const f of fields)
for (const [name, spec] of Object.entries(json[f] || {})) {
if (seen.has(name)) continue;
seen.add(name);
seeds.push({ name, spec, depth: 1 });
}
return { name: json.name || "this project", seeds };
}
// Resolve what to audit in project mode. With a lockfile present (and not
// disabled) we audit the exact installed tree; otherwise we fall back to
// re-resolving package.json ranges against the registry.
function loadProject({ useLock = true } = {}) {
const proj = readProjectDeps();
if (!proj) return null;
if (!useLock) return { ...proj, locked: null };
const lf = detectLockfile(process.cwd());
if (!lf) return { ...proj, locked: null };
if (lf.binary) return { ...proj, locked: null, binaryLock: lf.source };
if (!lf.entries || !lf.entries.length) return { ...proj, locked: null };
const direct = new Set(proj.seeds.map((s) => s.name));
const locked = lf.entries.map((e) => ({ ...e, depth: direct.has(e.name) ? 1 : 2 }));
return { ...proj, locked, lockSource: lf.source };
}
async function main() {
const argv = process.argv.slice(2).filter((a) => !a.startsWith("-"));
const spinner = () => process.stdout.isTTY && process.stdout.write(dim(" resolving…\r"));
const clearSpinner = () => process.stdout.isTTY && process.stdout.write(" \r");
// ---- project mode: no package given ----
if (!argv.length) {
const useLock = !process.argv.slice(2).includes("--no-lock");
const proj = loadProject({ useLock });
if (!proj) { usage(); return shutdown(1); }
if (proj.binaryLock)
console.error(
` ${yellow("note")} ${dim(`${proj.binaryLock} is a binary lockfile depsift can't read — auditing package.json ranges instead (bun's text lockfile, bun.lock, is supported).`)}`
);
const usingLock = !!(proj.locked && proj.locked.length);
if (!usingLock && !proj.seeds.length) {
console.log(`\n ${green("✓")} ${bold(proj.name)} has no dependencies.\n`);
return shutdown(0);
}
spinner();
const { records, errors } = usingLock
? await resolveLocked(proj.locked)
: await resolveSeeds(proj.seeds);
clearSpinner();
if (!records.length) { console.error(`\n ${red("✗")} could not resolve dependencies\n`); return shutdown(1); }
await fetchAdvisories(records);
const s = score(records, { asked: proj.seeds.length });
render(
{ subject: proj.name, project: true, resolution: usingLock ? "lockfile" : "registry", source: proj.lockSource },
s,
errors.length
);
return shutdown(s.grade === "F" ? 2 : 0);
}
// ---- single package mode ----
const { name, version } = parseArg(argv[0]);
spinner();
let result;
try {
result = await resolveSeeds([{ name, spec: version, depth: 0 }]);
} catch (e) {
clearSpinner();
console.error(`\n ${red("✗")} ${e.message}\n`);
return shutdown(1);
}
clearSpinner();
if (!result.records.length) {
console.error(`\n ${red("✗")} could not resolve ${name}\n`);
return shutdown(1);
}
await fetchAdvisories(result.records);
const root = result.records.find((r) => r.name === name && r.depth === 0);
const s = score(result.records, { excludeKey: root && root.key, asked: 1 });
render({ subject: name, version }, s, result.errors.length);
return shutdown(s.grade === "F" ? 2 : 0);
}
// Run only when invoked as the CLI, so the parsers can be imported for tests.
// Compare *real* paths: npm/pnpm/npx install the bin as a symlink, so argv[1]
// (the symlink) and import.meta.url (the resolved file) differ otherwise.
function isCliEntry() {
const arg = process.argv[1];
if (!arg) return false;
try {
return realpathSync(arg) === realpathSync(fileURLToPath(import.meta.url));
} catch {
return false;
}
}
if (isCliEntry()) {
main().catch(async (e) => {
console.error(e);
await shutdown(1);
});
}
export { parseJsonc, parsePackageLock, parsePnpmId, parsePnpmLock, parseBunLock, parseYarnLock };