dependency-detective 0.1.3 → 0.2.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.
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "dependency-detective",
3
+ "version": "0.1.1",
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": "Marvin Ackerman",
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
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/Marvinkwame/dependency-detective"
34
+ },
35
+ "homepage": "https://github.com/Marvinkwame/dependency-detective#"
36
+ }
@@ -0,0 +1,64 @@
1
+ import axios from "axios";
2
+
3
+
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;
19
+ }
20
+
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
+ }
36
+
37
+ // Fetch alternatives from npms.io
38
+ 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}`);
53
+ }
54
+
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
+ }
@@ -0,0 +1,141 @@
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
+ //default dependencies for react/nextjs project
11
+ const REQUIRED_DEPENDENCIES = new Set([
12
+ 'react',
13
+ 'react-dom',
14
+ 'next',
15
+ '@types/node',
16
+ '@types/react',
17
+ '@types/react-dom',
18
+ 'eslint',
19
+ 'eslint-config-next',
20
+ 'postcss',
21
+ 'typescript',
22
+ ]);
23
+
24
+ const spinner = ora('Analyzing your project dependencies...').start();
25
+
26
+ try {
27
+ // Get package.json from the target directory
28
+ const packageJsonPath = path.join(options.directory, 'package.json');
29
+
30
+ if (!fs.existsSync(packageJsonPath)) {
31
+ spinner.fail('No package.json found in the specified directory');
32
+ return;
33
+ }
34
+
35
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
36
+ const dependencies = {
37
+ ...(packageJson.dependencies || {}),
38
+ ...(packageJson.devDependencies || {}),
39
+ };
40
+
41
+ // Filter out required dependencies
42
+ const filteredDependencies = Object.fromEntries(
43
+ Object.entries(dependencies).filter(
44
+ ([depName]) => !REQUIRED_DEPENDENCIES.has(depName)
45
+ )
46
+ );
47
+
48
+ // Identifing unused dependencies
49
+ spinner.text = 'Scanning for unused dependencies...';
50
+ const unusedDeps = await findUnusedDependencies(options.directory, filteredDependencies);
51
+
52
+ // Checking for security vulnerabilities
53
+ spinner.text = 'Checking for security vulnerabilities...';
54
+ const vulnerabilities = await checkVulnerabilities(filteredDependencies);
55
+
56
+ // Suggesting alternatives (if enabled)
57
+ let alternatives = {};
58
+ if (options.suggestions !== false) {
59
+ spinner.text = 'Finding better alternatives...';
60
+ alternatives = await suggestAlternatives(filteredDependencies);
61
+ }
62
+
63
+
64
+ spinner.succeed('Analysis complete!');
65
+
66
+ // Display results
67
+ displayResults(unusedDeps, vulnerabilities, alternatives, options.verbose);
68
+ } catch (error) {
69
+ spinner.fail('Analysis failed');
70
+ console.error(chalk.red('Error:'), error.message);
71
+ }
72
+ }
73
+
74
+
75
+
76
+
77
+ function getSavingsEstimate(unusedDeps) {
78
+
79
+ // Average size of an npm package in MB
80
+ const AVERAGE_PACKAGE_SIZE_MB = 5;
81
+
82
+ // Calculate the total estimated savings
83
+ const totalSavingsMB = unusedDeps.length * AVERAGE_PACKAGE_SIZE_MB;
84
+
85
+ // Return the formatted estimate
86
+ return `~${totalSavingsMB}MB`;
87
+ }
88
+
89
+ // Define displayResults function
90
+ function displayResults(unusedDeps, vulnerabilities, alternatives, verbose) {
91
+ console.log('\n' + chalk.bold('📦 DEPENDENCY DETECTIVE REPORT') + '\n');
92
+
93
+ // Display unused dependencies
94
+ console.log(chalk.bold('🗑️ Unused Dependencies:'));
95
+ if (unusedDeps.length === 0) {
96
+ console.log(chalk.green(' No unused dependencies found. Great job!'));
97
+ } else {
98
+ unusedDeps.forEach(dep => {
99
+ console.log(` ${chalk.yellow(dep.name)} ${chalk.dim(`v${dep.version}`)}`);
100
+ if (verbose && dep.reason) {
101
+ console.log(` ${chalk.dim(dep.reason)}`);
102
+ }
103
+ });
104
+ console.log(chalk.dim(`\n Removing these could save approximately ${getSavingsEstimate(unusedDeps)} of disk space`));
105
+ }
106
+
107
+ // Display vulnerabilities
108
+ console.log('\n' + chalk.bold('🔒 Security Vulnerabilities:'));
109
+ if (Object.keys(vulnerabilities).length === 0) {
110
+ console.log(chalk.green(' No security vulnerabilities detected. You\'re secure!'));
111
+ } else {
112
+ Object.entries(vulnerabilities).forEach(([depName, issues]) => {
113
+ console.log(` ${chalk.red(depName)} ${chalk.dim(`(${issues.length} issues)`)}`);
114
+ if (verbose) {
115
+ issues.forEach(issue => {
116
+ console.log(` - ${issue.severity.toUpperCase()}: ${issue.title}`);
117
+ console.log(` ${chalk.dim(issue.description)}`);
118
+ });
119
+ }
120
+ });
121
+ }
122
+
123
+ // Display alternative suggestions
124
+ if (Object.keys(alternatives).length > 0) {
125
+ console.log('\n' + chalk.bold('💡 Recommended Alternatives:'));
126
+ Object.entries(alternatives).forEach(([depName, suggestion]) => {
127
+ console.log(` ${chalk.blue(depName)} → ${chalk.green(suggestion.name)}`);
128
+ if (verbose) {
129
+ console.log(` ${chalk.dim(suggestion.reason)}`);
130
+ console.log(` ${chalk.dim(`Weekly downloads: ${suggestion.downloads.toLocaleString()}`)}`);
131
+ console.log(` ${chalk.dim(`Last updated: ${suggestion.lastUpdated}`)}`);
132
+ }
133
+ });
134
+ }
135
+
136
+ console.log('\n' + chalk.bold('📋 Next Steps:'));
137
+ console.log(' 1. Run with --verbose flag for more detailed information');
138
+ console.log(' 2. Consider removing unused dependencies with: npm uninstall [package-names]');
139
+ console.log(' 3. Address security vulnerabilities by updating affected packages');
140
+ console.log(' 4. Evaluate suggested alternatives for potential improvements\n');
141
+ }
@@ -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 = "5867f5b0-1275-4bff-99b3-c307c545b6dd";
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
+
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
+ }
package/README.md CHANGED
@@ -24,6 +24,21 @@ npm install -g dependency-detective
24
24
  npx dependency-detective
25
25
  ```
26
26
 
27
+ ## ⚙️ Configuration
28
+
29
+ ### Snyk API Token (optional)
30
+
31
+ Vulnerability checking requires a free Snyk account. Without a token the tool still reports unused dependencies and alternative suggestions — the vulnerability section is skipped with a clear message.
32
+
33
+ 1. Sign up at [https://snyk.io](https://snyk.io) and copy your API token from Account Settings.
34
+ 2. Create a `.env` file in your project root (or export in your shell profile):
35
+
36
+ ```
37
+ SNYK_API_TOKEN=your-token-here
38
+ ```
39
+
40
+ The tool loads `.env` automatically via dotenv.
41
+
27
42
  ## 🚀 Usage
28
43
 
29
44
  ```bash
@@ -73,16 +88,20 @@ dependency-detective --no-suggestions
73
88
  | `-d, --directory <path>` | Project directory to analyze (default: current directory) |
74
89
  | `-v, --verbose` | Show detailed output including reasons and statistics |
75
90
  | `--no-suggestions` | Skip suggesting alternative packages |
91
+ | `--ignore <packages>` | Comma-separated list of package names to exclude from all checks |
76
92
  | `--help` | Display help information |
77
93
  | `--version` | Display version number |
78
94
 
95
+ 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.
96
+
79
97
  ## 🧩 How It Works
80
98
 
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
99
+ 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
100
+ 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
101
+ 3. **Dependency Analysis**: It cross-references all found references with your `package.json`
102
+ 4. **Security Checking**: It queries the Snyk API for known vulnerabilities (requires `SNYK_API_TOKEN`)
103
+ 5. **Alternative Analysis**: It evaluates potential alternative packages based on multiple metrics
104
+ 6. **Report Generation**: It presents findings in a clear, actionable format
86
105
 
87
106
  ## 🛠️ For Developers
88
107
 
@@ -93,9 +112,11 @@ dependency-detective/
93
112
  ├── index.js # CLI entry point
94
113
  ├── package.json
95
114
  └── src/
96
- ├── analyzer.js # Main analysis logic
97
- ├── unused-detector.js # Detects unused dependencies
98
- ├── security-checker.js # Checks for vulnerabilities
115
+ ├── analyzer.js # Main analysis logic and result display
116
+ ├── unused-detector.js # Orchestrates unused dependency detection
117
+ ├── ast-parser.js # AST-based import extraction (@babel/parser)
118
+ ├── config-scanner.js # Scans config files for package references
119
+ ├── security-checker.js # Checks for vulnerabilities via Snyk API
99
120
  └── alternative-suggester.js # Suggests better alternatives
100
121
  ```
101
122
 
@@ -118,13 +139,14 @@ npm test
118
139
 
119
140
  ## ⚠️ Limitations
120
141
 
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
142
+ - Dynamically computed imports (`require(variable)`) cannot be statically detected — use `--ignore` to exempt these packages
143
+ - Security vulnerability detection requires a Snyk API token and relies on Snyk's database, which may not cover every package
123
144
  - Alternative suggestions are based on general community metrics and might not be ideal for every specific use case
124
145
 
125
146
  ## 📝 Roadmap
126
147
 
127
- - [ ] Improve detection accuracy with AST parsing
148
+ - [x] Improve detection accuracy with AST parsing
149
+ - [x] Scan config files for build-tool package references
128
150
  - [ ] Add support for monorepos and workspaces
129
151
  - [ ] Visual reporting with charts and graphs
130
152
  - [ ] Interactive mode for bulk actions on dependencies
package/index.js CHANGED
@@ -1,19 +1,26 @@
1
1
  #!/usr/bin/env node
2
- import { program } from 'commander';
2
+
3
3
  import { createRequire } from 'module';
4
- const require = createRequire(import.meta.url);
5
- const packageJson = require('./package.json');
4
+ import { program } from 'commander';
6
5
  import { analyzeProject } from "./src/analyzer.js"
7
6
  import 'dotenv/config';
8
7
 
8
+ const require = createRequire(import.meta.url);
9
+ const { version } = require('./package.json');
10
+
11
+
9
12
  program
10
- .version(packageJson.version)
13
+ .version(version)
11
14
  .description('Analyzes your project dependencies to identify unused packages, security risks, and suggest alternatives')
12
15
  .option('-d, --directory <path>', 'project directory to analyze', process.cwd())
13
16
  .option('-v, --verbose', 'show detailed output')
14
17
  .option('--no-suggestions', 'skip suggesting alternative packages')
18
+ .option('--ignore <packages>', 'comma-separated package names to exclude from analysis', '')
15
19
  .action(async (options) => {
16
- await analyzeProject(options);
20
+ const ignoreList = options.ignore
21
+ ? options.ignore.split(',').map(p => p.trim()).filter(Boolean)
22
+ : [];
23
+ await analyzeProject({ ...options, ignore: ignoreList });
17
24
  });
18
25
 
19
26
  program.parse(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.2.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",
@@ -21,6 +21,7 @@
21
21
  "author": "Marvin Ackerman",
22
22
  "license": "MIT",
23
23
  "dependencies": {
24
+ "@babel/parser": "^7.29.3",
24
25
  "axios": "^1.8.1",
25
26
  "chalk": "^5.4.1",
26
27
  "commander": "^13.1.0",
package/src/analyzer.js CHANGED
@@ -6,25 +6,11 @@ import { findUnusedDependencies } from './unused-detector.js';
6
6
  import { checkVulnerabilities } from './security-checker.js';
7
7
  import { suggestAlternatives } from './alternative-suggester.js';
8
8
 
9
- export async function analyzeProject(options) {
10
- //default dependencies for react/nextjs project
11
- const REQUIRED_DEPENDENCIES = new Set([
12
- 'react',
13
- 'react-dom',
14
- 'next',
15
- '@types/node',
16
- '@types/react',
17
- '@types/react-dom',
18
- 'eslint',
19
- 'eslint-config-next',
20
- 'postcss',
21
- 'typescript',
22
- ]);
23
-
9
+ export async function analyzeProject(options = {}) {
24
10
  const spinner = ora('Analyzing your project dependencies...').start();
11
+ const ignoreSet = new Set(options.ignore || []);
25
12
 
26
13
  try {
27
- // Get package.json from the target directory
28
14
  const packageJsonPath = path.join(options.directory, 'package.json');
29
15
 
30
16
  if (!fs.existsSync(packageJsonPath)) {
@@ -38,32 +24,24 @@ export async function analyzeProject(options) {
38
24
  ...(packageJson.devDependencies || {}),
39
25
  };
40
26
 
41
- // Filter out required dependencies
42
27
  const filteredDependencies = Object.fromEntries(
43
- Object.entries(dependencies).filter(
44
- ([depName]) => !REQUIRED_DEPENDENCIES.has(depName)
45
- )
28
+ Object.entries(dependencies).filter(([depName]) => !ignoreSet.has(depName))
46
29
  );
47
30
 
48
- // Identifing unused dependencies
49
31
  spinner.text = 'Scanning for unused dependencies...';
50
32
  const unusedDeps = await findUnusedDependencies(options.directory, filteredDependencies);
51
33
 
52
- // Checking for security vulnerabilities
53
34
  spinner.text = 'Checking for security vulnerabilities...';
54
35
  const vulnerabilities = await checkVulnerabilities(filteredDependencies);
55
36
 
56
- // Suggesting alternatives (if enabled)
57
37
  let alternatives = {};
58
38
  if (options.suggestions !== false) {
59
39
  spinner.text = 'Finding better alternatives...';
60
40
  alternatives = await suggestAlternatives(filteredDependencies);
61
41
  }
62
42
 
63
-
64
43
  spinner.succeed('Analysis complete!');
65
44
 
66
- // Display results
67
45
  displayResults(unusedDeps, vulnerabilities, alternatives, options.verbose);
68
46
  } catch (error) {
69
47
  spinner.fail('Analysis failed');
@@ -71,9 +49,6 @@ export async function analyzeProject(options) {
71
49
  }
72
50
  }
73
51
 
74
-
75
-
76
-
77
52
  function getSavingsEstimate(unusedDeps) {
78
53
 
79
54
  // Average size of an npm package in MB
@@ -106,7 +81,11 @@ function displayResults(unusedDeps, vulnerabilities, alternatives, verbose) {
106
81
 
107
82
  // Display vulnerabilities
108
83
  console.log('\n' + chalk.bold('🔒 Security Vulnerabilities:'));
109
- if (Object.keys(vulnerabilities).length === 0) {
84
+ if (vulnerabilities === null) {
85
+ console.log(chalk.yellow(' ⚠ Skipped — SNYK_API_TOKEN not set.'));
86
+ console.log(chalk.dim(' To enable: add SNYK_API_TOKEN=<your-token> to a .env file.'));
87
+ console.log(chalk.dim(' Get a free token at https://snyk.io'));
88
+ } else if (Object.keys(vulnerabilities).length === 0) {
110
89
  console.log(chalk.green(' No security vulnerabilities detected. You\'re secure!'));
111
90
  } else {
112
91
  Object.entries(vulnerabilities).forEach(([depName, issues]) => {
@@ -0,0 +1,79 @@
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
+ let content;
34
+ try {
35
+ content = await fs.promises.readFile(filePath, 'utf8');
36
+ } catch {
37
+ return referenced;
38
+ }
39
+
40
+ let ast;
41
+ try {
42
+ ast = parse(content, {
43
+ sourceType: 'unambiguous',
44
+ plugins: BABEL_PLUGINS,
45
+ errorRecovery: true,
46
+ });
47
+ } catch (err) {
48
+ console.warn(`Warning: could not parse ${filePath}: ${err.message}`);
49
+ return referenced;
50
+ }
51
+
52
+ walk(ast, {
53
+ ImportDeclaration(node) {
54
+ if (node.source?.value) referenced.add(extractPackageName(node.source.value));
55
+ },
56
+ ExportNamedDeclaration(node) {
57
+ if (node.source?.value) referenced.add(extractPackageName(node.source.value));
58
+ },
59
+ ExportAllDeclaration(node) {
60
+ if (node.source?.value) referenced.add(extractPackageName(node.source.value));
61
+ },
62
+ CallExpression(node) {
63
+ if (
64
+ node.callee?.type === 'Identifier' &&
65
+ node.callee.name === 'require' &&
66
+ node.arguments?.[0]?.type === 'StringLiteral'
67
+ ) {
68
+ referenced.add(extractPackageName(node.arguments[0].value));
69
+ }
70
+ },
71
+ ImportExpression(node) {
72
+ if (node.source?.type === 'StringLiteral') {
73
+ referenced.add(extractPackageName(node.source.value));
74
+ }
75
+ },
76
+ });
77
+
78
+ return referenced;
79
+ }