npm-dependency-visualizer 0.0.0-stage → 0.1.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.
package/src/render.js ADDED
@@ -0,0 +1,227 @@
1
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0
2
+
3
+ const focusLegend = 'Focus (Sunset Boulevard): coral nodes with thick borders are matches; warm-sand nodes are ancestors; thick burnt-orange arrows trace the ancestor subgraph. Unrelated branches keep their normal style.'
4
+
5
+ function compareNodes(a, b) {
6
+ const aLocation = a.kind === 'placeholder' ? a.parent : a.location
7
+ const bLocation = b.kind === 'placeholder' ? b.parent : b.location
8
+ return compare(aLocation, bLocation) ||
9
+ compare(a.kind === 'placeholder' ? '1' : '0', b.kind === 'placeholder' ? '1' : '0') ||
10
+ compare(a.installationName, b.installationName) ||
11
+ compare(a.role ?? '', b.role ?? '')
12
+ }
13
+
14
+ function nodeName(node) {
15
+ if (node.kind === 'placeholder') return node.installationName
16
+ if (node.kind === 'root') return node.actualName
17
+ if (node.kind === 'workspace') return `${node.actualName} (workspace)`
18
+ if (node.actualName && node.actualName !== node.installationName) {
19
+ return `${node.installationName} (package ${node.actualName})`
20
+ }
21
+ if (node.aliasRequested && !node.actualName) {
22
+ return `${node.installationName} (package name not recorded)`
23
+ }
24
+ return node.installationName
25
+ }
26
+
27
+ function nodeLocation(node) {
28
+ if (node.kind === 'root') return '(root)'
29
+ if (node.kind === 'placeholder') {
30
+ return `not recorded; declared by ${node.parent || '(root)'} (${node.role})`
31
+ }
32
+ return node.location
33
+ }
34
+
35
+ function labelsAndIds(graph) {
36
+ const nodes = [...graph.nodes.values()].sort(compareNodes)
37
+ const labels = new Map()
38
+ const labelCounts = new Map()
39
+
40
+ for (const node of nodes) {
41
+ const label = node.kind === 'placeholder'
42
+ ? `${nodeName(node)} (${node.status})`
43
+ : node.kind === 'workspace'
44
+ ? `${node.actualName}@${node.version || 'version not recorded'} (workspace)`
45
+ : `${nodeName(node)}@${node.version || 'version not recorded'}`
46
+ labels.set(node.key, label)
47
+ labelCounts.set(label, (labelCounts.get(label) ?? 0) + 1)
48
+ }
49
+
50
+ const ids = new Map()
51
+ nodes.forEach((node, index) => {
52
+ ids.set(node.key, `n${index}`)
53
+ if (labelCounts.get(labels.get(node.key)) > 1) {
54
+ labels.set(node.key, `${labels.get(node.key)} [${nodeLocation(node)}]`)
55
+ }
56
+ })
57
+ return { ids, labels }
58
+ }
59
+
60
+ function mermaidText(value) {
61
+ return [...String(value)].map(character => {
62
+ const code = character.codePointAt(0)
63
+ return code < 32 || code === 127 || code === 0x2028 || code === 0x2029 || '#"&<>|[]`\\%'.includes(character)
64
+ ? `#${code};`
65
+ : character
66
+ }).join('')
67
+ }
68
+
69
+ function markdownText(value) {
70
+ const characters = [...String(value)]
71
+ return characters.map((character, index) => {
72
+ const code = character.codePointAt(0)
73
+ const urlColon = character === ':' && characters[index + 1] === '/' && characters[index + 2] === '/'
74
+ const wwwDot = character === '.' && characters.slice(Math.max(0, index - 3), index).join('').toLowerCase() === 'www'
75
+ return code < 32 || code === 127 || code === 0x2028 || code === 0x2029 ||
76
+ '&<>\\|`*_[\\]#!@'.includes(character) || urlColon || wwwDot
77
+ ? `&#${code};`
78
+ : character
79
+ }).join('')
80
+ }
81
+
82
+ function commentText(value) {
83
+ return [...String(value)].map(character => {
84
+ const code = character.codePointAt(0)
85
+ if (code < 32 || code === 127 || code === 0x2028 || code === 0x2029 || '%`\\<>'.includes(character)) {
86
+ return `\\u${code.toString(16).padStart(4, '0')}`
87
+ }
88
+ return character
89
+ }).join('')
90
+ }
91
+
92
+ function summary(view) {
93
+ const { graph } = view
94
+ const developmentOwners = graph.workspaces === null ? 'root' : 'root and workspace'
95
+ const selection = graph.includeDev
96
+ ? `production, optional, peer, and ${developmentOwners} development dependencies`
97
+ : 'production, optional, and peer dependencies'
98
+ const focus = view.focus === undefined ? 'none' : view.focus
99
+ const depth = view.depth === undefined ? 'unlimited' : String(view.depth)
100
+ const lines = [
101
+ `Inputs: package.json, package-lock.json; lockfile version ${graph.lockfileVersion}.`,
102
+ `Dependency selection: ${selection}.`,
103
+ `Filters: focus ${focus}; depth ${depth}.`,
104
+ `Displayed: ${view.nodes.length} nodes, ${view.edges.length} relationships.`,
105
+ `Omitted by filters: ${view.omittedNodes} nodes, ${view.omittedEdges} relationships.`,
106
+ `Excluded boundaries: ${graph.excludedBoundaries.length} relationships; excluded non-node_modules project records: ${graph.excludedProjectRecords}.`,
107
+ ]
108
+ if (graph.workspaces?.entryPoints) {
109
+ lines.push(`Workspaces: included; all ${graph.workspaces.declared} workspace projects are entry points, without root edges, because --include-dev follows every workspace's development dependencies.`)
110
+ } else if (graph.workspaces !== null) {
111
+ lines.push(`Workspaces: included; reached ${graph.workspaces.reached} of ${graph.workspaces.declared} workspace projects.`)
112
+ } else if (graph.workspacesExcluded) {
113
+ lines.push('Workspaces: excluded by --no-workspaces.')
114
+ }
115
+ if (graph.root.kind === 'workspace') {
116
+ lines.push(`Start node: workspace ${graph.root.actualName} at ${graph.root.location}.`)
117
+ }
118
+ if (view.focus !== undefined) {
119
+ lines.push(`Focus mode: ${view.focusMode}; matching instances: ${view.matchCount}.`)
120
+ }
121
+ if (view.hiddenMatches) {
122
+ lines.push(`Matching instances hidden by depth: ${view.hiddenMatches} of ${view.matchCount}.`)
123
+ }
124
+ return lines
125
+ }
126
+
127
+ function edgeLabel(edge) {
128
+ const role = edge.role === 'peer' && edge.optional ? 'optional peer' : edge.role
129
+ return `${role}: ${edge.name} @ ${edge.spec}`
130
+ }
131
+
132
+ function renderDiagram(view, ids, labels) {
133
+ const lines = ['flowchart LR']
134
+ const nodes = [...view.nodes].sort(compareNodes)
135
+ for (const node of nodes) {
136
+ const [open, close] = node.kind === 'workspace' ? ['[[', ']]'] : ['[', ']']
137
+ lines.push(` ${ids.get(node.key)}${open}"${mermaidText(labels.get(node.key))}"${close}`)
138
+ }
139
+
140
+ const edges = [...view.edges].sort((a, b) =>
141
+ compare(a.source, b.source) ||
142
+ compare(a.target, b.target) ||
143
+ compare(a.name, b.name) ||
144
+ compare(a.role, b.role) ||
145
+ compare(a.spec, b.spec))
146
+ for (const edge of edges) {
147
+ lines.push(` ${ids.get(edge.source)} -->|"${mermaidText(edgeLabel(edge))}"| ${ids.get(edge.target)}`)
148
+ }
149
+ if (view.focus !== undefined) {
150
+ lines.push(
151
+ ' classDef focusMatch fill:#f4a261,stroke:#264653,color:#264653,stroke-width:3px,font-family:DejaVu Sans',
152
+ ' classDef focusAncestor fill:#e9c46a,stroke:#264653,color:#264653,stroke-width:1.5px,font-family:DejaVu Sans',
153
+ )
154
+ for (const node of nodes) {
155
+ if (view.matchedNodes.has(node.key)) {
156
+ lines.push(` class ${ids.get(node.key)} focusMatch`)
157
+ } else if (view.focusNodes.has(node.key)) {
158
+ lines.push(` class ${ids.get(node.key)} focusAncestor`)
159
+ }
160
+ }
161
+ const highlightedEdges = edges.flatMap((edge, index) => view.focusEdges.has(edge) ? [index] : [])
162
+ if (highlightedEdges.length) {
163
+ lines.push(` linkStyle ${highlightedEdges.join(',')} stroke:#e76f51,stroke-width:3px`)
164
+ }
165
+ }
166
+ return lines.join('\n')
167
+ }
168
+
169
+ export function renderReport(view) {
170
+ const { graph } = view
171
+ const { ids, labels } = labelsAndIds(graph)
172
+ const diagram = renderDiagram(view, ids, labels)
173
+
174
+ const lines = [
175
+ `# Dependency graph: ${markdownText(graph.root.actualName)}`,
176
+ '',
177
+ ...summary(view).map(line => `- ${markdownText(line)}`),
178
+ '',
179
+ ]
180
+ if (graph.diagnostics.length) {
181
+ lines.push('## Warnings', '')
182
+ for (const diagnostic of graph.diagnostics) {
183
+ lines.push(`- ${markdownText(`${diagnostic.code}: ${diagnostic.message}`)}`)
184
+ }
185
+ lines.push('')
186
+ }
187
+
188
+ lines.push(
189
+ '## Legend',
190
+ '',
191
+ '- Arrows point from the declaring package to its resolved dependency.',
192
+ '- Node versions are selected versions; edge labels show the dependency role, declared name, and original specification.',
193
+ '- `prod`, `dev`, `optional`, `peer`, and `optional peer` identify dependency roles.',
194
+ '- Unresolved and unrecorded optional dependencies have placeholder nodes.',
195
+ ...(graph.workspaces === null ? [] : ['- Workspace projects use double-bordered (subroutine) nodes labeled `(workspace)`.']),
196
+ ...(view.focus === undefined ? [] : [`- ${focusLegend}`, '- The node index identifies matches and ancestors without relying on color.']),
197
+ '',
198
+ '## Dependency graph',
199
+ '',
200
+ '```mermaid',
201
+ diagram,
202
+ '```',
203
+ '',
204
+ '## Node index',
205
+ '',
206
+ view.focus === undefined
207
+ ? '| ID | Name | Selected version | Lockfile location |'
208
+ : '| ID | Name | Selected version | Lockfile location | Focus |',
209
+ view.focus === undefined
210
+ ? '| --- | --- | --- | --- |'
211
+ : '| --- | --- | --- | --- | --- |',
212
+ )
213
+
214
+ for (const node of [...view.nodes].sort(compareNodes)) {
215
+ const fields = [ids.get(node.key), nodeName(node), node.version || 'not recorded', nodeLocation(node)]
216
+ if (view.focus !== undefined) {
217
+ fields.push(view.matchedNodes.has(node.key) ? 'Match' : view.focusNodes.has(node.key) ? 'Ancestor' : 'Unrelated')
218
+ }
219
+ lines.push(`| ${fields.map(markdownText).join(' | ')} |`)
220
+ }
221
+ return `${lines.join('\n')}\n`
222
+ }
223
+
224
+ export function formatDiagnostic(diagnostic) {
225
+ const message = commentText(diagnostic.message)
226
+ return `${diagnostic.severity} [${diagnostic.code}]: ${message}`
227
+ }
package/src/select.js ADDED
@@ -0,0 +1,66 @@
1
+ import { InputError } from './errors.js'
2
+
3
+ export function selectView(graph, { focus, focusMode = 'highlight', depth } = {}) {
4
+ let selected = new Set(graph.nodes.keys())
5
+ const matchedNodes = new Set()
6
+ const focusNodes = new Set()
7
+
8
+ if (focus !== undefined) {
9
+ for (const edge of graph.edges) {
10
+ if (edge.name === focus) matchedNodes.add(edge.target)
11
+ }
12
+ if (!matchedNodes.size) {
13
+ throw new InputError(`No reachable dependency named ${JSON.stringify(focus)}`)
14
+ }
15
+
16
+ const queue = [...matchedNodes]
17
+ for (const key of matchedNodes) focusNodes.add(key)
18
+ for (let cursor = 0; cursor < queue.length; cursor++) {
19
+ for (const edge of graph.incoming.get(queue[cursor])) {
20
+ if (!focusNodes.has(edge.source)) {
21
+ focusNodes.add(edge.source)
22
+ queue.push(edge.source)
23
+ }
24
+ }
25
+ }
26
+ if (focusMode === 'filter') selected = new Set(focusNodes)
27
+ }
28
+
29
+ const focusEdges = new Set(graph.edges.filter(edge => focusNodes.has(edge.source) && focusNodes.has(edge.target)))
30
+
31
+ if (depth !== undefined) {
32
+ const withinDepth = new Set(graph.entryKeys)
33
+ const queue = graph.entryKeys.map(key => ({ key, distance: 0 }))
34
+ for (let cursor = 0; cursor < queue.length; cursor++) {
35
+ const { key, distance } = queue[cursor]
36
+ if (distance >= depth) continue
37
+ for (const edge of graph.outgoing.get(key)) {
38
+ if (selected.has(edge.target) && !withinDepth.has(edge.target)) {
39
+ withinDepth.add(edge.target)
40
+ queue.push({ key: edge.target, distance: distance + 1 })
41
+ }
42
+ }
43
+ }
44
+ selected = withinDepth
45
+ }
46
+
47
+ const nodes = [...graph.nodes.values()].filter(node => selected.has(node.key))
48
+ const edges = graph.edges.filter(edge => selected.has(edge.source) && selected.has(edge.target))
49
+ const hiddenMatches = [...matchedNodes].filter(key => !selected.has(key)).length
50
+
51
+ return {
52
+ graph,
53
+ nodes,
54
+ edges,
55
+ focus,
56
+ focusMode: focus === undefined ? undefined : focusMode,
57
+ matchedNodes,
58
+ focusNodes,
59
+ focusEdges,
60
+ depth,
61
+ matchCount: matchedNodes.size,
62
+ hiddenMatches,
63
+ omittedNodes: graph.nodes.size - nodes.length,
64
+ omittedEdges: graph.edges.length - edges.length,
65
+ }
66
+ }
@@ -0,0 +1,326 @@
1
+ import assert from 'node:assert/strict'
2
+ import { spawn, spawnSync } from 'node:child_process'
3
+ import { copyFile, link, mkdir, mkdtemp, readFile, readdir, rm, symlink, writeFile } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import { join } from 'node:path'
6
+ import { test } from 'node:test'
7
+ import { fileURLToPath, pathToFileURL } from 'node:url'
8
+ import { complexDirectory, npmCliDirectory } from '../test-support/fixtures.js'
9
+
10
+ const cli = fileURLToPath(new URL('../cli.js', import.meta.url))
11
+ const offlineGuard = fileURLToPath(new URL('../test-support/offline-guard.js', import.meta.url))
12
+
13
+ function run(args, options = {}) {
14
+ const nodeArgs = options.offline ? ['--import', pathToFileURL(offlineGuard).href, cli, ...args] : [cli, ...args]
15
+ return spawnSync(process.execPath, nodeArgs, {
16
+ encoding: 'utf8',
17
+ maxBuffer: 16 * 1024 * 1024,
18
+ cwd: options.cwd,
19
+ env: options.env ?? process.env,
20
+ })
21
+ }
22
+
23
+ async function temporaryDirectory(t) {
24
+ const directory = await mkdtemp(join(tmpdir(), 'npm-dependency-visualizer-'))
25
+ t.after(() => rm(directory, { recursive: true, force: true }))
26
+ return directory
27
+ }
28
+
29
+ async function copyInputs(from, to) {
30
+ for (const filename of ['package.json', 'package-lock.json']) {
31
+ await copyFile(join(from, filename), join(to, filename))
32
+ }
33
+ }
34
+
35
+ async function writeInputs(directory, manifest, packages = {}, version = 3) {
36
+ const root = structuredClone(manifest)
37
+ delete root.overrides
38
+ await writeFile(join(directory, 'package.json'), JSON.stringify(manifest))
39
+ await writeFile(join(directory, 'package-lock.json'), JSON.stringify({
40
+ lockfileVersion: version,
41
+ packages: { '': root, ...packages },
42
+ }))
43
+ }
44
+
45
+ function reverseKeys(value) {
46
+ if (Array.isArray(value)) return value.map(reverseKeys)
47
+ if (!value || typeof value !== 'object') return value
48
+ return Object.fromEntries(Object.entries(value).reverse().map(([key, child]) => [key, reverseKeys(child)]))
49
+ }
50
+
51
+ test('default CLI emits Markdown to stdout and diagnostics separately', () => {
52
+ const result = run([complexDirectory])
53
+ assert.equal(result.status, 0)
54
+ assert.match(result.stdout, /^# Dependency graph: sample-project\n/)
55
+ assert.match(result.stdout, /Displayed: 16 nodes, 20 relationships/)
56
+ assert.match(result.stdout, /```mermaid\n/)
57
+ assert.match(result.stderr, /warning \[optional-not-recorded\]/)
58
+ assert.match(result.stderr, /warning \[overrides-present\]/)
59
+ assert.doesNotMatch(result.stdout, /warning \[optional-not-recorded\]/)
60
+ assert.equal(result.stdout.includes('\r'), false)
61
+ assert.equal(result.stdout.endsWith('\n'), true)
62
+ })
63
+
64
+ test('output is always Markdown, including development roles', () => {
65
+ const markdown = run([complexDirectory, '--include-dev', '--focus', 'shared'])
66
+ assert.equal(markdown.status, 0)
67
+ assert.match(markdown.stdout, /^# Dependency graph:/)
68
+ assert.match(markdown.stdout, /Filters: focus shared/)
69
+ assert.match(markdown.stdout, /```mermaid\nflowchart LR\n/)
70
+ const removed = run([complexDirectory, '--format', 'mermaid'])
71
+ assert.equal(removed.status, 1)
72
+ assert.equal(removed.stdout, '')
73
+ assert.match(removed.stderr, /format/)
74
+
75
+ const full = run([complexDirectory, '--include-dev'])
76
+ assert.match(full.stdout, /Displayed: 18 nodes, 23 relationships/)
77
+ assert.match(full.stdout, /dev: both @ \^1\.0\.0/)
78
+ })
79
+
80
+ test('equivalent JSON key orders produce byte-identical output', async t => {
81
+ const directory = await temporaryDirectory(t)
82
+ for (const filename of ['package.json', 'package-lock.json']) {
83
+ const original = JSON.parse(await readFile(join(complexDirectory, filename), 'utf8'))
84
+ await writeFile(join(directory, filename), JSON.stringify(reverseKeys(original), null, 2))
85
+ }
86
+ const original = run([complexDirectory])
87
+ const reordered = run([directory])
88
+ const repeated = run([directory])
89
+ assert.equal(original.status, 0)
90
+ assert.equal(reordered.status, 0)
91
+ assert.equal(original.stdout, reordered.stdout)
92
+ assert.equal(reordered.stdout, repeated.stdout)
93
+ assert.equal(original.stderr, reordered.stderr)
94
+ for (const mode of ['highlight', 'filter']) {
95
+ const args = ['--focus', 'shared', '--focus-mode', mode]
96
+ assert.equal(run([complexDirectory, ...args]).stdout, run([directory, ...args]).stdout)
97
+ }
98
+ })
99
+
100
+ test('npm/cli focus preserves the whole graph unless filter mode or depth is requested', () => {
101
+ const full = run([npmCliDirectory])
102
+ assert.equal(full.status, 0)
103
+ assert.match(full.stdout, /Displayed: 149 nodes, 359 relationships/)
104
+ assert.match(full.stdout, /Omitted by filters: 0 nodes, 0 relationships/)
105
+ assert.match(full.stdout, /Workspaces: included; reached 12 of 16 workspace projects\./)
106
+ assert.match(full.stdout, /\[\["@npmcli\/arborist@10\.0\.4 \(workspace\)"\]\]/)
107
+ assert.doesNotMatch(full.stderr, /workspace-excluded/)
108
+
109
+ const excluded = run([npmCliDirectory, '--no-workspaces'])
110
+ assert.equal(excluded.status, 0)
111
+ assert.match(excluded.stdout, /Displayed: 125 nodes, 255 relationships/)
112
+ assert.match(excluded.stderr, /workspace-excluded/)
113
+ assert.match(excluded.stderr, /@npmcli\/arborist/)
114
+
115
+ const arborist = run([npmCliDirectory, '--workspace', '@npmcli/arborist'])
116
+ assert.equal(arborist.status, 0)
117
+ assert.match(arborist.stdout, /# Dependency graph: &#64;npmcli\/arborist/)
118
+ assert.match(arborist.stdout, /Start node: workspace &#64;npmcli\/arborist at workspaces\/arborist\./)
119
+ assert.equal(run([npmCliDirectory, '--workspace', 'nope']).status, 1)
120
+ assert.equal(run([npmCliDirectory, '--workspace', 'docs', '--no-workspaces']).status, 1)
121
+ assert.doesNotMatch(full.stdout, /[A-Za-z]:[\\/]/)
122
+
123
+ const focused = run([npmCliDirectory, '--focus', 'glob'])
124
+ assert.equal(focused.status, 0)
125
+ assert.match(focused.stdout, /Displayed: 149 nodes, 359 relationships/)
126
+ assert.match(focused.stdout, /Omitted by filters: 0 nodes, 0 relationships/)
127
+ assert.match(focused.stdout, /Focus mode: highlight; matching instances: 1/)
128
+ assert.match(focused.stdout, /glob@13\.0\.6/)
129
+ assert.match(focused.stdout, /class n\d+ focusMatch/)
130
+ assert.match(focused.stdout, /linkStyle [\d,]+ stroke:/)
131
+ assert.equal(run([npmCliDirectory, '--focus', 'glob', '--focus-mode', 'highlight']).stdout, focused.stdout)
132
+
133
+ const limited = run([npmCliDirectory, '--focus', 'glob', '--depth', '2'])
134
+ assert.equal(limited.status, 0)
135
+ assert.match(limited.stdout, /Filters: focus glob; depth 2/)
136
+ assert.match(limited.stdout, /Omitted by filters: [1-9]\d* nodes/)
137
+
138
+ const filtered = run([npmCliDirectory, '--focus', 'glob', '--focus-mode', 'filter', '--depth', '2'])
139
+ assert.equal(filtered.status, 0)
140
+ assert.match(filtered.stdout, /Focus mode: filter/)
141
+ assert.match(filtered.stdout, /Displayed: 26 nodes, 68 relationships/)
142
+ const filteredWithoutWorkspaces = run([npmCliDirectory, '--no-workspaces', '--focus', 'glob', '--focus-mode', 'filter', '--depth', '2'])
143
+ assert.match(filteredWithoutWorkspaces.stdout, /Displayed: 14 nodes, 29 relationships/)
144
+ })
145
+
146
+ test('invalid arguments, malformed input, unsupported versions, and unmatched focus fail without a report', async t => {
147
+ for (const args of [
148
+ [complexDirectory, '--depth', '-1'],
149
+ [complexDirectory, '--depth', '1.5'],
150
+ [complexDirectory, '--focus', 'not-here'],
151
+ [complexDirectory, '--focus', 'shared', '--focus-mode', 'invalid'],
152
+ [complexDirectory, '--focus', 'shared', '--focus-mode', ''],
153
+ [complexDirectory, '--focus-mode', 'filter'],
154
+ [complexDirectory, '--focus-mode', 'highlight'],
155
+ [complexDirectory, '--unknown'],
156
+ ]) {
157
+ const result = run(args)
158
+ assert.equal(result.status, 1, args.join(' '))
159
+ assert.equal(result.stdout, '')
160
+ assert.match(result.stderr, /error:/)
161
+ }
162
+
163
+ const directory = await temporaryDirectory(t)
164
+ let result = run([directory])
165
+ assert.equal(result.status, 1)
166
+ assert.equal(result.stdout, '')
167
+ assert.match(result.stderr, /Cannot read package/)
168
+
169
+ await writeFile(join(directory, 'package.json'), '{')
170
+ await writeFile(join(directory, 'package-lock.json'), '{}')
171
+ result = run([directory])
172
+ assert.equal(result.status, 1)
173
+ assert.match(result.stderr, /Cannot parse package\.json/)
174
+
175
+ await writeInputs(directory, { name: 'empty', version: '1' }, {}, 1)
176
+ result = run([directory])
177
+ assert.equal(result.status, 1)
178
+ assert.match(result.stderr, /Unsupported lockfileVersion 1/)
179
+
180
+ await writeInputs(directory, { name: 'empty', version: '1', dependencies: { dep: '^1' } })
181
+ const lockfile = JSON.parse(await readFile(join(directory, 'package-lock.json'), 'utf8'))
182
+ lockfile.packages[''].dependencies.dep = '^2'
183
+ await writeFile(join(directory, 'package-lock.json'), JSON.stringify(lockfile))
184
+ result = run([directory])
185
+ assert.equal(result.status, 1)
186
+ assert.match(result.stderr, /dependencies\["dep"\]/)
187
+ })
188
+
189
+ test('dependency-free projects generate a root-only graph', async t => {
190
+ const directory = await temporaryDirectory(t)
191
+ await writeInputs(directory, { name: 'empty', version: '1.0.0' })
192
+ const result = run([directory])
193
+ assert.equal(result.status, 0)
194
+ assert.equal(result.stderr, '')
195
+ assert.match(result.stdout, /Displayed: 1 nodes, 0 relationships/)
196
+ assert.match(result.stdout, /empty@1\.0\.0/)
197
+ })
198
+
199
+ test('offline execution ignores node_modules and leaves inputs and npm cache unchanged', async t => {
200
+ const directory = await temporaryDirectory(t)
201
+ await copyInputs(complexDirectory, directory)
202
+ const files = ['package.json', 'package-lock.json']
203
+ const before = await Promise.all(files.map(name => readFile(join(directory, name))))
204
+ const cache = join(directory, 'isolated-cache')
205
+ const env = { ...process.env, npm_config_cache: cache }
206
+ const baseline = run([directory], { env, offline: true })
207
+ assert.equal(baseline.status, 0, baseline.stderr)
208
+
209
+ await mkdir(join(directory, 'node_modules', 'unrelated'), { recursive: true })
210
+ await writeFile(join(directory, 'node_modules', 'unrelated', 'package.json'), '{"name":"unrelated"}')
211
+ await mkdir(join(directory, 'unrelated-workspace'))
212
+ await writeFile(join(directory, 'unrelated-workspace', 'package.json'), '{"name":"workspace"}')
213
+ const withLocalFiles = run([directory], { env, offline: true })
214
+ assert.equal(withLocalFiles.status, 0, withLocalFiles.stderr)
215
+ assert.equal(withLocalFiles.stdout, baseline.stdout)
216
+ assert.equal(withLocalFiles.stderr, baseline.stderr)
217
+ for (let index = 0; index < files.length; index++) {
218
+ assert.deepEqual(await readFile(join(directory, files[index])), before[index])
219
+ }
220
+ assert.equal((await readdir(directory)).includes('isolated-cache'), false)
221
+ })
222
+
223
+ test('output replacement protects inputs, hard links, existing files, and temporary files', async t => {
224
+ const directory = await temporaryDirectory(t)
225
+ await copyInputs(complexDirectory, directory)
226
+ const manifestPath = join(directory, 'package.json')
227
+ const lockfilePath = join(directory, 'package-lock.json')
228
+ const manifestBefore = await readFile(manifestPath)
229
+ const lockfileBefore = await readFile(lockfilePath)
230
+ const output = join(directory, 'report.md')
231
+ await writeFile(output, 'prior report')
232
+
233
+ let result = run([directory, '--output', output, '--focus', 'not-here'])
234
+ assert.equal(result.status, 1)
235
+ assert.equal(await readFile(output, 'utf8'), 'prior report')
236
+
237
+ for (const input of [manifestPath, lockfilePath]) {
238
+ result = run([directory, '--output', input])
239
+ assert.equal(result.status, 1)
240
+ assert.match(result.stderr, /Output must not overwrite/)
241
+ }
242
+ const alias = join(directory, 'hardlink.json')
243
+ await link(manifestPath, alias)
244
+ result = run([directory, '--output', alias])
245
+ assert.equal(result.status, 1)
246
+ assert.match(result.stderr, /Output must not overwrite/)
247
+ assert.deepEqual(await readFile(manifestPath), manifestBefore)
248
+ assert.deepEqual(await readFile(lockfilePath), lockfileBefore)
249
+
250
+ const outputDirectory = join(directory, 'output-directory')
251
+ await mkdir(outputDirectory)
252
+ result = run([directory, '--output', outputDirectory])
253
+ assert.equal(result.status, 1)
254
+ assert.deepEqual(await readdir(outputDirectory), [])
255
+ assert.equal((await readdir(directory)).some(name => name.startsWith('.output-directory.') && name.endsWith('.tmp')), false)
256
+
257
+ result = run([directory, '--output', output])
258
+ assert.equal(result.status, 0)
259
+ assert.equal(result.stdout, '')
260
+ assert.match(await readFile(output, 'utf8'), /^# Dependency graph: sample-project/)
261
+ assert.deepEqual(await readFile(manifestPath), manifestBefore)
262
+ assert.deepEqual(await readFile(lockfilePath), lockfileBefore)
263
+ })
264
+
265
+ test('output paths resolving through a symlink cannot overwrite an input', async t => {
266
+ const directory = await temporaryDirectory(t)
267
+ await copyInputs(complexDirectory, directory)
268
+ const manifest = join(directory, 'package.json')
269
+ const alias = join(directory, 'alias.json')
270
+ try {
271
+ await symlink(manifest, alias, 'file')
272
+ } catch (error) {
273
+ if (error.code === 'EPERM' || error.code === 'EACCES' || error.code === 'ENOTSUP') {
274
+ t.skip(`File symlinks are unavailable: ${error.code}`)
275
+ return
276
+ }
277
+ throw error
278
+ }
279
+ const before = await readFile(manifest)
280
+ const result = run([directory, '--output', alias])
281
+ assert.equal(result.status, 1)
282
+ assert.match(result.stderr, /Output must not overwrite/)
283
+ assert.deepEqual(await readFile(manifest), before)
284
+ })
285
+
286
+ test('diagnostic reports replace output files and retain errors outside the filtered view', async t => {
287
+ const directory = await temporaryDirectory(t)
288
+ await writeInputs(directory, { name: 'broken', version: '1', dependencies: { missing: '^1' } })
289
+ const output = join(directory, 'report.md')
290
+ await writeFile(output, 'old')
291
+ const result = run([directory, '--depth', '0', '--output', output])
292
+ assert.equal(result.status, 2)
293
+ assert.equal(result.stdout, '')
294
+ assert.match(result.stderr, /error \[dependency-unresolved\]/)
295
+ const report = await readFile(output, 'utf8')
296
+ assert.match(report, /Displayed: 1 nodes, 0 relationships/)
297
+ assert.match(report, /dependency-unresolved/)
298
+ assert.doesNotMatch(report, /^old$/)
299
+ })
300
+
301
+ test('a closed stdout pipe produces an output error and exit code 1', async () => {
302
+ const child = spawn(process.execPath, [cli, npmCliDirectory, '--include-dev'], {
303
+ stdio: ['ignore', 'pipe', 'pipe'],
304
+ })
305
+ let stderr = ''
306
+ child.stderr.setEncoding('utf8')
307
+ child.stderr.on('data', chunk => { stderr += chunk })
308
+ child.stdout.destroy()
309
+ const status = await new Promise((resolve, reject) => {
310
+ child.once('error', reject)
311
+ child.once('close', resolve)
312
+ })
313
+ assert.equal(status, 1, stderr)
314
+ assert.match(stderr, /error:.*(?:EPIPE|write)/i)
315
+ })
316
+
317
+ test('help and version work without project input files', async t => {
318
+ const directory = await temporaryDirectory(t)
319
+ const help = run(['--help'], { cwd: directory })
320
+ assert.equal(help.status, 0)
321
+ assert.match(help.stdout, /--focus <name>/)
322
+ assert.match(help.stdout, /--focus-mode <mode>/)
323
+ const version = run(['--version'], { cwd: directory })
324
+ assert.equal(version.status, 0)
325
+ assert.match(version.stdout, /^\d+\.\d+\.\d+\n$/)
326
+ })