@exodus/stasis 1.0.0-beta.9 → 1.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +6 -2
  2. package/bin/stasis.js +222 -334
  3. package/package.json +38 -14
  4. package/src/audit-corrections.js +11 -42
  5. package/src/audit.js +256 -212
  6. package/src/babel.js +119 -82
  7. package/src/bundle-from-lockfile.js +9 -21
  8. package/src/bundle-reader.js +24 -8
  9. package/src/bundle.js +0 -3
  10. package/src/cmd/build.js +211 -117
  11. package/src/cmd/bundle-options.js +347 -0
  12. package/src/cmd/bundle.js +1664 -1001
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +48 -21
  15. package/src/cmd/output.js +24 -12
  16. package/src/cmd/sbom.js +6 -9
  17. package/src/cmd/tokens.js +60 -0
  18. package/src/define.js +218 -0
  19. package/src/diff.js +73 -129
  20. package/src/esbuild.js +0 -4
  21. package/src/flow.js +27 -0
  22. package/src/installed.js +265 -0
  23. package/src/json-stream.js +4 -9
  24. package/src/loader-mock.js +3 -8
  25. package/src/loader.js +1 -5
  26. package/src/loaders/bash.js +43 -120
  27. package/src/loaders/cargo.js +301 -808
  28. package/src/loaders/foundry.js +112 -290
  29. package/src/loaders/paths.js +15 -26
  30. package/src/loaders/php.js +211 -492
  31. package/src/loaders/rust.js +518 -1461
  32. package/src/loaders/solidity-ownership.js +51 -142
  33. package/src/loaders/solidity.js +42 -188
  34. package/src/loaders/toml.js +7 -17
  35. package/src/lockfile.js +0 -3
  36. package/src/metro-assets.js +41 -0
  37. package/src/metro-resolver.js +58 -133
  38. package/src/metro-transformer.js +0 -6
  39. package/src/metro.js +0 -4
  40. package/src/mock.js +32 -80
  41. package/src/parse.js +8 -7
  42. package/src/prune.js +0 -3
  43. package/src/resolve-fields.js +152 -249
  44. package/src/resolve-node.js +29 -45
  45. package/src/resolve-typescript.js +166 -298
  46. package/src/rollup.js +0 -4
  47. package/src/run-installed.js +10 -0
  48. package/src/sbom.js +70 -97
  49. package/src/scan.js +240 -282
  50. package/src/sixel.js +310 -0
  51. package/src/table.js +95 -0
  52. package/src/validate-notes.d.ts +19 -0
  53. package/src/validate-notes.js +72 -0
  54. package/src/validate.d.ts +159 -0
  55. package/src/validate.js +1315 -0
  56. package/src/vfs-bundle/entries.js +50 -46
  57. package/src/vfs-bundle/github.js +114 -94
  58. package/src/vfs-bundle/glob.js +379 -0
  59. package/src/vfs-bundle/lazy.js +99 -0
  60. package/src/vfs-bundle/prisma.js +235 -105
  61. package/src/vfs-bundle/soldeer.js +28 -49
  62. package/src/vfs-bundle/tree.js +418 -277
  63. package/src/vfs-bundle/yarnclean.js +79 -0
  64. package/src/vfs-bundle.js +24 -55
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +79 -231
  67. package/src/installed-commits.js +0 -182
package/src/why.js CHANGED
@@ -1,65 +1,46 @@
1
- import { hasNodeModulesSegment, moduleFileKey } from '@exodus/stasis-core/util'
1
+ import { entryDirOf, hasNodeModulesSegment, moduleFileKey, upsert } from '@exodus/stasis-core/util'
2
2
  import { isEvidenceFile } from './audit-corrections.js'
3
3
  import { parseFile } from './parse.js'
4
4
 
5
- // `stasis audit --why` support: from an artifact's resolution graph (`imports`)
6
- // and its per-consumer provenance (`reason`), explain WHY a vulnerable module is
7
- // present by listing the cross-module import chains that reach it.
8
- //
9
- // Corrections apply at the EDGE level (see audit-corrections.js): an edge whose
10
- // target file is not evidence of the module's real code -- a package.json
11
- // manifest read, or a corrected file like ws's noop browser.js stub -- never
12
- // enters the graph, so no displayed chain ends with (or passes through) one, and
13
- // a consumer that recorded only such files of a package is not one of its reasons.
14
- //
15
- // A "path" is a chain of node_modules packages ending at the target module, e.g.
16
- // `a -> b -> c`. The first-party (`src`) node is never shown: a chain is walked
17
- // back through cross-module edges and stops at a HEAD -- a module that a src file
18
- // imports directly, OR one nothing else in node_modules imports (the top of its
19
- // dependency subtree). So `a -> b -> c` surfaces even when no src file imports
20
- // `a` directly (a is the top of the chain), and `b -> c` surfaces additionally
21
- // when `b` is itself imported by src.
22
- //
23
- // The reasons shown for a flagged package are EXACTLY the ones that recorded the
24
- // package itself -- the same set the non-`--why` column reports (see collectReasons).
25
- // `--why` only adds, per reason, HOW that reason reaches it. So a consumer that
26
- // imports a package but never recorded it (externalized it) is not one of its
27
- // reasons and is never shown; and every reason that did record it appears, at least
28
- // as a bare line.
29
- //
30
- // The per-reason PATH is file-level. A consumer "has" the edge `b -> c` only if it
31
- // recorded the specific file in `b` that imports `c`, so a chain belongs to a
32
- // consumer only when it recorded the file forming EVERY edge -- `metro: a -> b -> c`
33
- // can't appear if the file importing `c` from `b` isn't metro's. Each reason's
34
- // chains are enumerated on its own subgraph (only its edges), so it shows its
35
- // MAXIMAL file-level path: if metro's edges only reach up to `b`, its line is the
36
- // shorter `metro: b -> c`; a reason that recorded the package but never imports it
37
- // through the graph shows a bare `metro: c`. A bundle with a single consumer omits
38
- // the `reason` map entirely; there every chain renders bare, with no prefix.
5
+ // Every record of a module map, and after a dependency's, each `vendored` copy in it as a record at its directory,
6
+ // with its host's `ecosystem`, `vendoredIn` its host's dir, and the `files` it holds. A host keeps all its files.
7
+ export function* packageRecords(modules) {
8
+ for (const [dir, record] of modules) {
9
+ yield [dir, record]
10
+ if (record.vendored === undefined) continue
11
+ const held = new Map()
12
+ for (const rel of Object.keys(record.files)) {
13
+ const sub = entryDirOf(record.vendored, rel)
14
+ if (sub === undefined) continue
15
+ // A descriptor, so a contents-free bundle's locked values stay unread.
16
+ Object.defineProperty(upsert(held, sub, () => Object.create(null)), rel.slice(sub.length + 1), Object.getOwnPropertyDescriptor(record.files, rel))
17
+ }
18
+ for (const [sub, files] of held) {
19
+ const { name, version } = record.vendored[sub]
20
+ yield [moduleFileKey(dir, sub), { name, version, ecosystem: record.ecosystem, vendoredIn: dir, files }]
21
+ }
22
+ }
23
+ }
24
+
25
+ // `stasis audit --why`: the import chains (`a -> b -> c`) by which each consumer that recorded a flagged package
26
+ // reaches it, on its own file-level subgraph, climbing to a HEAD: a package src imports, or one nothing in
27
+ // node_modules does. An edge into a file that is no evidence of real code (audit-corrections.js) is none.
39
28
 
40
- // Cap on paths enumerated per target to bound pathological graphs (many diamond
41
- // dependencies compound into a combinatorial number of simple paths). Hitting it
42
- // is surfaced as a marker line rather than silently dropped.
29
+ // Diamond dependencies compound into a combinatorial number of simple paths; a cut is marked, not silently dropped.
43
30
  const PATH_CAP = 2000
44
31
 
45
- // Packages a chain never walks PAST: everything imports these build/runtime hubs,
46
- // so continuing up from them just adds noise. When a chain reaches one it stops
47
- // there, and the hub becomes the chain's head (`@babel/core -> a -> b -> c`),
48
- // still prefixed with its own reason.
32
+ // Build/runtime hubs everything imports: a chain reaching one stops there, the hub its head.
49
33
  const TERMINAL_PACKAGES = new Set(['@babel/core', 'react-native', 'metro'])
50
34
 
51
- // Index one parsed artifact: map every project-relative file to its owning module
52
- // dir, record each dir's package identity + whether it's a node_modules dep, and
53
- // keep each dir's EVIDENCE file list (for the target's-own-reason lookup).
54
- // `fileToDir` is complete; `dirFiles` only holds files that count as real code of
55
- // the dir (see audit-corrections.js) -- a consumer that recorded nothing of a
56
- // package but a corrected file / its package.json manifest is not one of its
57
- // reasons, exactly as in collectReasons.
35
+ const EMPTY_GRAPH = { adjRev: new Map(), srcImporters: new Map() }
36
+
37
+ // Each dir's evidence files (`dirFiles`) as collectReasons counts them. A copy a dependency ships is a module of its
38
+ // own, so a chain can end at it, its files its host's evidence too.
58
39
  function moduleIndex(artifact) {
59
40
  const fileToDir = new Map()
60
41
  const dirInfo = new Map()
61
42
  const dirFiles = new Map()
62
- for (const [dir, { name, version, files }] of artifact.modules) {
43
+ for (const [dir, { name, version, files }] of packageRecords(artifact.modules)) {
63
44
  dirInfo.set(dir, { name: name ?? null, version: version ?? null, dep: hasNodeModulesSegment(dir) })
64
45
  const list = []
65
46
  for (const rel of Object.keys(files)) {
@@ -72,91 +53,54 @@ function moduleIndex(artifact) {
72
53
  return { fileToDir, dirInfo, dirFiles }
73
54
  }
74
55
 
75
- // Flatten the imports graph (conditions -> parent -> specifier -> target) into
76
- // deduped file-level edges [parentFile, targetFile]. A `--metro` target may be a
77
- // { platform: file } map; each platform's file becomes its own edge.
56
+ // Deduped [parentFile, targetFile] edges; a `--metro` target may be a { platform: file } map.
78
57
  function fileEdges(imports) {
79
- const edges = []
80
- const seen = new Set()
58
+ const edges = new Map()
81
59
  for (const [, byParent] of imports) {
82
60
  for (const [parent, specifiers] of byParent) {
83
61
  for (const [, target] of specifiers) {
84
- const targets = target instanceof Map ? [...target.values()] : [target]
85
- for (const t of targets) {
86
- const key = `${parent}\0${t}`
87
- if (seen.has(key)) continue
88
- seen.add(key)
89
- edges.push([parent, t])
90
- }
62
+ for (const t of target instanceof Map ? target.values() : [target]) edges.set(`${parent}\0${t}`, [parent, t])
91
63
  }
92
64
  }
93
65
  }
94
- return edges
66
+ return edges.values()
95
67
  }
96
68
 
97
- // Per-reason cross-module subgraphs. Every import edge is a FILE edge (a specific
98
- // file in the parent importing the target), and a consumer only "has" that edge if
99
- // it recorded the PARENT file. So a chain belongs to a reason only when that reason
100
- // bundled the file forming EVERY one of its edges. We build one subgraph per
101
- // consumer (bucket) -- holding only the edges that consumer's files created -- and
102
- // later enumerate that consumer's chains on it. With no reason map there is a single
103
- // bucket '' holding the full graph (chains render bare). Each subgraph:
104
- // adjRev: depDir -> Set(dep predecessor dir) -- dep->dep edges, reversed
105
- // srcImporters: depDir -> Set(src file) -- src->dep edges
106
- // Intra-module edges and edges into a src module are dropped.
69
+ // Per-consumer subgraphs ('' the whole graph where there is no reason map), an edge a consumer's where it recorded
70
+ // the importing file: `adjRev` dep dir -> the dep dirs importing it, `srcImporters` dep dir -> the src files.
107
71
  function bucketGraphs(edges, fileToDir, dirInfo, fileReasons) {
108
72
  const graphs = new Map()
109
- const graphFor = (bucket) => {
110
- let g = graphs.get(bucket)
111
- if (g === undefined) graphs.set(bucket, (g = { adjRev: new Map(), srcImporters: new Map() }))
112
- return g
113
- }
114
73
  for (const [pf, tf] of edges) {
115
74
  const pd = fileToDir.get(pf)
116
75
  const td = fileToDir.get(tf)
117
76
  if (pd === undefined || td === undefined || pd === td) continue
118
77
  const tdi = dirInfo.get(td)
119
78
  if (!tdi.dep) continue
120
- // An edge counts only when it targets the module's real code (see
121
- // audit-corrections.js): a `package.json` manifest read (react-native scans
122
- // sibling packages' manifests for Haste/asset resolution) or a corrected file
123
- // (ws's noop browser.js stub) is not a dependency on the module and must not
124
- // pull it into the --why graph -- no chain may end (or pass) through one.
79
+ // A manifest read (react-native scans its siblings' for Haste) or a corrected file (ws's noop
80
+ // browser.js) is no dependency on the module: no chain may end at or pass through one.
125
81
  if (!isEvidenceFile(tdi.name, tdi.version, tf.slice(td.length + 1))) continue
126
- // The consumers this edge belongs to: those that recorded its parent file.
127
82
  const buckets = fileReasons === null ? [''] : (fileReasons.get(pf) ?? [])
128
83
  const dep = dirInfo.get(pd).dep
129
84
  for (const bucket of buckets) {
130
- const map = dep ? graphFor(bucket).adjRev : graphFor(bucket).srcImporters
131
- let set = map.get(td)
132
- if (set === undefined) map.set(td, (set = new Set()))
133
- set.add(dep ? pd : pf)
85
+ const graph = upsert(graphs, bucket, () => ({ adjRev: new Map(), srcImporters: new Map() }))
86
+ upsert(dep ? graph.adjRev : graph.srcImporters, td, () => new Set()).add(dep ? pd : pf)
134
87
  }
135
88
  }
136
89
  return graphs
137
90
  }
138
91
 
139
- // Invert the reason map to file -> Set(consumer). null when the artifact carries
140
- // no reason map (single-consumer bundle / lockfile) -> chains render bare.
141
- export function invertReason(reason) {
92
+ // file -> Set(consumer), or null without a reason map (a single-consumer bundle, a lockfile): chains render bare.
93
+ export function invertReason(reason, name = (consumer) => consumer) {
142
94
  if (!reason) return null
143
95
  const byFile = new Map()
144
96
  for (const [consumer, list] of Object.entries(reason)) {
145
97
  if (!Array.isArray(list)) continue
146
- for (const f of list) {
147
- let set = byFile.get(f)
148
- if (set === undefined) byFile.set(f, (set = new Set()))
149
- set.add(consumer)
150
- }
98
+ for (const f of list) upsert(byFile, f, () => new Set()).add(name(consumer))
151
99
  }
152
100
  return byFile
153
101
  }
154
102
 
155
- // dir -> Set(consumer): the consumers that recorded any of the dir's own EVIDENCE
156
- // files (dirFiles is pre-filtered -- a consumer that recorded only a corrected
157
- // file / manifest of the dir doesn't count; see moduleIndex). null when the
158
- // artifact has no reason map. Used to decide whether a bare target belongs to a
159
- // reason that never imports it (a flagged package a bundler shipped).
103
+ // dir -> the consumers that recorded any of its evidence files: whether a target belongs to one never importing it.
160
104
  function dirReasonsIndex(dirFiles, fileReasons) {
161
105
  if (fileReasons === null) return null
162
106
  const byDir = new Map()
@@ -168,13 +112,8 @@ function dirReasonsIndex(dirFiles, fileReasons) {
168
112
  return byDir
169
113
  }
170
114
 
171
- // Every simple dep-only path (within one reason's subgraph) that ends at
172
- // `targetDir`, walking predecessors backward and emitting a path each time its
173
- // head is a HEAD node (`isHead`) or a terminal package (`isTerminal`). A terminal
174
- // node ALSO stops the walk -- the chain never goes past @babel/core / react-native
175
- // / metro, and this applies to `targetDir` too: a terminal target is emitted bare
176
- // (just `[targetDir]`), never climbed above. Its provenance instead comes from the
177
- // reason whose subgraph this is. Returns dirs head-first; `truncated` flags the cap.
115
+ // Every simple path of `adjRev` ending at `targetDir`, head first, where its head is a HEAD or a terminal package,
116
+ // which the walk never climbs past.
178
117
  function pathsTo(adjRev, isHead, isTerminal, targetDir) {
179
118
  const results = []
180
119
  let truncated = false
@@ -185,7 +124,7 @@ function pathsTo(adjRev, isHead, isTerminal, targetDir) {
185
124
  }
186
125
  const terminal = isTerminal(node)
187
126
  if (isHead(node) || terminal) results.push(suffix)
188
- if (terminal) return // don't walk past @babel/core / react-native / metro
127
+ if (terminal) return
189
128
  for (const pred of adjRev.get(node) ?? []) {
190
129
  if (inPath.has(pred)) continue // no repeated module -> break cycles
191
130
  inPath.add(pred)
@@ -201,24 +140,13 @@ function pathsTo(adjRev, isHead, isTerminal, targetDir) {
201
140
  const chainKey = (c, i = 0) => c.slice(i).join('\0')
202
141
  const renderChain = (c) => c.join(' -> ')
203
142
 
204
- // Display order for one bucket's (deduped) chains:
205
- // 1. a chain that is a full proper suffix of another always renders before it
206
- // (`B -> C` before `A -> B -> C`) -- a hard constraint;
207
- // 2. chains sharing a head stay contiguous, and recursively chains sharing a
208
- // longer prefix stay contiguous within their group -- never interleaved
209
- // with other groups;
210
- // 3. among sibling groups (at every level), the group whose LONGEST chain is
211
- // shortest renders first; ties alphabetically.
212
- // All chains end at the same target, so a full suffix always has a DIFFERENT
213
- // head: rule 1 only ever orders head groups against each other, never members of
214
- // one group, and is enforced with a topological pass over the head groups. In
215
- // the rare cyclic case (mutual suffix constraints through an import cycle) the
216
- // preferred group order wins and one constraint is dropped.
143
+ // One bucket's chains in display order: a full suffix of another first (`B -> C` before `A -> B -> C`), chains
144
+ // sharing a prefix contiguous, sibling groups by their longest chain, shortest first, then name. A suffix only orders
145
+ // head groups (all chains end at one target): a topological pass, a cycle's constraints broken by that preference.
217
146
  function orderChains(chains) {
218
147
  if (chains.length <= 1) return chains
219
148
 
220
- // Recursive contiguous grouping: `list` shares its first `depth` nodes; group
221
- // by the node AT `depth` and order sibling groups shortest-max first.
149
+ // `list` shares its first `depth` nodes: group it by the node at `depth`, recursively.
222
150
  const arrange = (list, depth) => {
223
151
  if (list.length <= 1) return list
224
152
  return [...Map.groupBy(list, (c) => c[depth])]
@@ -229,8 +157,7 @@ function orderChains(chains) {
229
157
 
230
158
  const byHead = Map.groupBy(chains, (c) => c[0])
231
159
 
232
- // Rule 1: whenever a chain is a full suffix of another, its head group must
233
- // render before the extension's head group.
160
+ // A chain's full suffix's head group renders before the chain's.
234
161
  const keys = new Set(chains.map((c) => chainKey(c)))
235
162
  const succ = new Map([...byHead.keys()].map((h) => [h, new Set()]))
236
163
  const indeg = new Map([...byHead.keys()].map((h) => [h, 0]))
@@ -259,42 +186,19 @@ function orderChains(chains) {
259
186
  return out
260
187
  }
261
188
 
262
- // Compress one reason bucket's chains (node-name arrays, all ending at the same
263
- // target). Chains are emitted in display order (orderChains -- prefix groups
264
- // kept contiguous, a full-suffix chain always before its extensions); each collapses
265
- // at the earliest node whose remaining sub-path to the target is already
266
- // recoverable from the lines above it, rendering `prefix -> node -> ... -> target`.
267
- // A sub-path is recoverable once ANY emitted line shows its head node in the
268
- // line's visible part -- a full line shows every node, a collapsed line its prefix
269
- // down to the collapse point -- because from there the earlier lines spell out the
270
- // rest. So a repeated tail is written out once and referenced with `...`
271
- // everywhere else, transitively:
272
- // D -> C -> B -> A (full)
273
- // P -> E -> D -> ... -> A (D's tail is in the full line)
274
- // Q -> E -> ... -> A (E's tail is now visible in P's line)
275
- // G -> F -> E -> ... -> A
276
- // H -> F -> ... -> A (F's tail is visible in G's line)
277
- // A collapse hides only nodes between the visible ones and the target, and lines
278
- // that collapse to identical text are emitted once (a hub reached by several shown
279
- // sub-paths yields a single `importer -> hub -> ... -> target` per importer).
189
+ // One bucket's chains, in orderChains' order, each collapsed at its earliest node whose sub-path to the
190
+ // target an earlier line shows (a line shows its nodes down to its collapse point), so `D -> C -> B -> A`
191
+ // then gives `P -> E -> D -> ... -> A`, then `Q -> E -> ... -> A`. Lines collapsing alike are emitted once.
280
192
  function compressChains(chains) {
281
193
  const uniq = [...new Map(chains.map((c) => [renderChain(c), c])).values()]
282
194
  if (uniq.length <= 1) return uniq.map(renderChain)
283
195
  const sorted = orderChains(uniq)
284
- const target = sorted[0][sorted[0].length - 1]
196
+ const target = sorted[0].at(-1)
285
197
 
286
198
  const revealed = new Set() // sub-paths recoverable from lines already emitted
287
- const out = []
288
- const seen = new Set()
289
- const push = (line) => {
290
- if (!seen.has(line)) {
291
- seen.add(line)
292
- out.push(line)
293
- }
294
- }
199
+ const out = new Set()
295
200
  for (const c of sorted) {
296
- // Collapse at the longest proper tail (earliest position, >= 3 nodes so >= 1 is
297
- // hidden) that an earlier line already made recoverable.
201
+ // Collapse at the longest proper tail (>= 3 nodes, so one is hidden) an earlier line made recoverable.
298
202
  let at = -1
299
203
  for (let i = 1; c.length - i >= 3; i++) {
300
204
  if (revealed.has(chainKey(c, i))) {
@@ -302,128 +206,72 @@ function compressChains(chains) {
302
206
  break
303
207
  }
304
208
  }
305
- // Index of the last node this line shows: all of them when full, the collapse
306
- // point otherwise.
307
- const visible = at === -1 ? c.length - 1 : at
308
- if (at === -1) push(renderChain(c))
309
- else push(`${renderChain(c.slice(0, at + 1))} -> ... -> ${target}`)
209
+ out.add(at === -1 ? renderChain(c) : `${renderChain(c.slice(0, at + 1))} -> ... -> ${target}`)
310
210
  // Every sub-path headed by a node this line shows is now recoverable.
211
+ const visible = at === -1 ? c.length - 1 : at
311
212
  for (let i = 0; i <= visible; i++) revealed.add(chainKey(c, i))
312
213
  }
313
- return out
214
+ return [...out]
314
215
  }
315
216
 
316
- // Default (non `--why-deep`) pruning: drop a chain when another chain in the SAME
317
- // bucket is a full proper suffix of it. Those longer chains only tell how the
318
- // suffix's head is reached through further subdeps -- when that head is itself a
319
- // direct dependency of src (or the flagged target itself), its own line already
320
- // explains the pull-in, so `A -> B -> C -> D` is noise next to `B -> C -> D` (and
321
- // everything is noise next to a bare `D`). Only a FULL suffix counts: chains that
322
- // merely share a tail (`E -> C -> B -> A` vs `D -> C -> B -> A`) both survive and
323
- // are left to compressChains. The shortest chain always survives.
217
+ // Without --why-deep, drop a chain when another in its bucket is a full proper suffix of it: the suffix's
218
+ // line already explains the pull-in. Chains that merely share a tail both stay, for compressChains.
324
219
  function dropSuffixed(chains) {
325
220
  const keys = new Set(chains.map((c) => chainKey(c)))
326
- return chains.filter((c) => {
327
- for (let i = 1; i < c.length; i++) {
328
- if (keys.has(chainKey(c, i))) return false
329
- }
330
- return true
331
- })
221
+ return chains.filter((c) => !c.keys().drop(1).some((i) => keys.has(chainKey(c, i))))
332
222
  }
333
223
 
334
- // Map each targeted package (`name@version`) to its ordered `--why` lines.
335
- // `targetKeys` (optional) restricts work to the packages that matter (the ones
336
- // carrying advisories); omit it to compute for every node_modules package.
337
- // `reasonFilter` (optional, from --reason) keeps only chains attributed to that
338
- // consumer, dropping every other chain (and bare, unattributed chains).
339
- // By default a chain is dropped when a same-bucket chain is a full suffix of it
340
- // (see dropSuffixed); `deep` (--why-deep) keeps every chain. Chains are then
341
- // deduplicated and compressed per reason bucket (see compressChains), unless
342
- // `full` (--why-full) -- then every surviving chain is spelled out with no `...`
343
- // collapse, in the same shortest-first order. The flags compose: deep + full is
344
- // the complete raw listing. Artifacts without a resolution graph (`imports`)
345
- // contribute nothing.
346
- export function collectWhy(files, targetKeys, reasonFilter = null, { deep = false, full = false } = {}) {
347
- // key -> reason bucket ('' = unattributed) -> Map(chainKey -> node-name array)
224
+ // Each package of `targetKeys` (`name@version`, else every dependency) -> its --why lines, `consumer: chain`, or a
225
+ // bare chain without a reason map. Pruned (dropSuffixed) unless `deep`, compressed (compressChains) unless `full`.
226
+ export function collectWhy(files, targetKeys, reasonFilter = null, { deep = false, full = false, consumerName } = {}) {
227
+ // key -> reason bucket ('' unattributed) -> Map(chainKey -> node names)
348
228
  const acc = new Map()
349
229
  const truncatedKeys = new Set()
350
- const bucketChains = (key, bucket) => {
351
- let buckets = acc.get(key)
352
- if (buckets === undefined) acc.set(key, (buckets = new Map()))
353
- let chains = buckets.get(bucket)
354
- if (chains === undefined) buckets.set(bucket, (chains = new Map()))
355
- return chains
356
- }
357
- const addChain = (key, bucket, nodes) => bucketChains(key, bucket).set(chainKey(nodes), nodes)
358
-
359
- const EMPTY_GRAPH = { adjRev: new Map(), srcImporters: new Map() }
230
+ const addChain = (key, bucket, nodes) => upsert(upsert(acc, key, () => new Map()), bucket, () => new Map()).set(chainKey(nodes), nodes)
360
231
 
361
232
  for (const file of files) {
362
233
  const artifact = parseFile(file)
363
- const imports = artifact.imports
364
- if (!imports || imports.size === 0) continue
234
+ if (!artifact.imports || artifact.imports.size === 0) continue
365
235
 
366
236
  const { fileToDir, dirInfo, dirFiles } = moduleIndex(artifact)
367
- const edges = fileEdges(imports)
368
- const fileReasons = invertReason(artifact.reason)
369
- const graphs = bucketGraphs(edges, fileToDir, dirInfo, fileReasons)
237
+ const fileReasons = invertReason(artifact.reason, consumerName)
238
+ const graphs = bucketGraphs(fileEdges(artifact.imports), fileToDir, dirInfo, fileReasons)
370
239
  const dirReasons = dirReasonsIndex(dirFiles, fileReasons)
371
- // Terminal packages end a chain regardless of what imports them.
372
240
  const isTerminal = (node) => TERMINAL_PACKAGES.has(dirInfo.get(node)?.name)
373
241
 
374
- // Group target dirs by `name@version` (a package can appear at several dirs,
375
- // e.g. nested node_modules); paths from every matching dir are unioned.
242
+ // A package can be at several dirs (nested node_modules): their paths are unioned.
376
243
  const dirsByKey = new Map()
377
244
  for (const [dir, info] of dirInfo) {
378
245
  if (!info.dep || !info.name || !info.version) continue
379
246
  const key = `${info.name}@${info.version}`
380
247
  if (targetKeys && !targetKeys.has(key)) continue
381
- let arr = dirsByKey.get(key)
382
- if (arr === undefined) dirsByKey.set(key, (arr = []))
383
- arr.push(dir)
248
+ upsert(dirsByKey, key, () => []).push(dir)
384
249
  }
385
- if (dirsByKey.size === 0) continue
386
250
 
387
251
  for (const [key, dirs] of dirsByKey) {
388
252
  for (const targetDir of dirs) {
389
- // The reasons to report are exactly the ones the FLAGGED package itself was
390
- // recorded under -- identical to the non-`--why` column (see collectReasons).
391
- // For each, enumerate that reason's MAXIMAL file-level chains on its own
392
- // subgraph; a reason that recorded the package but doesn't import it through
393
- // the graph still yields a bare line. A reason that IMPORTS the package but
394
- // never recorded it (externalized it) is not one of the package's reasons and
395
- // is not shown -- so the --why reason set matches non-`--why` exactly.
253
+ // The consumers that recorded the package itself, as collectReasons': one importing it unrecorded is none.
396
254
  const own = fileReasons === null ? [''] : (dirReasons.get(targetDir) ?? [])
397
255
  for (const bucket of own) {
398
256
  if (reasonFilter !== null && bucket !== reasonFilter) continue
399
257
  const { adjRev, srcImporters } = graphs.get(bucket) ?? EMPTY_GRAPH
400
- // A head tops a chain: a src file imports it directly, or nothing else
401
- // in this bucket's graph imports it.
402
258
  const isHead = (node) => srcImporters.has(node) || !adjRev.has(node)
403
259
  const { results, truncated } = pathsTo(adjRev, isHead, isTerminal, targetDir)
404
260
  if (truncated) truncatedKeys.add(key)
405
- for (const p of results) {
406
- const nodes = p.map((d) => dirInfo.get(d)?.name ?? d)
407
- addChain(key, reasonFilter !== null ? '' : bucket, nodes)
408
- }
261
+ for (const p of results) addChain(key, reasonFilter !== null ? '' : bucket, p.map((d) => dirInfo.get(d)?.name ?? d))
409
262
  }
410
263
  }
411
264
  }
412
265
  }
413
266
 
414
- // --why-full: no `...` collapse -- every chain spelled out, in the same display
415
- // order as the collapsed rendering (see orderChains).
416
- const renderFull = (chains) => orderChains(chains).map(renderChain)
417
-
418
- // Prune (unless deep), compress (unless full), and render each bucket (buckets
419
- // sorted so a consumer's chains group together; bare '' sorts first).
267
+ // Buckets sorted, so bare '' first.
420
268
  const byPkg = new Map()
421
269
  for (const [key, buckets] of acc) {
422
270
  const lines = []
423
271
  for (const bucket of [...buckets.keys()].toSorted((a, b) => a.localeCompare(b))) {
424
272
  let chains = [...buckets.get(bucket).values()]
425
273
  if (!deep) chains = dropSuffixed(chains)
426
- for (const rendered of (full ? renderFull(chains) : compressChains(chains))) {
274
+ for (const rendered of (full ? orderChains(chains).map(renderChain) : compressChains(chains))) {
427
275
  lines.push(bucket ? `${bucket}: ${rendered}` : rendered)
428
276
  }
429
277
  }