-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.js
More file actions
337 lines (289 loc) Β· 9.54 KB
/
test.js
File metadata and controls
337 lines (289 loc) Β· 9.54 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
#!/usr/bin/env node
import madge from "madge";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
/**
* Reads tsconfig.json or jsconfig.json to extract path aliases
*/
function extractPathAliases(projectPath) {
const configFiles = ["tsconfig.json", "jsconfig.json"];
for (const configFile of configFiles) {
const configPath = path.join(projectPath, configFile);
if (fs.existsSync(configPath)) {
try {
const configContent = fs.readFileSync(configPath, "utf8");
// Remove comments (simple approach)
const cleanContent = configContent.replace(
/\/\*[\s\S]*?\*\/|\/\/.*/g,
""
);
const config = JSON.parse(cleanContent);
if (config.compilerOptions?.paths) {
const aliases = {};
const baseUrl = config.compilerOptions.baseUrl || ".";
Object.entries(config.compilerOptions.paths).forEach(
([alias, paths]) => {
// Convert "@/*" to "@" for webpack alias format
const cleanAlias = alias.replace("/*", "");
const targetPath = paths[0].replace("/*", "");
// Resolve to absolute path
aliases[cleanAlias] = path.resolve(
projectPath,
baseUrl,
targetPath
);
}
);
console.log(`β
Loaded path aliases from ${configFile}:`, aliases);
return aliases;
}
} catch (error) {
console.warn(`β οΈ Could not parse ${configFile}:`, error.message);
}
}
}
// Default fallback for Next.js
console.log("β οΈ No config found, using default Next.js alias");
return {
"@": projectPath,
};
}
/**
* Analyzes project dependencies using Madge
*/
async function analyzeDependencies(projectPath, outputPath) {
console.log("π Starting dependency analysis with Madge...");
console.log(`π Project: ${projectPath}`);
try {
// Check if project path exists
if (!fs.existsSync(projectPath)) {
throw new Error(`Project path does not exist: ${projectPath}`);
}
// Extract path aliases
const aliases = extractPathAliases(projectPath);
// Run Madge analysis with proper configuration
const result = await madge(projectPath, {
fileExtensions: ["js", "jsx", "ts", "tsx", "mjs", "cjs"],
excludeRegExp: [
/node_modules/,
/\.next/,
/dist/,
/build/,
/__tests__/,
/\.test\./,
/\.spec\./,
],
// Pass webpack config as a proper configuration object
webpackConfig: {
resolve: {
alias: aliases,
extensions: [".js", ".jsx", ".ts", ".tsx", ".json", ".mjs", ".cjs"],
},
},
// Additional configuration
baseDir: projectPath,
includeNpm: false,
});
const dependencyGraph = result.obj();
const circularDependencies = result.circular();
const warnings = result.warnings() || [];
console.log(`β
Analyzed ${Object.keys(dependencyGraph).length} files`);
console.log(
`β οΈ Found ${circularDependencies.length} circular dependencies`
);
if (warnings.length > 0) {
console.log(`β οΈ ${warnings.length} warnings`);
}
// Convert to our format with absolute paths
const dependencyMap = convertToDependencyMap(dependencyGraph, projectPath);
// Prepare output
const output = {
metadata: {
analyzedAt: new Date().toISOString(),
projectRoot: projectPath,
totalFiles: Object.keys(dependencyMap).length,
circularDependenciesCount: circularDependencies.length,
},
dependencyMap,
circularDependencies,
warnings,
stats: calculateStats(dependencyMap),
};
// Write to file
fs.writeFileSync(outputPath, JSON.stringify(output, null, 2));
console.log(`π Results written to: ${outputPath}`);
// Print summary
printSummary(output);
return output;
} catch (error) {
console.error("β Analysis failed:", error.message);
console.error(error.stack);
process.exit(1);
}
}
/**
* Converts Madge's graph format to our dependency map
*/
function convertToDependencyMap(madgeGraph, projectRoot) {
const dependencyMap = {};
// Pass 1: Create entries for all files
Object.keys(madgeGraph).forEach((relativePath) => {
const absolutePath = path.resolve(projectRoot, relativePath);
dependencyMap[absolutePath] = {
id: absolutePath,
name: path.basename(absolutePath),
relativePath: relativePath,
type: "file",
extension: path.extname(absolutePath),
fullPath: absolutePath,
imports: [],
importedBy: [],
};
});
// Pass 2: Populate imports and importedBy
Object.entries(madgeGraph).forEach(([sourceRelPath, dependencies]) => {
const sourceAbsPath = path.resolve(projectRoot, sourceRelPath);
if (!dependencyMap[sourceAbsPath]) return;
dependencies.forEach((depRelPath) => {
const depAbsPath = path.resolve(projectRoot, depRelPath);
// Add to source's imports
if (dependencyMap[depAbsPath]) {
dependencyMap[sourceAbsPath].imports.push({
name: path.basename(depAbsPath),
resolvedPath: depAbsPath,
relativePath: depRelPath,
isLocal: true,
exists: true,
type: "import",
});
// Add to target's importedBy
dependencyMap[depAbsPath].importedBy.push({
source: sourceAbsPath,
name: path.basename(sourceAbsPath),
relativePath: sourceRelPath,
fullPath: sourceAbsPath,
type: "import",
});
}
});
});
return dependencyMap;
}
/**
* Calculate statistics about the dependency map
*/
function calculateStats(dependencyMap) {
const files = Object.values(dependencyMap);
// Most imported files
const mostImported = files
.filter((f) => f.importedBy.length > 0)
.sort((a, b) => b.importedBy.length - a.importedBy.length)
.slice(0, 10)
.map((f) => ({
path: f.relativePath,
name: f.name,
importedByCount: f.importedBy.length,
}));
// Files with most dependencies
const mostDependencies = files
.filter((f) => f.imports.length > 0)
.sort((a, b) => b.imports.length - a.imports.length)
.slice(0, 10)
.map((f) => ({
path: f.relativePath,
name: f.name,
importsCount: f.imports.length,
}));
// Orphan files (not imported by anyone)
const orphanFiles = files
.filter((f) => f.importedBy.length === 0)
.map((f) => ({
path: f.relativePath,
name: f.name,
}));
// Files by extension
const filesByExtension = {};
files.forEach((f) => {
const ext = f.extension || "no-extension";
filesByExtension[ext] = (filesByExtension[ext] || 0) + 1;
});
return {
totalFiles: files.length,
totalDependencies: files.reduce((sum, f) => sum + f.imports.length, 0),
averageDependenciesPerFile:
files.length > 0
? (
files.reduce((sum, f) => sum + f.imports.length, 0) / files.length
).toFixed(2)
: 0,
mostImportedFiles: mostImported,
mostDependentFiles: mostDependencies,
orphanFiles: orphanFiles.slice(0, 20),
orphanCount: orphanFiles.length,
filesByExtension,
};
}
/**
* Prints a summary to the console
*/
function printSummary(output) {
const { stats, circularDependencies } = output;
console.log("\nπ Analysis Summary:");
console.log("ββββββββββββββββββββββββββββββββββββββββ");
console.log(`Total Files: ${stats.totalFiles}`);
console.log(`Total Dependencies: ${stats.totalDependencies}`);
console.log(`Average Dependencies/File: ${stats.averageDependenciesPerFile}`);
console.log(`Orphan Files: ${stats.orphanCount}`);
console.log(`Circular Dependencies: ${circularDependencies.length}`);
console.log("\nπ Files by Extension:");
Object.entries(stats.filesByExtension)
.sort((a, b) => b[1] - a[1])
.forEach(([ext, count]) => {
console.log(` ${ext}: ${count}`);
});
if (stats.mostImportedFiles.length > 0) {
console.log("\nπ₯ Most Imported Files:");
stats.mostImportedFiles.slice(0, 5).forEach((file, i) => {
console.log(
` ${i + 1}. ${file.path} (imported ${file.importedByCount} times)`
);
});
}
if (stats.mostDependentFiles.length > 0) {
console.log("\nπ¦ Files with Most Dependencies:");
stats.mostDependentFiles.slice(0, 5).forEach((file, i) => {
console.log(
` ${i + 1}. ${file.path} (imports ${file.importsCount} files)`
);
});
}
if (circularDependencies.length > 0) {
console.log("\nβ οΈ Circular Dependencies Found:");
circularDependencies.slice(0, 3).forEach((cycle, i) => {
console.log(` ${i + 1}. ${cycle.join(" β ")}`);
});
if (circularDependencies.length > 3) {
console.log(` ... and ${circularDependencies.length - 3} more`);
}
}
console.log("\nβ
Analysis complete!");
}
// Main execution
const args = process.argv.slice(2);
if (args.length === 0) {
console.error(
"Usage: node analyze-dependencies.js <project-path> [output-file]"
);
console.error(
"Example: node analyze-dependencies.js /Users/rkg/my-project ./output.json"
);
process.exit(1);
}
const projectPath = path.resolve(args[0]);
const outputPath = args[1]
? path.resolve(args[1])
: path.join(process.cwd(), "dependency-analysis.json");
analyzeDependencies(projectPath, outputPath);