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.
@@ -0,0 +1,141 @@
1
+ import assert from 'node:assert/strict'
2
+ import { JSDOM } from 'jsdom'
3
+ import { marked } from 'marked'
4
+ import { test } from 'node:test'
5
+ import { buildGraph } from '../src/graph.js'
6
+ import { readInputs } from '../src/input.js'
7
+ import { renderReport } from '../src/render.js'
8
+ import { selectView } from '../src/select.js'
9
+ import { complexDirectory, makeInputs, npmCliDirectory } from '../test-support/fixtures.js'
10
+
11
+ const dom = new JSDOM('<!doctype html><html><body></body></html>')
12
+ globalThis.window = dom.window
13
+ globalThis.document = dom.window.document
14
+ const { default: mermaid } = await import('mermaid')
15
+ mermaid.initialize({ startOnLoad: false, securityLevel: 'strict' })
16
+
17
+ function diagramOf(view) {
18
+ const diagrams = marked.lexer(renderReport(view)).filter(token => token.type === 'code' && token.lang === 'mermaid')
19
+ assert.equal(diagrams.length, 1)
20
+ return diagrams[0].text
21
+ }
22
+
23
+ async function assertParses(view) {
24
+ const markdown = renderReport(view)
25
+ const tokens = marked.lexer(markdown)
26
+ const diagrams = tokens.filter(token => token.type === 'code' && token.lang === 'mermaid')
27
+ assert.equal(diagrams.length, 1)
28
+ assert.equal((await mermaid.parse(diagrams[0].text)).diagramType, 'flowchart-v2')
29
+ const parsed = await mermaid.mermaidAPI.getDiagramFromText(diagrams[0].text)
30
+ assert.equal(parsed.db.getVertices().size, view.nodes.length)
31
+ assert.equal(parsed.db.getEdges().length, view.edges.length)
32
+ assert.equal(tokens.filter(token => token.type === 'table').length, 1)
33
+ return markdown
34
+ }
35
+
36
+ test('the Markdown Mermaid block parses with the same nodes and edges', async () => {
37
+ const graph = buildGraph(await readInputs(complexDirectory))
38
+ await assertParses(selectView(graph))
39
+ await assertParses(selectView(graph, { focus: 'shared', depth: 2 }))
40
+ await assertParses(selectView(graph, { focus: 'shared', focusMode: 'filter', depth: 2 }))
41
+ const rootOnly = selectView(graph, { depth: 0 })
42
+ await assertParses(rootOnly)
43
+ })
44
+
45
+ test('the representative full and focused npm/cli graphs parse', async () => {
46
+ const graph = buildGraph(await readInputs(npmCliDirectory))
47
+ await assertParses(selectView(graph))
48
+ await assertParses(selectView(graph, { focus: 'glob' }))
49
+ await assertParses(selectView(graph, { focus: 'glob', focusMode: 'filter', depth: 2 }))
50
+ const parsed = await mermaid.mermaidAPI.getDiagramFromText(diagramOf(selectView(graph)))
51
+ const subroutines = [...parsed.db.getVertices().values()].filter(vertex => vertex.type === 'subroutine')
52
+ assert.equal(subroutines.length, 12)
53
+
54
+ const withDev = selectView(buildGraph(await readInputs(npmCliDirectory), { includeDev: true }), { depth: 1 })
55
+ await assertParses(withDev)
56
+ const devParsed = await mermaid.mermaidAPI.getDiagramFromText(diagramOf(withDev))
57
+ assert.equal([...devParsed.db.getVertices().values()].filter(vertex => vertex.type === 'subroutine').length, 16)
58
+ })
59
+
60
+ test('focus styles apply to matches and only ancestor edges in final Mermaid edge order', async () => {
61
+ const graph = buildGraph(await readInputs(complexDirectory))
62
+ for (const options of [
63
+ { focus: 'shared' },
64
+ { focus: 'shared', depth: 2 },
65
+ { focus: 'shared', focusMode: 'filter' },
66
+ { focus: 'shared', focusMode: 'filter', depth: 1 },
67
+ { focus: 'shared', depth: 0 },
68
+ ]) {
69
+ const view = selectView(graph, options)
70
+ const markdown = await assertParses(view)
71
+ const parsed = await mermaid.mermaidAPI.getDiagramFromText(diagramOf(view))
72
+ const vertices = parsed.db.getVertices()
73
+ const ancestorLabels = new Set([
74
+ 'sample-project@1.0.0', 'a@1.1.0', 'b@2.1.0', 'cycle@1.0.0', 'deep@2.3.0',
75
+ ])
76
+ let matches = 0
77
+ for (const vertex of vertices.values()) {
78
+ if (vertex.text.startsWith('shared@')) {
79
+ assert.deepEqual(vertex.classes, ['focusMatch'])
80
+ matches++
81
+ } else {
82
+ assert.deepEqual(vertex.classes, ancestorLabels.has(vertex.text) ? ['focusAncestor'] : [])
83
+ }
84
+ }
85
+ assert.equal(matches, view.matchCount - view.hiddenMatches)
86
+ for (const edge of parsed.db.getEdges()) {
87
+ const onPath = vertices.get(edge.start).classes.length && vertices.get(edge.end).classes.length
88
+ assert.deepEqual(edge.style ?? [], onPath ? ['stroke:#e76f51', 'stroke-width:3px', 'fill:none'] : [])
89
+ }
90
+ assert.match(markdown, /\| Lockfile location \| Focus \|/)
91
+ if (matches) assert.match(markdown, /\| Match \|/)
92
+ if (!view.edges.length) assert.doesNotMatch(diagramOf(view), /linkStyle/)
93
+ }
94
+ })
95
+
96
+ test('no focus leaves all nodes and edges unstyled', async () => {
97
+ const graph = buildGraph(await readInputs(complexDirectory))
98
+ const view = selectView(graph)
99
+ const report = diagramOf(view)
100
+ assert.doesNotMatch(report, /classDef|^\s+class |linkStyle/m)
101
+ const parsed = await mermaid.mermaidAPI.getDiagramFromText(report)
102
+ for (const vertex of parsed.db.getVertices().values()) assert.deepEqual(vertex.classes, [])
103
+ for (const edge of parsed.db.getEdges()) assert.equal(edge.style, undefined)
104
+ })
105
+
106
+ test('untrusted labels cannot create Markdown links, HTML, fences, or Mermaid directives', async () => {
107
+ const manifest = {
108
+ name: 'root"]\n```mermaid\nclick n0 href "https://evil.invalid"\n<script>alert(1)</script> www.example.invalid user@example.invalid\u2028',
109
+ version: '1.0.0',
110
+ dependencies: {
111
+ unsafe: 'https://example.invalid/a.tgz?x=1|2&y=3#v1"\n```\n%%{init: {"securityLevel":"loose"}}%% <script>alert(2)</script>',
112
+ },
113
+ }
114
+ const graph = buildGraph(makeInputs(manifest, {
115
+ 'node_modules/unsafe': { name: 'name|`[]<&>@example.com', version: '2.0.0' },
116
+ }))
117
+ const markdown = await assertParses(selectView(graph))
118
+ const html = marked.parse(markdown)
119
+ const document = new JSDOM(html).window.document
120
+ assert.equal(document.querySelectorAll('a, script, iframe, img').length, 0)
121
+ assert.match(document.body.textContent, /www\.example\.invalid user@example\.invalid/)
122
+ assert.equal(markdown.match(/^```/gm).length, 2)
123
+ assert.doesNotMatch(markdown, /<script/i)
124
+ assert.doesNotMatch(diagramOf(selectView(graph)), /%%\{/)
125
+ })
126
+
127
+ test('node IDs remain stable when changing only view filters', async () => {
128
+ const graph = buildGraph(await readInputs(complexDirectory))
129
+ const all = diagramOf(selectView(graph))
130
+ const lines = input => input.split('\n').filter(line => /^\s+n\d+\["/.test(line))
131
+ const allLines = new Set(lines(all))
132
+ for (const options of [
133
+ { focus: 'shared' },
134
+ { focus: 'shared', focusMode: 'filter' },
135
+ { focus: 'shared', focusMode: 'filter', depth: 1 },
136
+ { depth: 1 },
137
+ ]) {
138
+ const focused = diagramOf(selectView(graph, options))
139
+ for (const line of lines(focused)) assert.equal(allLines.has(line), true, line)
140
+ }
141
+ })
@@ -0,0 +1,32 @@
1
+ import assert from 'node:assert/strict'
2
+ import fs from 'node:fs/promises'
3
+ import { syncBuiltinESMExports } from 'node:module'
4
+ import { tmpdir } from 'node:os'
5
+ import { join } from 'node:path'
6
+ import { test } from 'node:test'
7
+
8
+ test('temporary output is removed even if writing and closing both fail', async () => {
9
+ const directory = await fs.mkdtemp(join(tmpdir(), 'npm-dependency-output-'))
10
+ const originalOpen = fs.open
11
+ fs.open = async (...args) => {
12
+ const handle = await originalOpen(...args)
13
+ return {
14
+ async writeFile() { throw new Error('simulated write failure') },
15
+ async close() {
16
+ await handle.close()
17
+ throw new Error('simulated close failure')
18
+ },
19
+ }
20
+ }
21
+ syncBuiltinESMExports()
22
+
23
+ try {
24
+ const { writeReport } = await import('../src/output.js?close-failure')
25
+ await assert.rejects(writeReport(join(directory, 'report.md'), [], 'report'), /simulated close failure/)
26
+ assert.deepEqual(await fs.readdir(directory), [])
27
+ } finally {
28
+ fs.open = originalOpen
29
+ syncBuiltinESMExports()
30
+ await fs.rm(directory, { recursive: true, force: true })
31
+ }
32
+ })
@@ -0,0 +1,19 @@
1
+ import { fileURLToPath } from 'node:url'
2
+ import { validateInputs } from '../src/input.js'
3
+
4
+ export const complexDirectory = fileURLToPath(new URL('../test/fixtures/complex/', import.meta.url))
5
+ export const npmCliDirectory = fileURLToPath(new URL('../test/fixtures/npm-cli/', import.meta.url))
6
+
7
+ export function makeInputs(manifest, packages = {}, version = 3) {
8
+ const root = structuredClone(manifest)
9
+ delete root.overrides
10
+ const lockfile = {
11
+ lockfileVersion: version,
12
+ packages: { '': root, ...packages },
13
+ }
14
+ return validateInputs(manifest, lockfile)
15
+ }
16
+
17
+ export function edge(graph, source, name, role) {
18
+ return graph.edges.find(item => item.source === source && item.name === name && item.role === role)
19
+ }
@@ -0,0 +1,25 @@
1
+ import childProcess from 'node:child_process'
2
+ import dgram from 'node:dgram'
3
+ import dns from 'node:dns'
4
+ import http from 'node:http'
5
+ import https from 'node:https'
6
+ import { syncBuiltinESMExports } from 'node:module'
7
+ import net from 'node:net'
8
+
9
+ const blocked = () => {
10
+ throw new Error('Network access and child processes are forbidden in this test')
11
+ }
12
+
13
+ for (const name of ['spawn', 'spawnSync', 'exec', 'execSync', 'execFile', 'execFileSync', 'fork']) {
14
+ childProcess[name] = blocked
15
+ }
16
+ for (const name of ['connect', 'createConnection', 'createServer']) net[name] = blocked
17
+ net.Socket.prototype.connect = blocked
18
+ for (const name of ['request', 'get']) {
19
+ http[name] = blocked
20
+ https[name] = blocked
21
+ }
22
+ for (const name of ['lookup', 'resolve', 'resolve4', 'resolve6']) dns[name] = blocked
23
+ dgram.createSocket = blocked
24
+ globalThis.fetch = blocked
25
+ syncBuiltinESMExports()