dependency-detective 0.1.3 → 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.
Files changed (31) hide show
  1. package/.claude/worktrees/amazing-bartik-b7ca06/.claude/settings.local.json +19 -0
  2. package/.claude/worktrees/amazing-bartik-b7ca06/LICENSE +21 -0
  3. package/.claude/worktrees/amazing-bartik-b7ca06/README.md +151 -0
  4. package/.claude/worktrees/amazing-bartik-b7ca06/docs/superpowers/specs/2026-05-09-correctness-fixes-design.md +118 -0
  5. package/.claude/worktrees/amazing-bartik-b7ca06/index.js +19 -0
  6. package/.claude/worktrees/amazing-bartik-b7ca06/package-lock.json +915 -0
  7. package/.claude/worktrees/amazing-bartik-b7ca06/package.json +36 -0
  8. package/.claude/worktrees/amazing-bartik-b7ca06/src/alternative-suggester.js +64 -0
  9. package/.claude/worktrees/amazing-bartik-b7ca06/src/analyzer.js +141 -0
  10. package/.claude/worktrees/amazing-bartik-b7ca06/src/security-checker.js +62 -0
  11. package/.claude/worktrees/amazing-bartik-b7ca06/src/unused-detector.js +71 -0
  12. package/README.md +224 -150
  13. package/index.js +31 -19
  14. package/package.json +5 -5
  15. package/src/alternative-suggester.js +24 -56
  16. package/src/analyzer.js +221 -141
  17. package/src/ast-parser.js +85 -0
  18. package/src/config-scanner.js +128 -0
  19. package/src/script-scanner.js +77 -0
  20. package/src/security-checker.js +56 -49
  21. package/src/unused-detector.js +50 -52
  22. package/src/util/concurrency.js +15 -0
  23. package/tests/alternative-suggester.test.js +28 -0
  24. package/tests/analyzer.test.js +97 -0
  25. package/tests/ast-parser.test.js +32 -0
  26. package/tests/concurrency.test.js +24 -0
  27. package/tests/config-scanner.test.js +87 -0
  28. package/tests/fixtures/sample-imports.js +6 -0
  29. package/tests/script-scanner.test.js +61 -0
  30. package/tests/security-checker.test.js +55 -0
  31. package/tests/unused-detector.test.js +18 -0
package/README.md CHANGED
@@ -1,151 +1,225 @@
1
- # dependency-detective 🕵️‍♂️
2
-
3
- A powerful Node.js tool that analyzes your project's dependencies, identifies unused packages, forecasts potential security risks, and suggests better alternatives based on community engagement and update frequency.
4
-
5
-
6
- ## 🔍 Overview
7
-
8
- **dependency-detective** addresses a common pain point that virtually every Node.js developer faces - dependency management gets messy as projects grow, and it's hard to know which packages are actually being used, which ones pose security risks, and which ones could be replaced with better alternatives.
9
-
10
- ## ✨ Features
11
-
12
- - **Unused Dependencies Detection**: Identifies truly unused packages that can be safely removed
13
- - **Security Vulnerabilities Check**: Highlights packages with known security issues
14
- - **Alternative Package Suggestions**: Recommends better alternatives based on community adoption, performance metrics, and update frequency
15
- - **Detailed Reporting**: Get comprehensive information about your dependency health in an easy-to-read format
16
-
17
- ## 📋 Installation
18
-
19
- ```bash
20
- # Install globally
21
- npm install -g dependency-detective
22
-
23
- # Or use with npx
24
- npx dependency-detective
25
- ```
26
-
27
- ## 🚀 Usage
28
-
29
- ```bash
30
- # Run in your project directory
31
- dependency-detective
32
-
33
- # Or specify a different project directory
34
- dependency-detective --directory /path/to/your/project
35
-
36
- # Show more detailed information
37
- dependency-detective --verbose
38
-
39
- # Skip alternative package suggestions
40
- dependency-detective --no-suggestions
41
- ```
42
-
43
- ## 📊 Example Output
44
-
45
- ```
46
- 📦 DEPENDENCY DETECTIVE REPORT
47
-
48
- 🗑️ Unused Dependencies:
49
- jquery v3.6.0
50
- moment v2.29.4
51
-
52
- Removing these could save approximately ~10MB of disk space
53
-
54
- 🔒 Security Vulnerabilities:
55
- lodash (1 issues)
56
-
57
- 💡 Recommended Alternatives:
58
- moment → date-fns
59
- jquery → No dependency needed
60
- express → fastify
61
-
62
- 📋 Next Steps:
63
- 1. Run with --verbose flag for more detailed information
64
- 2. Consider removing unused dependencies with: npm uninstall [package-names]
65
- 3. Address security vulnerabilities by updating affected packages
66
- 4. Evaluate suggested alternatives for potential improvements
67
- ```
68
-
69
- ## 🔧 Options
70
-
71
- | Option | Description |
72
- |--------|-------------|
73
- | `-d, --directory <path>` | Project directory to analyze (default: current directory) |
74
- | `-v, --verbose` | Show detailed output including reasons and statistics |
75
- | `--no-suggestions` | Skip suggesting alternative packages |
76
- | `--help` | Display help information |
77
- | `--version` | Display version number |
78
-
79
- ## 🧩 How It Works
80
-
81
- 1. **Scanning Source Code**: The tool scans your project files looking for import/require statements
82
- 2. **Dependency Analysis**: It cross-references found imports with your package.json
83
- 3. **Security Checking**: It queries security databases for known vulnerabilities
84
- 4. **Alternative Analysis**: It evaluates potential alternative packages based on multiple metrics
85
- 5. **Report Generation**: It presents findings in a clear, actionable format
86
-
87
- ## 🛠️ For Developers
88
-
89
- ### Project Structure
90
-
91
- ```
92
- dependency-detective/
93
- ├── index.js # CLI entry point
94
- ├── package.json
95
- └── src/
96
- ├── analyzer.js # Main analysis logic
97
- ├── unused-detector.js # Detects unused dependencies
98
- ├── security-checker.js # Checks for vulnerabilities
99
- └── alternative-suggester.js # Suggests better alternatives
100
- ```
101
-
102
- ### Local Development
103
-
104
- ```bash
105
- # Clone the repository
106
- git clone https://github.com/yourusername/dependency-detective.git
107
- cd dependency-detective
108
-
109
- # Install dependencies
110
- npm install
111
-
112
- # Link for local testing
113
- npm link
114
-
115
- # Run tests
116
- npm test
117
- ```
118
-
119
- ## ⚠️ Limitations
120
-
121
- - The tool may not detect dependencies used in dynamically generated requires or imports
122
- - Security vulnerability detection relies on external databases which may not be 100% complete
123
- - Alternative suggestions are based on general community metrics and might not be ideal for every specific use case
124
-
125
- ## 📝 Roadmap
126
-
127
- - [ ] Improve detection accuracy with AST parsing
128
- - [ ] Add support for monorepos and workspaces
129
- - [ ] Visual reporting with charts and graphs
130
- - [ ] Interactive mode for bulk actions on dependencies
131
- - [ ] Customizable rules and thresholds
132
- - [ ] GitHub Actions integration
133
-
134
- ## 📄 License
135
-
136
- MIT
137
-
138
- ## 👥 Contributing
139
-
140
- Contributions are welcome! Please feel free to submit a Pull Request.
141
-
142
- 1. Fork the repository
143
- 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
144
- 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
145
- 4. Push to the branch (`git push origin feature/amazing-feature`)
146
- 5. Open a Pull Request
147
-
148
- ## 🙏 Acknowledgements
149
-
150
- - Thanks to all the open-source package maintainers
1
+ # dependency-detective 🕵️‍♂️
2
+
3
+ A Node.js tool that analyzes your project's dependencies: it identifies unused packages, checks for known security vulnerabilities (via the free OSV.dev database — no token required), and flags packages whose latest version has been officially deprecated.
4
+
5
+
6
+ ## 🔍 Overview
7
+
8
+ **dependency-detective** addresses a common pain point that virtually every Node.js developer faces - dependency management gets messy as projects grow, and it's hard to know which packages are actually being used, which ones pose security risks, and which ones could be replaced with better alternatives.
9
+
10
+ ## ✨ Features
11
+
12
+ - **Unused Dependencies Detection**: Identifies truly unused packages that can be safely removed
13
+ - **Security Vulnerabilities Check**: Highlights packages with known security issues, using the free OSV.dev database
14
+ - **Deprecated Package Detection**: Flags dependencies whose latest version has been officially deprecated by its maintainer
15
+ - **Detailed Reporting**: Get comprehensive information about your dependency health in an easy-to-read format
16
+
17
+ ## 📋 Installation
18
+
19
+ ```bash
20
+ # Install globally
21
+ npm install -g dependency-detective
22
+
23
+ # Or use with npx
24
+ npx dependency-detective
25
+ ```
26
+
27
+ ## ⚙️ Configuration
28
+
29
+ No configuration or API tokens are required. Vulnerability data comes from the free
30
+ [OSV.dev](https://osv.dev) database and works out of the box.
31
+
32
+ > Note: vulnerability checks read the **installed** version of each package from
33
+ > `node_modules`. Run `npm install` first for full coverage — uninstalled packages are
34
+ > reported as "not checked".
35
+
36
+ ## 🚀 Usage
37
+
38
+ ```bash
39
+ # Run in your project directory
40
+ dependency-detective
41
+
42
+ # Or specify a different project directory
43
+ dependency-detective --directory /path/to/your/project
44
+
45
+ # Show more detailed information
46
+ dependency-detective --verbose
47
+
48
+ # Skip the deprecated-package check
49
+ dependency-detective --no-suggestions
50
+
51
+ # Print the report as JSON
52
+ dependency-detective --json
53
+ ```
54
+
55
+ ## 📊 Example Output
56
+
57
+ ```
58
+ 📦 DEPENDENCY DETECTIVE REPORT
59
+
60
+ 🗑️ Unused Dependencies:
61
+ jquery v3.6.0
62
+ moment v2.29.4
63
+
64
+ Removing these could free about 3.2MB on disk
65
+
66
+ 🔒 Security Vulnerabilities:
67
+ lodash (1 issues)
68
+
69
+ ⚠️ Deprecated Packages:
70
+ request
71
+
72
+ 📋 Next Steps:
73
+ 1. Run with --verbose flag for more detailed information
74
+ 2. Consider removing unused dependencies with: npm uninstall [package-names]
75
+ 3. Address security vulnerabilities by updating affected packages
76
+ 4. Replace deprecated packages with maintained alternatives
77
+ ```
78
+
79
+ ## 🔧 Options
80
+
81
+ | Option | Description |
82
+ |--------|-------------|
83
+ | `-d, --directory <path>` | Project directory to analyze (default: current directory) |
84
+ | `-v, --verbose` | Show detailed output including reasons and statistics |
85
+ | `--no-suggestions` | Skip the deprecated-package check |
86
+ | `--ignore <packages>` | Comma-separated list of package names to exclude from all checks |
87
+ | `--json` | Print the report as JSON instead of the formatted report |
88
+ | `--help` | Display help information |
89
+ | `--version` | Display version number |
90
+
91
+ Use `--ignore` for packages that are intentionally hard to detect — build tools, PostCSS plugins, ESLint configs, and similar packages that are referenced in config files rather than imported in source code.
92
+
93
+ ## 🤖 Using in CI
94
+
95
+ The exit code tells your pipeline whether anything needs attention:
96
+
97
+ | Exit code | Meaning |
98
+ |-----------|---------|
99
+ | `0` | No unused dependencies or known vulnerabilities |
100
+ | `1` | Unused dependencies or known vulnerabilities found |
101
+ | `2` | The analysis could not run (for example, no `package.json`) |
102
+
103
+ Deprecated packages are reported but don't fail the run. If the vulnerability lookup itself fails (network error), `securityCheckFailed` is `true` in the JSON and the run doesn't fail on that alone.
104
+
105
+ ```bash
106
+ # Fail the build on unused or vulnerable dependencies
107
+ npx dependency-detective
108
+
109
+ # Save a machine-readable report
110
+ npx dependency-detective --json > dependency-report.json
111
+ ```
112
+
113
+ With `--json`, only JSON is written to stdout:
114
+
115
+ ```json
116
+ {
117
+ "directory": "/path/to/project",
118
+ "unused": [{ "name": "moment", "version": "^2.29.4" }],
119
+ "estimatedSavingsBytes": 4404019,
120
+ "vulnerabilities": [
121
+ {
122
+ "name": "lodash",
123
+ "issues": [
124
+ {
125
+ "id": "GHSA-35jh-r3h4-6jhm",
126
+ "severity": "HIGH",
127
+ "title": "Command Injection in lodash",
128
+ "fixedIn": "4.17.21",
129
+ "url": "https://osv.dev/vulnerability/GHSA-35jh-r3h4-6jhm"
130
+ }
131
+ ]
132
+ }
133
+ ],
134
+ "notChecked": [],
135
+ "securityCheckFailed": false,
136
+ "deprecated": [{ "name": "request", "message": "request has been deprecated", "lastUpdated": "2024-01-01T00:00:00.000Z" }],
137
+ "warnings": [],
138
+ "summary": { "unused": 1, "vulnerable": 1, "deprecated": 1 }
139
+ }
140
+ ```
141
+
142
+ `deprecated` is `null` when the check is skipped with `--no-suggestions`. If the analysis can't run, the output is `{ "error": "..." }` with exit code `2`.
143
+
144
+ ## 🧩 How It Works
145
+
146
+ 1. **AST-Based Source Scanning**: The tool parses your JS/TS/JSX/TSX files using `@babel/parser` to accurately detect `import`, `require`, `export ... from`, and dynamic `import()` statements — no regex guessing
147
+ 2. **Config File Scanning**: It also checks common config files (`tailwind.config.js`, `.eslintrc`, `postcss.config.js`, `vite.config.js`, `tsconfig.json`, and more) for packages referenced outside of source code. ESLint configs are understood in both flat (`eslint.config.*`) and legacy (`.eslintrc*`, including YAML and the `eslintConfig` field in `package.json`) form, including short names such as `react` for `eslint-plugin-react` and `airbnb` for `eslint-config-airbnb`
148
+ 3. **Script Scanning**: It checks your `package.json` scripts for each package's commands, read from its `bin` field — so `tsc` counts as using `typescript` and `run-p` as using `npm-run-all`
149
+ 4. **Dependency Analysis**: It cross-references all found references with your `package.json`
150
+ 5. **Security Checking**: It queries the free OSV.dev vulnerability database for the installed version of each package (no token required)
151
+ 6. **Deprecation Analysis**: It checks the npm registry for packages whose latest version is officially deprecated
152
+ 7. **Report Generation**: It presents findings in a clear, actionable format
153
+
154
+ ## 🛠️ For Developers
155
+
156
+ ### Project Structure
157
+
158
+ ```
159
+ dependency-detective/
160
+ ├── index.js # CLI entry point
161
+ ├── package.json
162
+ └── src/
163
+ ├── analyzer.js # Main analysis logic and result display
164
+ ├── unused-detector.js # Orchestrates unused dependency detection
165
+ ├── ast-parser.js # AST-based import extraction (@babel/parser)
166
+ ├── config-scanner.js # Scans config files for package references
167
+ ├── script-scanner.js # Matches npm script commands to packages via their bin field
168
+ ├── security-checker.js # Checks vulnerabilities via OSV.dev (no token)
169
+ ├── alternative-suggester.js # Flags officially-deprecated packages
170
+ └── util/
171
+ └── concurrency.js # Concurrency-capped async map helper
172
+ ```
173
+
174
+ ### Local Development
175
+
176
+ ```bash
177
+ # Clone the repository
178
+ git clone https://github.com/Marvinkwame/dependency-detective.git
179
+ cd dependency-detective
180
+
181
+ # Install dependencies
182
+ npm install
183
+
184
+ # Link for local testing
185
+ npm link
186
+
187
+ # Run tests
188
+ npm test
189
+ ```
190
+
191
+ ## ⚠️ Limitations
192
+
193
+ - Dynamically computed imports (`require(variable)`) cannot be statically detected — use `--ignore` to exempt these packages
194
+ - Vulnerability checks read the installed version from `node_modules`; uninstalled packages are skipped
195
+ - Vulnerability data comes from OSV.dev, whose coverage and severity ratings may differ from commercial databases
196
+ - Vue/Svelte/Astro single-file components are not yet scanned for imports
197
+
198
+ ## 📝 Roadmap
199
+
200
+ - [x] Improve detection accuracy with AST parsing
201
+ - [x] Scan config files for build-tool package references
202
+ - [x] Token-free vulnerability checks via OSV.dev
203
+ - [ ] `--fix` / interactive removal of unused dependencies
204
+ - [ ] Add support for monorepos and workspaces
205
+ - [x] `--json` output and CI mode with exit codes
206
+ - [ ] Maintenance/abandonment signals for dependencies
207
+
208
+ ## 📄 License
209
+
210
+ MIT
211
+
212
+ ## 👥 Contributing
213
+
214
+ Contributions are welcome! Please feel free to submit a Pull Request.
215
+
216
+ 1. Fork the repository
217
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
218
+ 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
219
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
220
+ 5. Open a Pull Request
221
+
222
+ ## 🙏 Acknowledgements
223
+
224
+ - Thanks to all the open-source package maintainers
151
225
  - Inspired by similar tools like depcheck and npm-check
package/index.js CHANGED
@@ -1,19 +1,31 @@
1
- #!/usr/bin/env node
2
- import { program } from 'commander';
3
- import { createRequire } from 'module';
4
- const require = createRequire(import.meta.url);
5
- const packageJson = require('./package.json');
6
- import { analyzeProject } from "./src/analyzer.js"
7
- import 'dotenv/config';
8
-
9
- program
10
- .version(packageJson.version)
11
- .description('Analyzes your project dependencies to identify unused packages, security risks, and suggest alternatives')
12
- .option('-d, --directory <path>', 'project directory to analyze', process.cwd())
13
- .option('-v, --verbose', 'show detailed output')
14
- .option('--no-suggestions', 'skip suggesting alternative packages')
15
- .action(async (options) => {
16
- await analyzeProject(options);
17
- });
18
-
19
- program.parse(process.argv);
1
+ #!/usr/bin/env node
2
+
3
+ import { createRequire } from 'module';
4
+ import { program } from 'commander';
5
+ import { analyzeProject } from "./src/analyzer.js"
6
+
7
+ const require = createRequire(import.meta.url);
8
+ const { version } = require('./package.json');
9
+
10
+
11
+ program
12
+ .version(version)
13
+ .description('Analyzes your project dependencies to identify unused packages, security risks, and suggest alternatives')
14
+ .option('-d, --directory <path>', 'project directory to analyze', process.cwd())
15
+ .option('-v, --verbose', 'show detailed output')
16
+ .option('--no-suggestions', 'skip suggesting alternative packages')
17
+ .option('--ignore <packages>', 'comma-separated package names to exclude from analysis', '')
18
+ .option('--json', 'print the report as JSON (for CI and scripts)')
19
+ .addHelpText('after', `
20
+ Exit codes:
21
+ 0 no unused dependencies or known vulnerabilities
22
+ 1 unused dependencies or known vulnerabilities found
23
+ 2 the analysis could not run (e.g. no package.json)`)
24
+ .action(async (options) => {
25
+ const ignoreList = options.ignore
26
+ ? options.ignore.split(',').map(p => p.trim()).filter(Boolean)
27
+ : [];
28
+ process.exitCode = await analyzeProject({ ...options, ignore: ignoreList });
29
+ });
30
+
31
+ await program.parseAsync(process.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dependency-detective",
3
- "version": "0.1.3",
3
+ "version": "0.4.0",
4
4
  "description": "Analyzes your project's dependencies, identifies unused ones, forecasts potential security risks, and suggests better alternatives",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -9,7 +9,7 @@
9
9
  },
10
10
  "scripts": {
11
11
  "start": "node index.js",
12
- "test": "echo \"Error: no test specified\" && exit 1"
12
+ "test": "node --test"
13
13
  },
14
14
  "keywords": [
15
15
  "dependencies",
@@ -21,11 +21,11 @@
21
21
  "author": "Marvin Ackerman",
22
22
  "license": "MIT",
23
23
  "dependencies": {
24
- "axios": "^1.8.1",
24
+ "@babel/parser": "^7.29.3",
25
+ "axios": "^1.21.1",
25
26
  "chalk": "^5.4.1",
26
27
  "commander": "^13.1.0",
27
- "dotenv": "^16.4.7",
28
- "glob": "^11.0.1",
28
+ "glob": "^14.0.6",
29
29
  "ora": "^8.2.0"
30
30
  },
31
31
  "repository": {
@@ -1,64 +1,32 @@
1
- import axios from "axios";
1
+ import axios from 'axios';
2
+ import { mapWithConcurrency } from './util/concurrency.js';
2
3
 
4
+ const CONCURRENCY = 8;
3
5
 
4
- export async function suggestAlternatives(dependencies) {
5
- const alternatives = {};
6
-
7
- for (const [depName, version] of Object.entries(dependencies)) {
8
- try {
9
- const suggestion = await findBetterAlternative(depName, version);
10
- if (suggestion) {
11
- alternatives[depName] = suggestion;
12
- }
13
- } catch (error) {
14
- console.error(`Failed to find alternatives for ${depName}: ${error.message}`);
15
- }
16
- }
17
-
18
- return alternatives;
6
+ export function extractDeprecation(registryDoc) {
7
+ const latest = registryDoc?.['dist-tags']?.latest;
8
+ if (!latest) return null;
9
+ const deprecated = registryDoc.versions?.[latest]?.deprecated;
10
+ if (!deprecated) return null;
11
+ return {
12
+ deprecated: typeof deprecated === 'string' ? deprecated : 'This package is deprecated',
13
+ lastUpdated: registryDoc.time?.modified ?? null,
14
+ };
19
15
  }
20
16
 
21
- export async function findBetterAlternative(packageName, version) {
22
- try {
23
- // Fetch package data from npm registry
24
- const npmResponse = await axios.get(`https://registry.npmjs.org/${packageName}`);
25
- const packageData = npmResponse.data;
26
-
27
- // Check if the package is deprecated
28
- if (packageData.deprecated) {
29
- return {
30
- name: packageName,
31
- reason: `This package is deprecated: ${packageData.deprecated}`,
32
- downloads: packageData.downloads || 0,
33
- lastUpdated: packageData.time.modified,
34
- };
35
- }
17
+ export async function suggestAlternatives(dependencies) {
18
+ const deps = Object.keys(dependencies);
19
+ const alternatives = {};
36
20
 
37
- // Fetch alternatives from npms.io
21
+ await mapWithConcurrency(deps, CONCURRENCY, async (dep) => {
38
22
  try {
39
- const alternativesResponse = await axios.get(`https://api.npms.io/v2/package/${packageName}`);
40
- const alternativesData = alternativesResponse.data;
41
-
42
- if (alternativesData.alternatives && alternativesData.alternatives.length > 0) {
43
- const bestAlternative = alternativesData.alternatives[0];
44
- return {
45
- name: bestAlternative.package.name,
46
- reason: `Recommended alternative: ${bestAlternative.package.description}`,
47
- downloads: bestAlternative.package.downloads,
48
- lastUpdated: bestAlternative.package.date,
49
- };
50
- }
51
- } catch (error) {
52
- console.error(`No alternatives found for ${packageName} in npms.io: ${error.message}`);
23
+ const res = await axios.get(`https://registry.npmjs.org/${dep}`);
24
+ const info = extractDeprecation(res.data);
25
+ if (info) alternatives[dep] = { name: dep, ...info };
26
+ } catch {
27
+ // per-dep registry failure — omit silently
53
28
  }
29
+ });
54
30
 
55
- return null;
56
- } catch (error) {
57
- if (error.response && error.response.status === 404) {
58
- console.error(`Package ${packageName} not found in npm registry.`);
59
- } else {
60
- console.error(`Failed to fetch alternatives for ${packageName}: ${error.message}`);
61
- }
62
- return null;
63
- }
64
- }
31
+ return alternatives;
32
+ }