dependency-detective 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.
package/README.md ADDED
@@ -0,0 +1,151 @@
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
151
+ - Inspired by similar tools like depcheck and npm-check
package/index.js ADDED
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { program } from 'commander';
4
+ import packageJson from './package.json' assert { type: 'json' };
5
+ import { analyzeProject } from "./src/analyzer.js"
6
+ import 'dotenv/config';
7
+
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);
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "dependency-detective",
3
+ "version": "0.1.0",
4
+ "description": "Analyzes your project's dependencies, identifies unused ones, forecasts potential security risks, and suggests better alternatives",
5
+ "main": "index.js",
6
+ "type": "module",
7
+ "bin": {
8
+ "dependency-detective": "./index.js"
9
+ },
10
+ "scripts": {
11
+ "start": "node index.js",
12
+ "test": "echo \"Error: no test specified\" && exit 1"
13
+ },
14
+ "keywords": [
15
+ "dependencies",
16
+ "npm",
17
+ "node",
18
+ "security",
19
+ "optimization"
20
+ ],
21
+ "author": "Your Name",
22
+ "license": "MIT",
23
+ "dependencies": {
24
+ "axios": "^1.8.1",
25
+ "chalk": "^5.4.1",
26
+ "commander": "^13.1.0",
27
+ "dotenv": "^16.4.7",
28
+ "glob": "^11.0.1",
29
+ "ora": "^8.2.0"
30
+ }
31
+ }
@@ -0,0 +1,66 @@
1
+ import axios from "axios";
2
+
3
+
4
+ export async function suggestAlternatives(dependencies) {
5
+ const alternatives = {};
6
+
7
+ // In a production tool, you'd query actual package data from npm or similar
8
+ // This is a simplified example with mock data
9
+ for (const [depName, version] of Object.entries(dependencies)) {
10
+ try {
11
+ const suggestion = await findBetterAlternative(depName, version);
12
+ if (suggestion) {
13
+ alternatives[depName] = suggestion;
14
+ }
15
+ } catch (error) {
16
+ console.error(`Failed to find alternatives for ${depName}: ${error.message}`);
17
+ }
18
+ }
19
+
20
+ return alternatives;
21
+ }
22
+
23
+ export async function findBetterAlternative(packageName, version) {
24
+ try {
25
+ // Fetch package data from npm registry
26
+ const npmResponse = await axios.get(`https://registry.npmjs.org/${packageName}`);
27
+ const packageData = npmResponse.data;
28
+
29
+ // Check if the package is deprecated
30
+ if (packageData.deprecated) {
31
+ return {
32
+ name: packageName,
33
+ reason: `This package is deprecated: ${packageData.deprecated}`,
34
+ downloads: packageData.downloads || 0,
35
+ lastUpdated: packageData.time.modified,
36
+ };
37
+ }
38
+
39
+ // Fetch alternatives from npms.io
40
+ try {
41
+ const alternativesResponse = await axios.get(`https://api.npms.io/v2/package/${packageName}`);
42
+ const alternativesData = alternativesResponse.data;
43
+
44
+ if (alternativesData.alternatives && alternativesData.alternatives.length > 0) {
45
+ const bestAlternative = alternativesData.alternatives[0];
46
+ return {
47
+ name: bestAlternative.package.name,
48
+ reason: `Recommended alternative: ${bestAlternative.package.description}`,
49
+ downloads: bestAlternative.package.downloads,
50
+ lastUpdated: bestAlternative.package.date,
51
+ };
52
+ }
53
+ } catch (error) {
54
+ console.error(`No alternatives found for ${packageName} in npms.io: ${error.message}`);
55
+ }
56
+
57
+ return null;
58
+ } catch (error) {
59
+ if (error.response && error.response.status === 404) {
60
+ console.error(`Package ${packageName} not found in npm registry.`);
61
+ } else {
62
+ console.error(`Failed to fetch alternatives for ${packageName}: ${error.message}`);
63
+ }
64
+ return null;
65
+ }
66
+ }
@@ -0,0 +1,139 @@
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 async function analyzeProject(options) {
10
+ const REQUIRED_DEPENDENCIES = new Set([
11
+ 'react',
12
+ 'react-dom',
13
+ 'next',
14
+ '@types/node',
15
+ '@types/react',
16
+ '@types/react-dom',
17
+ 'eslint',
18
+ 'eslint-config-next',
19
+ 'postcss',
20
+ 'typescript',
21
+ ]);
22
+
23
+ const spinner = ora('Analyzing your project dependencies...').start();
24
+
25
+ try {
26
+ // Get package.json from the target directory
27
+ const packageJsonPath = path.join(options.directory, 'package.json');
28
+
29
+ if (!fs.existsSync(packageJsonPath)) {
30
+ spinner.fail('No package.json found in the specified directory');
31
+ return;
32
+ }
33
+
34
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
35
+ const dependencies = {
36
+ ...(packageJson.dependencies || {}),
37
+ ...(packageJson.devDependencies || {}),
38
+ };
39
+
40
+ // Filter out required dependencies
41
+ const filteredDependencies = Object.fromEntries(
42
+ Object.entries(dependencies).filter(
43
+ ([depName]) => !REQUIRED_DEPENDENCIES.has(depName)
44
+ )
45
+ );
46
+
47
+ // 1. Identify unused dependencies
48
+ spinner.text = 'Scanning for unused dependencies...';
49
+ const unusedDeps = await findUnusedDependencies(options.directory, filteredDependencies);
50
+
51
+ // 2. Check for security vulnerabilities
52
+ spinner.text = 'Checking for security vulnerabilities...';
53
+ const vulnerabilities = await checkVulnerabilities(filteredDependencies);
54
+
55
+ // 3. Suggest alternatives (if enabled)
56
+ let alternatives = {};
57
+ if (options.suggestions !== false) {
58
+ spinner.text = 'Finding better alternatives...';
59
+ alternatives = await suggestAlternatives(filteredDependencies);
60
+ }
61
+
62
+ // Complete the analysis
63
+ spinner.succeed('Analysis complete!');
64
+
65
+ // Display results
66
+ displayResults(unusedDeps, vulnerabilities, alternatives, options.verbose);
67
+ } catch (error) {
68
+ spinner.fail('Analysis failed');
69
+ console.error(chalk.red('Error:'), error.message);
70
+ }
71
+ }
72
+
73
+ // analyzer.js or index.js
74
+
75
+ // Define getSavingsEstimate function
76
+ function getSavingsEstimate(unusedDeps) {
77
+ // Average size of an npm package in MB
78
+ const AVERAGE_PACKAGE_SIZE_MB = 5;
79
+
80
+ // Calculate the total estimated savings
81
+ const totalSavingsMB = unusedDeps.length * AVERAGE_PACKAGE_SIZE_MB;
82
+
83
+ // Return the formatted estimate
84
+ return `~${totalSavingsMB}MB`;
85
+ }
86
+
87
+ // Define displayResults function
88
+ function displayResults(unusedDeps, vulnerabilities, alternatives, verbose) {
89
+ console.log('\n' + chalk.bold('📦 DEPENDENCY DETECTIVE REPORT') + '\n');
90
+
91
+ // Display unused dependencies
92
+ console.log(chalk.bold('🗑️ Unused Dependencies:'));
93
+ if (unusedDeps.length === 0) {
94
+ console.log(chalk.green(' No unused dependencies found. Great job!'));
95
+ } else {
96
+ unusedDeps.forEach(dep => {
97
+ console.log(` ${chalk.yellow(dep.name)} ${chalk.dim(`v${dep.version}`)}`);
98
+ if (verbose && dep.reason) {
99
+ console.log(` ${chalk.dim(dep.reason)}`);
100
+ }
101
+ });
102
+ console.log(chalk.dim(`\n Removing these could save approximately ${getSavingsEstimate(unusedDeps)} of disk space`));
103
+ }
104
+
105
+ // Display vulnerabilities
106
+ console.log('\n' + chalk.bold('🔒 Security Vulnerabilities:'));
107
+ if (Object.keys(vulnerabilities).length === 0) {
108
+ console.log(chalk.green(' No security vulnerabilities detected. You\'re secure!'));
109
+ } else {
110
+ Object.entries(vulnerabilities).forEach(([depName, issues]) => {
111
+ console.log(` ${chalk.red(depName)} ${chalk.dim(`(${issues.length} issues)`)}`);
112
+ if (verbose) {
113
+ issues.forEach(issue => {
114
+ console.log(` - ${issue.severity.toUpperCase()}: ${issue.title}`);
115
+ console.log(` ${chalk.dim(issue.description)}`);
116
+ });
117
+ }
118
+ });
119
+ }
120
+
121
+ // Display alternative suggestions
122
+ if (Object.keys(alternatives).length > 0) {
123
+ console.log('\n' + chalk.bold('💡 Recommended Alternatives:'));
124
+ Object.entries(alternatives).forEach(([depName, suggestion]) => {
125
+ console.log(` ${chalk.blue(depName)} → ${chalk.green(suggestion.name)}`);
126
+ if (verbose) {
127
+ console.log(` ${chalk.dim(suggestion.reason)}`);
128
+ console.log(` ${chalk.dim(`Weekly downloads: ${suggestion.downloads.toLocaleString()}`)}`);
129
+ console.log(` ${chalk.dim(`Last updated: ${suggestion.lastUpdated}`)}`);
130
+ }
131
+ });
132
+ }
133
+
134
+ console.log('\n' + chalk.bold('📋 Next Steps:'));
135
+ console.log(' 1. Run with --verbose flag for more detailed information');
136
+ console.log(' 2. Consider removing unused dependencies with: npm uninstall [package-names]');
137
+ console.log(' 3. Address security vulnerabilities by updating affected packages');
138
+ console.log(' 4. Evaluate suggested alternatives for potential improvements\n');
139
+ }
@@ -0,0 +1,62 @@
1
+ import https from "https";
2
+ import axios from "axios";
3
+
4
+ export async function checkVulnerabilities(dependencies) {
5
+ const vulnerabilities = {};
6
+
7
+ for (const [depName, version] of Object.entries(dependencies)) {
8
+ try {
9
+ const issues = await checkPackageVulnerabilities(depName, version);
10
+ if (issues.length > 0) {
11
+ vulnerabilities[depName] = issues;
12
+ }
13
+ } catch (error) {
14
+ console.error(
15
+ `Failed to check vulnerabilities for ${depName}: ${error.message}`
16
+ );
17
+ }
18
+ }
19
+
20
+ return vulnerabilities;
21
+ }
22
+
23
+ export async function checkPackageVulnerabilities(packageName, version) {
24
+ try {
25
+ const SNYK_API_TOKEN = process.env.SNYK_API_TOKEN; // Ensure you set this environment variable
26
+ if (!SNYK_API_TOKEN) {
27
+ throw new Error(
28
+ "Snyk API token is missing. Please set the SNYK_API_TOKEN environment variable."
29
+ );
30
+ }
31
+
32
+ const response = await axios.get(
33
+ `https://snyk.io/api/v1/test/npm/${packageName}/${version}`,
34
+ {
35
+ headers: {
36
+ Authorization: `token ${SNYK_API_TOKEN}`,
37
+ },
38
+ }
39
+ );
40
+
41
+ const vulnerabilities = response.data.issues.vulnerabilities;
42
+
43
+ return vulnerabilities.map((vuln) => ({
44
+ severity: vuln.severity,
45
+ title: vuln.title,
46
+ description: vuln.description,
47
+ }));
48
+ } catch (error) {
49
+ if (error.response && error.response.status === 401) {
50
+ console.error(
51
+ `Failed to authenticate with Snyk API. Please check your SNYK_API_TOKEN.`
52
+ );
53
+ } else if (error.response && error.response.status === 404) {
54
+ console.error(`Package ${packageName} not found in Snyk database.`);
55
+ } else {
56
+ console.error(
57
+ `Failed to fetch vulnerabilities for ${packageName}: ${error.message}`
58
+ );
59
+ }
60
+ return [];
61
+ }
62
+ }
@@ -0,0 +1,71 @@
1
+ //const fs = require('fs');
2
+ //const path = require('path');
3
+ //const glob = require('glob');
4
+
5
+ import fs from "fs"
6
+ import path from "path"
7
+ import { glob } from "glob"
8
+
9
+ export async function findUnusedDependencies(directory, dependencies) {
10
+ const unusedDeps = [];
11
+ const allDeps = Object.keys(dependencies);
12
+
13
+ // Get all JavaScript/TypeScript files in the project
14
+ const files = glob.sync('**/*.{js,jsx,ts,tsx}', {
15
+ cwd: directory,
16
+ ignore: ['**/node_modules/**', '**/dist/**', '**/build/**'],
17
+ });
18
+
19
+ const fileContents = files.map(file =>
20
+ fs.readFileSync(path.join(directory, file), 'utf8')
21
+ );
22
+
23
+ allDeps.forEach(dep => {
24
+ const version = dependencies[dep];
25
+ let isUsed = false;
26
+
27
+ // Common import/require patterns
28
+ const importPatterns = [
29
+ new RegExp(`import.*from\\s+['"]${dep}['\"]`),
30
+ new RegExp(`import\\s+['"]${dep}['\"]`),
31
+ new RegExp(`require\\s*\\(\\s*['"]${dep}['\"]\\s*\\)`),
32
+ new RegExp(`import\\s*\\(\\s*['"]${dep}['\"]\\s*\\)`),
33
+ ];
34
+
35
+ // Also check for submodule imports
36
+ const submodulePattern = new RegExp(`import.*from\\s+['"]${dep}/`);
37
+ const submoduleRequirePattern = new RegExp(`require\\s*\\(\\s*['"]${dep}/`);
38
+
39
+ // Check if the dependency is mentioned in any file
40
+ for (const content of fileContents) {
41
+ if (
42
+ importPatterns.some(pattern => pattern.test(content)) ||
43
+ submodulePattern.test(content) ||
44
+ submoduleRequirePattern.test(content)
45
+ ) {
46
+ isUsed = true;
47
+ break;
48
+ }
49
+ }
50
+
51
+ // Check package.json for dependencies that might be used in scripts
52
+ const packageJson = JSON.parse(fs.readFileSync(path.join(directory, 'package.json'), 'utf8'));
53
+ const scripts = packageJson.scripts || {};
54
+
55
+ if (!isUsed) {
56
+ // Check if it's used in npm scripts
57
+ isUsed = Object.values(scripts).some(script => script.includes(dep));
58
+ }
59
+
60
+ // If the dependency is still not found to be used, add it to the unused list
61
+ if (!isUsed) {
62
+ unusedDeps.push({
63
+ name: dep,
64
+ version,
65
+ reason: `Not imported or used in scripts`,
66
+ });
67
+ }
68
+ });
69
+
70
+ return unusedDeps;
71
+ }