-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathexport.js
More file actions
378 lines (340 loc) · 12.1 KB
/
Copy pathexport.js
File metadata and controls
378 lines (340 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import path from 'node:path';
import { isTestFile } from '../infrastructure/test-filter.js';
import {
renderFileLevelDOT,
renderFileLevelGraphML,
renderFileLevelMermaid,
renderFileLevelNeo4jCSV,
renderFunctionLevelDOT,
renderFunctionLevelGraphML,
renderFunctionLevelMermaid,
renderFunctionLevelNeo4jCSV,
} from '../presentation/export.js';
import { paginateResult } from '../shared/paginate.js';
const DEFAULT_MIN_CONFIDENCE = 0.5;
// ─── Shared data loaders ─────────────────────────────────────────────
/**
* Load file-level edges from DB with filtering.
* @param {object} db
* @param {object} opts
* @param {boolean} [opts.includeKind] - Include edge_kind in SELECT DISTINCT
* @param {boolean} [opts.includeConfidence] - Include confidence (adds a column to DISTINCT — use only when needed)
* @returns {{ edges: Array, totalEdges: number }}
*/
function loadFileLevelEdges(
db,
{ noTests, minConfidence, limit, includeKind = false, includeConfidence = false },
) {
const minConf = minConfidence ?? DEFAULT_MIN_CONFIDENCE;
const kindClause = includeKind ? ', e.kind AS edge_kind' : '';
const confidenceClause = includeConfidence ? ', e.confidence' : '';
let edges = db
.prepare(
`
SELECT DISTINCT n1.file AS source, n2.file AS target${kindClause}${confidenceClause}
FROM edges e
JOIN nodes n1 ON e.source_id = n1.id
JOIN nodes n2 ON e.target_id = n2.id
WHERE n1.file != n2.file AND e.kind IN ('imports', 'imports-type', 'calls')
AND e.confidence >= ?
`,
)
.all(minConf);
if (noTests) edges = edges.filter((e) => !isTestFile(e.source) && !isTestFile(e.target));
const totalEdges = edges.length;
if (limit && edges.length > limit) edges = edges.slice(0, limit);
return { edges, totalEdges };
}
/**
* Load function-level edges from DB with filtering.
* Returns the maximal field set needed by any serializer.
* @returns {{ edges: Array, totalEdges: number }}
*/
function loadFunctionLevelEdges(db, { noTests, minConfidence, limit }) {
const minConf = minConfidence ?? DEFAULT_MIN_CONFIDENCE;
let edges = db
.prepare(
`
SELECT n1.id AS source_id, n1.name AS source_name, n1.kind AS source_kind,
n1.file AS source_file, n1.line AS source_line, n1.role AS source_role,
n2.id AS target_id, n2.name AS target_name, n2.kind AS target_kind,
n2.file AS target_file, n2.line AS target_line, n2.role AS target_role,
e.kind AS edge_kind, e.confidence
FROM edges e
JOIN nodes n1 ON e.source_id = n1.id
JOIN nodes n2 ON e.target_id = n2.id
WHERE n1.kind IN ('function', 'method', 'class', 'interface', 'type', 'struct', 'enum', 'trait', 'record', 'module', 'constant')
AND n2.kind IN ('function', 'method', 'class', 'interface', 'type', 'struct', 'enum', 'trait', 'record', 'module', 'constant')
AND e.kind = 'calls'
AND e.confidence >= ?
`,
)
.all(minConf);
if (noTests)
edges = edges.filter((e) => !isTestFile(e.source_file) && !isTestFile(e.target_file));
const totalEdges = edges.length;
if (limit && edges.length > limit) edges = edges.slice(0, limit);
return { edges, totalEdges };
}
/**
* Load directory groupings for file-level graphs.
* Uses DB directory nodes if available, falls back to path.dirname().
* @returns {Array<{ name: string, files: Array<{ path: string, basename: string }>, cohesion: number|null }>}
*/
function loadDirectoryGroups(db, allFiles) {
const hasDirectoryNodes =
db.prepare("SELECT COUNT(*) as c FROM nodes WHERE kind = 'directory'").get().c > 0;
const dirs = new Map();
if (hasDirectoryNodes) {
const dbDirs = db
.prepare(`
SELECT n.id, n.name, nm.cohesion
FROM nodes n
LEFT JOIN node_metrics nm ON n.id = nm.node_id
WHERE n.kind = 'directory'
`)
.all();
for (const d of dbDirs) {
const containedFiles = db
.prepare(`
SELECT n.name FROM edges e
JOIN nodes n ON e.target_id = n.id
WHERE e.source_id = ? AND e.kind = 'contains' AND n.kind = 'file'
`)
.all(d.id)
.map((r) => r.name)
.filter((f) => allFiles.has(f));
if (containedFiles.length > 0) {
dirs.set(d.name, { files: containedFiles, cohesion: d.cohesion ?? null });
}
}
} else {
for (const file of allFiles) {
const dir = path.dirname(file) || '.';
if (!dirs.has(dir)) dirs.set(dir, { files: [], cohesion: null });
dirs.get(dir).files.push(file);
}
}
return [...dirs]
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([name, info]) => ({
name,
files: info.files.map((f) => ({ path: f, basename: path.basename(f) })),
cohesion: info.cohesion,
}));
}
/**
* Load directory groupings for Mermaid file-level graphs (simplified — no cohesion, string arrays).
*/
function loadMermaidDirectoryGroups(db, allFiles) {
const hasDirectoryNodes =
db.prepare("SELECT COUNT(*) as c FROM nodes WHERE kind = 'directory'").get().c > 0;
const dirs = new Map();
if (hasDirectoryNodes) {
const dbDirs = db.prepare("SELECT id, name FROM nodes WHERE kind = 'directory'").all();
for (const d of dbDirs) {
const containedFiles = db
.prepare(`
SELECT n.name FROM edges e
JOIN nodes n ON e.target_id = n.id
WHERE e.source_id = ? AND e.kind = 'contains' AND n.kind = 'file'
`)
.all(d.id)
.map((r) => r.name)
.filter((f) => allFiles.has(f));
if (containedFiles.length > 0) dirs.set(d.name, containedFiles);
}
} else {
for (const file of allFiles) {
const dir = path.dirname(file) || '.';
if (!dirs.has(dir)) dirs.set(dir, []);
dirs.get(dir).push(file);
}
}
return [...dirs]
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([name, files]) => ({ name, files }));
}
/**
* Load node roles for Mermaid function-level styling.
* @returns {Map<string, string>} "file::name" → role
*/
function loadNodeRoles(db, edges) {
const roles = new Map();
const seen = new Set();
for (const e of edges) {
for (const [file, name] of [
[e.source_file, e.source_name],
[e.target_file, e.target_name],
]) {
const key = `${file}::${name}`;
if (seen.has(key)) continue;
seen.add(key);
const row = db
.prepare('SELECT role FROM nodes WHERE file = ? AND name = ? AND role IS NOT NULL LIMIT 1')
.get(file, name);
if (row?.role) roles.set(key, row.role);
}
}
return roles;
}
// ─── Public API ──────────────────────────────────────────────────────
/**
* Export the dependency graph in DOT (Graphviz) format.
*/
export function exportDOT(db, opts = {}) {
const fileLevel = opts.fileLevel !== false;
const noTests = opts.noTests || false;
const minConfidence = opts.minConfidence;
const limit = opts.limit;
if (fileLevel) {
const { edges, totalEdges } = loadFileLevelEdges(db, { noTests, minConfidence, limit });
const allFiles = new Set();
for (const { source, target } of edges) {
allFiles.add(source);
allFiles.add(target);
}
const dirs = loadDirectoryGroups(db, allFiles);
return renderFileLevelDOT({ dirs, edges, totalEdges, limit });
}
const { edges, totalEdges } = loadFunctionLevelEdges(db, { noTests, minConfidence, limit });
return renderFunctionLevelDOT({ edges, totalEdges, limit });
}
/**
* Export the dependency graph in Mermaid format.
*/
export function exportMermaid(db, opts = {}) {
const fileLevel = opts.fileLevel !== false;
const noTests = opts.noTests || false;
const minConfidence = opts.minConfidence;
const direction = opts.direction || 'LR';
const limit = opts.limit;
if (fileLevel) {
const { edges, totalEdges } = loadFileLevelEdges(db, {
noTests,
minConfidence,
limit,
includeKind: true,
});
const allFiles = new Set();
for (const { source, target } of edges) {
allFiles.add(source);
allFiles.add(target);
}
const dirs = loadMermaidDirectoryGroups(db, allFiles);
return renderFileLevelMermaid({ direction, dirs, edges, totalEdges, limit });
}
const { edges, totalEdges } = loadFunctionLevelEdges(db, { noTests, minConfidence, limit });
const roles = loadNodeRoles(db, edges);
return renderFunctionLevelMermaid({ direction, edges, roles, totalEdges, limit });
}
/**
* Export as JSON adjacency list.
*/
export function exportJSON(db, opts = {}) {
const noTests = opts.noTests || false;
const minConf = opts.minConfidence ?? DEFAULT_MIN_CONFIDENCE;
let nodes = db
.prepare(`
SELECT id, name, kind, file, line FROM nodes WHERE kind = 'file'
`)
.all();
if (noTests) nodes = nodes.filter((n) => !isTestFile(n.file));
let edges = db
.prepare(`
SELECT DISTINCT n1.file AS source, n2.file AS target, e.kind, e.confidence
FROM edges e
JOIN nodes n1 ON e.source_id = n1.id
JOIN nodes n2 ON e.target_id = n2.id
WHERE n1.file != n2.file AND e.confidence >= ?
`)
.all(minConf);
if (noTests) edges = edges.filter((e) => !isTestFile(e.source) && !isTestFile(e.target));
const base = { nodes, edges };
return paginateResult(base, 'edges', { limit: opts.limit, offset: opts.offset });
}
/**
* Export the dependency graph in GraphML (XML) format.
*/
export function exportGraphML(db, opts = {}) {
const fileLevel = opts.fileLevel !== false;
const noTests = opts.noTests || false;
const minConfidence = opts.minConfidence;
const limit = opts.limit;
if (fileLevel) {
const { edges } = loadFileLevelEdges(db, { noTests, minConfidence, limit });
return renderFileLevelGraphML({ edges });
}
const { edges } = loadFunctionLevelEdges(db, { noTests, minConfidence, limit });
return renderFunctionLevelGraphML({ edges });
}
/**
* Export the dependency graph in TinkerPop GraphSON v3 format.
*/
export function exportGraphSON(db, opts = {}) {
const noTests = opts.noTests || false;
const minConf = opts.minConfidence ?? DEFAULT_MIN_CONFIDENCE;
let nodes = db
.prepare(`
SELECT id, name, kind, file, line, role FROM nodes
WHERE kind IN ('function', 'method', 'class', 'interface', 'type', 'struct', 'enum', 'trait', 'record', 'module', 'constant', 'file')
`)
.all();
if (noTests) nodes = nodes.filter((n) => !isTestFile(n.file));
let edges = db
.prepare(`
SELECT e.rowid AS id, n1.id AS outV, n2.id AS inV, e.kind, e.confidence
FROM edges e
JOIN nodes n1 ON e.source_id = n1.id
JOIN nodes n2 ON e.target_id = n2.id
WHERE e.confidence >= ?
`)
.all(minConf);
if (noTests) {
const nodeIds = new Set(nodes.map((n) => n.id));
edges = edges.filter((e) => nodeIds.has(e.outV) && nodeIds.has(e.inV));
}
const vertices = nodes.map((n) => ({
id: n.id,
label: n.kind,
properties: {
name: [{ id: 0, value: n.name }],
file: [{ id: 0, value: n.file }],
...(n.line != null ? { line: [{ id: 0, value: n.line }] } : {}),
...(n.role ? { role: [{ id: 0, value: n.role }] } : {}),
},
}));
const gEdges = edges.map((e) => ({
id: e.id,
label: e.kind,
inV: e.inV,
outV: e.outV,
properties: {
confidence: e.confidence,
},
}));
const base = { vertices, edges: gEdges };
return paginateResult(base, 'edges', { limit: opts.limit, offset: opts.offset });
}
/**
* Export the dependency graph as Neo4j bulk-import CSV files.
* Returns { nodes: string, relationships: string }.
*/
export function exportNeo4jCSV(db, opts = {}) {
const fileLevel = opts.fileLevel !== false;
const noTests = opts.noTests || false;
const minConfidence = opts.minConfidence;
const limit = opts.limit;
if (fileLevel) {
const { edges } = loadFileLevelEdges(db, {
noTests,
minConfidence,
limit,
includeKind: true,
includeConfidence: true,
});
return renderFileLevelNeo4jCSV({ edges });
}
const { edges } = loadFunctionLevelEdges(db, { noTests, minConfidence, limit });
return renderFunctionLevelNeo4jCSV({ edges });
}