@exodus/stasis 1.0.0-beta.15 → 1.0.0-beta.17

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