dependency-detective 0.2.0 → 0.4.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/README.md +224 -172
- package/index.js +31 -26
- package/package.json +4 -5
- package/src/alternative-suggester.js +24 -56
- package/src/analyzer.js +221 -120
- package/src/ast-parser.js +85 -79
- package/src/config-scanner.js +128 -65
- package/src/script-scanner.js +77 -0
- package/src/security-checker.js +56 -45
- package/src/unused-detector.js +69 -49
- package/src/util/concurrency.js +15 -0
- package/tests/alternative-suggester.test.js +28 -0
- package/tests/analyzer.test.js +97 -0
- package/tests/ast-parser.test.js +32 -0
- package/tests/concurrency.test.js +24 -0
- package/tests/config-scanner.test.js +87 -0
- package/tests/fixtures/sample-imports.js +6 -0
- package/tests/script-scanner.test.js +61 -0
- package/tests/security-checker.test.js +55 -0
- package/tests/unused-detector.test.js +18 -0
package/src/analyzer.js
CHANGED
|
@@ -1,120 +1,221 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
import chalk from 'chalk';
|
|
4
|
-
import ora from 'ora';
|
|
5
|
-
import { findUnusedDependencies } from './unused-detector.js';
|
|
6
|
-
import { checkVulnerabilities } from './security-checker.js';
|
|
7
|
-
import { suggestAlternatives } from './alternative-suggester.js';
|
|
8
|
-
|
|
9
|
-
export
|
|
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
|
-
console.log(
|
|
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
|
-
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import chalk from 'chalk';
|
|
4
|
+
import ora from 'ora';
|
|
5
|
+
import { findUnusedDependencies } from './unused-detector.js';
|
|
6
|
+
import { checkVulnerabilities } from './security-checker.js';
|
|
7
|
+
import { suggestAlternatives } from './alternative-suggester.js';
|
|
8
|
+
|
|
9
|
+
export const EXIT_OK = 0;
|
|
10
|
+
export const EXIT_ISSUES = 1;
|
|
11
|
+
export const EXIT_ERROR = 2;
|
|
12
|
+
|
|
13
|
+
class AnalysisError extends Error {}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Runs every check and returns a plain report object. Prints nothing.
|
|
17
|
+
* `onProgress` receives a short status message before each step.
|
|
18
|
+
*/
|
|
19
|
+
export async function runAnalysis(options = {}, onProgress = () => {}) {
|
|
20
|
+
const directory = path.resolve(options.directory ?? process.cwd());
|
|
21
|
+
const ignoreSet = new Set(options.ignore || []);
|
|
22
|
+
|
|
23
|
+
const packageJsonPath = path.join(directory, 'package.json');
|
|
24
|
+
if (!fs.existsSync(packageJsonPath)) {
|
|
25
|
+
throw new AnalysisError(`No package.json found in ${directory}`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
let packageJson;
|
|
29
|
+
try {
|
|
30
|
+
packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
|
|
31
|
+
} catch (err) {
|
|
32
|
+
throw new AnalysisError(`Could not read ${packageJsonPath}: ${err.message}`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const dependencies = Object.fromEntries(
|
|
36
|
+
Object.entries({
|
|
37
|
+
...(packageJson.dependencies || {}),
|
|
38
|
+
...(packageJson.devDependencies || {}),
|
|
39
|
+
}).filter(([depName]) => !ignoreSet.has(depName))
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
onProgress('Scanning for unused dependencies...');
|
|
43
|
+
const { unusedDeps, warnings } = await findUnusedDependencies(directory, dependencies, packageJson);
|
|
44
|
+
|
|
45
|
+
onProgress('Checking for security vulnerabilities...');
|
|
46
|
+
const security = await checkVulnerabilities(dependencies, directory);
|
|
47
|
+
|
|
48
|
+
let deprecated = null;
|
|
49
|
+
if (options.suggestions !== false) {
|
|
50
|
+
onProgress('Checking for deprecated packages...');
|
|
51
|
+
const found = await suggestAlternatives(dependencies);
|
|
52
|
+
deprecated = Object.values(found).map((info) => ({
|
|
53
|
+
name: info.name,
|
|
54
|
+
message: info.deprecated,
|
|
55
|
+
lastUpdated: info.lastUpdated,
|
|
56
|
+
}));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const unused = unusedDeps.map(({ name, version }) => ({ name, version }));
|
|
60
|
+
const vulnerabilities = Object.entries(security.vulnerabilities).map(([name, issues]) => ({
|
|
61
|
+
name,
|
|
62
|
+
issues,
|
|
63
|
+
}));
|
|
64
|
+
|
|
65
|
+
return {
|
|
66
|
+
directory,
|
|
67
|
+
unused,
|
|
68
|
+
estimatedSavingsBytes: getSavingsBytes(unused, directory),
|
|
69
|
+
vulnerabilities,
|
|
70
|
+
notChecked: security.skipped,
|
|
71
|
+
securityCheckFailed: security.failed,
|
|
72
|
+
deprecated,
|
|
73
|
+
warnings,
|
|
74
|
+
summary: {
|
|
75
|
+
unused: unused.length,
|
|
76
|
+
vulnerable: vulnerabilities.length,
|
|
77
|
+
deprecated: deprecated?.length ?? 0,
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 1 when there are unused dependencies or known vulnerabilities, else 0. */
|
|
83
|
+
export function exitCodeFor(report) {
|
|
84
|
+
return report.unused.length > 0 || report.vulnerabilities.length > 0 ? EXIT_ISSUES : EXIT_OK;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** CLI entry: prints the report (human-readable or JSON) and returns an exit code. */
|
|
88
|
+
export async function analyzeProject(options = {}) {
|
|
89
|
+
if (options.json) {
|
|
90
|
+
try {
|
|
91
|
+
const report = await runAnalysis(options);
|
|
92
|
+
console.log(JSON.stringify(report, null, 2));
|
|
93
|
+
return exitCodeFor(report);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
console.log(JSON.stringify({ error: error.message }, null, 2));
|
|
96
|
+
return EXIT_ERROR;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const spinner = ora('Analyzing your project dependencies...').start();
|
|
101
|
+
try {
|
|
102
|
+
const report = await runAnalysis(options, (text) => {
|
|
103
|
+
spinner.text = text;
|
|
104
|
+
});
|
|
105
|
+
spinner.succeed('Analysis complete!');
|
|
106
|
+
displayResults(report, options.verbose);
|
|
107
|
+
return exitCodeFor(report);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (error instanceof AnalysisError) {
|
|
110
|
+
spinner.fail(error.message);
|
|
111
|
+
} else {
|
|
112
|
+
spinner.fail('Analysis failed');
|
|
113
|
+
console.error(chalk.red('Error:'), error.message);
|
|
114
|
+
}
|
|
115
|
+
return EXIT_ERROR;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function dirSize(dir) {
|
|
120
|
+
let total = 0;
|
|
121
|
+
let entries;
|
|
122
|
+
try {
|
|
123
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
124
|
+
} catch {
|
|
125
|
+
return 0;
|
|
126
|
+
}
|
|
127
|
+
for (const entry of entries) {
|
|
128
|
+
const full = path.join(dir, entry.name);
|
|
129
|
+
if (entry.isDirectory()) {
|
|
130
|
+
total += dirSize(full);
|
|
131
|
+
} else {
|
|
132
|
+
try {
|
|
133
|
+
total += fs.statSync(full).size;
|
|
134
|
+
} catch {
|
|
135
|
+
// unreadable entry — skip
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return total;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function getSavingsBytes(unused, directory) {
|
|
143
|
+
const nodeModules = path.join(directory, 'node_modules');
|
|
144
|
+
if (unused.length === 0 || !fs.existsSync(nodeModules)) return null;
|
|
145
|
+
let bytes = 0;
|
|
146
|
+
for (const dep of unused) {
|
|
147
|
+
bytes += dirSize(path.join(nodeModules, dep.name));
|
|
148
|
+
}
|
|
149
|
+
return bytes;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function displayResults(report, verbose) {
|
|
153
|
+
console.log('\n' + chalk.bold('📦 DEPENDENCY DETECTIVE REPORT') + '\n');
|
|
154
|
+
|
|
155
|
+
// Unused dependencies
|
|
156
|
+
console.log(chalk.bold('🗑️ Unused Dependencies:'));
|
|
157
|
+
if (report.unused.length === 0) {
|
|
158
|
+
console.log(chalk.green(' No unused dependencies found. Great job!'));
|
|
159
|
+
} else {
|
|
160
|
+
for (const dep of report.unused) {
|
|
161
|
+
console.log(` ${chalk.yellow(dep.name)} ${chalk.dim(`v${dep.version}`)}`);
|
|
162
|
+
if (verbose) {
|
|
163
|
+
console.log(` ${chalk.dim('Not imported in any source, config file or script')}`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
if (report.estimatedSavingsBytes !== null) {
|
|
167
|
+
const mb = (report.estimatedSavingsBytes / (1024 * 1024)).toFixed(1);
|
|
168
|
+
console.log(chalk.dim(`\n Removing these could free about ${mb}MB on disk`));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Security vulnerabilities
|
|
173
|
+
console.log('\n' + chalk.bold('🔒 Security Vulnerabilities:'));
|
|
174
|
+
if (report.securityCheckFailed) {
|
|
175
|
+
console.log(chalk.yellow(' ⚠ Security check failed (network error). Try again later.'));
|
|
176
|
+
} else if (report.vulnerabilities.length === 0) {
|
|
177
|
+
console.log(chalk.green(' No known vulnerabilities detected.'));
|
|
178
|
+
} else {
|
|
179
|
+
for (const { name, issues } of report.vulnerabilities) {
|
|
180
|
+
console.log(` ${chalk.red(name)} ${chalk.dim(`(${issues.length} issues)`)}`);
|
|
181
|
+
if (verbose) {
|
|
182
|
+
for (const issue of issues) {
|
|
183
|
+
console.log(` - ${String(issue.severity).toUpperCase()}: ${issue.title}`);
|
|
184
|
+
const meta = [issue.fixedIn && `fixed in ${issue.fixedIn}`, issue.url].filter(Boolean);
|
|
185
|
+
if (meta.length > 0) console.log(` ${chalk.dim(meta.join(' · '))}`);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (report.notChecked.length > 0) {
|
|
191
|
+
console.log(
|
|
192
|
+
chalk.dim(
|
|
193
|
+
` ${report.notChecked.length} package(s) not checked (not installed) — run \`npm install\` for full coverage.`
|
|
194
|
+
)
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// Deprecated packages
|
|
199
|
+
if (report.deprecated?.length > 0) {
|
|
200
|
+
console.log('\n' + chalk.bold('⚠️ Deprecated Packages:'));
|
|
201
|
+
for (const info of report.deprecated) {
|
|
202
|
+
console.log(` ${chalk.yellow(info.name)}`);
|
|
203
|
+
if (verbose) {
|
|
204
|
+
console.log(` ${chalk.dim(info.message)}`);
|
|
205
|
+
if (info.lastUpdated) console.log(` ${chalk.dim(`Last updated: ${info.lastUpdated}`)}`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (report.warnings.length > 0) {
|
|
211
|
+
console.log('\n' + chalk.dim('Warnings:'));
|
|
212
|
+
for (const w of report.warnings) console.log(chalk.dim(` - ${w}`));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Next steps
|
|
216
|
+
console.log('\n' + chalk.bold('📋 Next Steps:'));
|
|
217
|
+
console.log(' 1. Run with --verbose flag for more detailed information');
|
|
218
|
+
console.log(' 2. Consider removing unused dependencies with: npm uninstall [package-names]');
|
|
219
|
+
console.log(' 3. Address security vulnerabilities by updating affected packages');
|
|
220
|
+
console.log(' 4. Replace deprecated packages with maintained alternatives\n');
|
|
221
|
+
}
|
package/src/ast-parser.js
CHANGED
|
@@ -1,79 +1,85 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import { parse } from '@babel/parser';
|
|
3
|
-
|
|
4
|
-
const BABEL_PLUGINS = ['jsx', 'typescript', 'dynamicImport', 'importMeta'];
|
|
5
|
-
|
|
6
|
-
function extractPackageName(source) {
|
|
7
|
-
if (source.startsWith('.')) return source;
|
|
8
|
-
if (source.startsWith('@')) {
|
|
9
|
-
return source.split('/').slice(0, 2).join('/');
|
|
10
|
-
}
|
|
11
|
-
return source.split('/')[0];
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
function walk(node, visitor) {
|
|
15
|
-
if (!node || typeof node !== 'object' || Array.isArray(node)) return;
|
|
16
|
-
if (!node.type) return;
|
|
17
|
-
if (visitor[node.type]) visitor[node.type](node);
|
|
18
|
-
for (const key of Object.keys(node)) {
|
|
19
|
-
const child = node[key];
|
|
20
|
-
if (Array.isArray(child)) {
|
|
21
|
-
for (const item of child) {
|
|
22
|
-
if (item && typeof item === 'object' && item.type) walk(item, visitor);
|
|
23
|
-
}
|
|
24
|
-
} else if (child && typeof child === 'object' && child.type) {
|
|
25
|
-
walk(child, visitor);
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export async function parseFileImports(filePath) {
|
|
31
|
-
const referenced = new Set();
|
|
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
|
-
node.
|
|
67
|
-
)
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
referenced.add(extractPackageName(node.
|
|
74
|
-
}
|
|
75
|
-
},
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import { parse } from '@babel/parser';
|
|
3
|
+
|
|
4
|
+
const BABEL_PLUGINS = ['jsx', 'typescript', 'dynamicImport', 'importMeta'];
|
|
5
|
+
|
|
6
|
+
export function extractPackageName(source) {
|
|
7
|
+
if (source.startsWith('.')) return source;
|
|
8
|
+
if (source.startsWith('@')) {
|
|
9
|
+
return source.split('/').slice(0, 2).join('/');
|
|
10
|
+
}
|
|
11
|
+
return source.split('/')[0];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function walk(node, visitor) {
|
|
15
|
+
if (!node || typeof node !== 'object' || Array.isArray(node)) return;
|
|
16
|
+
if (!node.type) return;
|
|
17
|
+
if (visitor[node.type]) visitor[node.type](node);
|
|
18
|
+
for (const key of Object.keys(node)) {
|
|
19
|
+
const child = node[key];
|
|
20
|
+
if (Array.isArray(child)) {
|
|
21
|
+
for (const item of child) {
|
|
22
|
+
if (item && typeof item === 'object' && item.type) walk(item, visitor);
|
|
23
|
+
}
|
|
24
|
+
} else if (child && typeof child === 'object' && child.type) {
|
|
25
|
+
walk(child, visitor);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function parseFileImports(filePath) {
|
|
31
|
+
const referenced = new Set();
|
|
32
|
+
const warnings = [];
|
|
33
|
+
|
|
34
|
+
let content;
|
|
35
|
+
try {
|
|
36
|
+
content = await fs.promises.readFile(filePath, 'utf8');
|
|
37
|
+
} catch {
|
|
38
|
+
return { referenced, warnings };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
let ast;
|
|
42
|
+
try {
|
|
43
|
+
ast = parse(content, {
|
|
44
|
+
sourceType: 'unambiguous',
|
|
45
|
+
plugins: BABEL_PLUGINS,
|
|
46
|
+
errorRecovery: true,
|
|
47
|
+
});
|
|
48
|
+
} catch (err) {
|
|
49
|
+
warnings.push(`Could not parse ${filePath}: ${err.message}`);
|
|
50
|
+
return { referenced, warnings };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
walk(ast, {
|
|
54
|
+
ImportDeclaration(node) {
|
|
55
|
+
if (node.source?.value) referenced.add(extractPackageName(node.source.value));
|
|
56
|
+
},
|
|
57
|
+
ExportNamedDeclaration(node) {
|
|
58
|
+
if (node.source?.value) referenced.add(extractPackageName(node.source.value));
|
|
59
|
+
},
|
|
60
|
+
ExportAllDeclaration(node) {
|
|
61
|
+
if (node.source?.value) referenced.add(extractPackageName(node.source.value));
|
|
62
|
+
},
|
|
63
|
+
CallExpression(node) {
|
|
64
|
+
// require('pkg') — CommonJS
|
|
65
|
+
const isRequire =
|
|
66
|
+
node.callee?.type === 'Identifier' && node.callee.name === 'require';
|
|
67
|
+
// import('pkg') — @babel/parser emits a CallExpression with an Import callee
|
|
68
|
+
const isDynamicImport = node.callee?.type === 'Import';
|
|
69
|
+
if (
|
|
70
|
+
(isRequire || isDynamicImport) &&
|
|
71
|
+
node.arguments?.[0]?.type === 'StringLiteral'
|
|
72
|
+
) {
|
|
73
|
+
referenced.add(extractPackageName(node.arguments[0].value));
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
// ESTree-shaped dynamic import (only if a future estree plugin is enabled)
|
|
77
|
+
ImportExpression(node) {
|
|
78
|
+
if (node.source?.type === 'StringLiteral') {
|
|
79
|
+
referenced.add(extractPackageName(node.source.value));
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
return { referenced, warnings };
|
|
85
|
+
}
|