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/src/analyzer.js CHANGED
@@ -1,141 +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 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
- }
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
+ }
@@ -0,0 +1,85 @@
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
+ }
@@ -0,0 +1,128 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ const CONFIG_FILES = [
5
+ 'tailwind.config.js',
6
+ 'tailwind.config.ts',
7
+ 'postcss.config.js',
8
+ 'postcss.config.cjs',
9
+ 'babel.config.js',
10
+ 'babel.config.json',
11
+ 'jest.config.js',
12
+ 'jest.config.ts',
13
+ 'vite.config.js',
14
+ 'vite.config.ts',
15
+ 'webpack.config.js',
16
+ 'webpack.config.cjs',
17
+ 'prettier.config.js',
18
+ // ESLint flat config (default since ESLint 9)
19
+ 'eslint.config.js',
20
+ 'eslint.config.mjs',
21
+ 'eslint.config.cjs',
22
+ 'eslint.config.ts',
23
+ 'eslint.config.mts',
24
+ 'eslint.config.cts',
25
+ // ESLint legacy config
26
+ '.eslintrc',
27
+ '.eslintrc.js',
28
+ '.eslintrc.cjs',
29
+ '.eslintrc.json',
30
+ '.eslintrc.yaml',
31
+ '.eslintrc.yml',
32
+ '.babelrc',
33
+ '.babelrc.json',
34
+ 'vitest.config.js',
35
+ 'vitest.config.ts',
36
+ 'tsconfig.json',
37
+ '.stylelintrc',
38
+ '.stylelintrc.json',
39
+ 'svelte.config.js',
40
+ 'astro.config.mjs',
41
+ ];
42
+
43
+ function escapeRegex(str) {
44
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
45
+ }
46
+
47
+ export function isReferenced(content, depName) {
48
+ const pattern = new RegExp(`['"\`]${escapeRegex(depName)}['"\`/]`);
49
+ return pattern.test(content);
50
+ }
51
+
52
+ // Legacy ESLint configs can name plugins and shareable configs by short name
53
+ // ("react" for eslint-plugin-react), and YAML configs leave names unquoted.
54
+ const ESLINT_LEGACY_FILES = new Set([
55
+ '.eslintrc',
56
+ '.eslintrc.js',
57
+ '.eslintrc.cjs',
58
+ '.eslintrc.json',
59
+ '.eslintrc.yaml',
60
+ '.eslintrc.yml',
61
+ ]);
62
+
63
+ /**
64
+ * The short names ESLint accepts for a plugin or shareable-config package:
65
+ * eslint-plugin-react → react
66
+ * eslint-config-airbnb → airbnb
67
+ * @typescript-eslint/eslint-plugin → @typescript-eslint
68
+ * @scope/eslint-plugin-foo → @scope/foo
69
+ */
70
+ export function eslintShortNames(depName) {
71
+ const unscoped = depName.match(/^eslint-(?:plugin|config)-(.+)$/);
72
+ if (unscoped) return [unscoped[1]];
73
+
74
+ const scoped = depName.match(/^(@[^/]+)\/eslint-(?:plugin|config)(?:-(.+))?$/);
75
+ if (scoped) return [scoped[2] ? `${scoped[1]}/${scoped[2]}` : scoped[1]];
76
+
77
+ return [];
78
+ }
79
+
80
+ /**
81
+ * Whether a legacy ESLint config refers to depName, by full or short name,
82
+ * quoted or not. Matches `react`, `plugin:react/recommended` and rule keys
83
+ * like `react/jsx-key`, but not `react-hooks`.
84
+ */
85
+ export function isEslintReference(content, depName) {
86
+ const names = [depName, ...eslintShortNames(depName)];
87
+ if (names.length === 1) return false;
88
+ return names.some((name) =>
89
+ new RegExp(`(?:^|[\\s'"\`\\[,:])${escapeRegex(name)}(?:$|[\\s'"\`\\],/])`, 'm').test(content)
90
+ );
91
+ }
92
+
93
+ export async function scanConfigFiles(directory, dependencyNames, packageJson = {}) {
94
+ if (!Array.isArray(dependencyNames) && !dependencyNames?.[Symbol.iterator]) {
95
+ return new Set();
96
+ }
97
+
98
+ const referenced = new Set();
99
+
100
+ const check = (content, eslintLegacy) => {
101
+ for (const depName of dependencyNames) {
102
+ if (
103
+ isReferenced(content, depName) ||
104
+ (eslintLegacy && isEslintReference(content, depName))
105
+ ) {
106
+ referenced.add(depName);
107
+ }
108
+ }
109
+ };
110
+
111
+ await Promise.all(
112
+ CONFIG_FILES.map(async (configFile) => {
113
+ let content;
114
+ try {
115
+ content = await fs.promises.readFile(path.join(directory, configFile), 'utf8');
116
+ } catch {
117
+ return; // file missing or unreadable — skip
118
+ }
119
+ check(content, ESLINT_LEGACY_FILES.has(configFile));
120
+ })
121
+ );
122
+
123
+ if (packageJson?.eslintConfig) {
124
+ check(JSON.stringify(packageJson.eslintConfig), true);
125
+ }
126
+
127
+ return referenced;
128
+ }
@@ -0,0 +1,77 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ // Used when a package isn't installed, so its `bin` field can't be read.
5
+ // Only packages whose command differs from their package name are listed.
6
+ const KNOWN_COMMANDS = {
7
+ typescript: ['tsc', 'tsserver'],
8
+ 'npm-run-all': ['npm-run-all', 'run-s', 'run-p'],
9
+ 'npm-run-all2': ['npm-run-all', 'run-s', 'run-p'],
10
+ '@angular/cli': ['ng'],
11
+ '@nestjs/cli': ['nest'],
12
+ '@biomejs/biome': ['biome'],
13
+ '@playwright/test': ['playwright'],
14
+ '@changesets/cli': ['changeset'],
15
+ '@11ty/eleventy': ['eleventy'],
16
+ '@sveltejs/kit': ['svelte-kit'],
17
+ '@tauri-apps/cli': ['tauri'],
18
+ '@vue/cli-service': ['vue-cli-service'],
19
+ '@storybook/cli': ['storybook', 'sb'],
20
+ '@graphql-codegen/cli': ['graphql-codegen', 'gql-gen'],
21
+ 'ts-node': ['ts-node', 'ts-node-esm'],
22
+ 'webpack-cli': ['webpack-cli', 'webpack'],
23
+ 'http-server': ['http-server', 'hs'],
24
+ };
25
+
26
+ function escapeRegex(str) {
27
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
28
+ }
29
+
30
+ /**
31
+ * The command names a dependency can be invoked by in npm scripts: its own
32
+ * name plus every key of its `bin` field (read from node_modules). A string
33
+ * `bin` installs a command named after the package, minus any scope.
34
+ */
35
+ export function commandNames(directory, depName) {
36
+ const names = new Set([depName]);
37
+
38
+ let bin;
39
+ try {
40
+ const pkgPath = path.join(directory, 'node_modules', depName, 'package.json');
41
+ bin = JSON.parse(fs.readFileSync(pkgPath, 'utf8')).bin;
42
+ } catch {
43
+ for (const cmd of KNOWN_COMMANDS[depName] ?? []) names.add(cmd);
44
+ return [...names];
45
+ }
46
+
47
+ if (typeof bin === 'string') {
48
+ names.add(depName.startsWith('@') ? depName.split('/')[1] : depName);
49
+ } else if (bin && typeof bin === 'object') {
50
+ for (const cmd of Object.keys(bin)) names.add(cmd);
51
+ }
52
+ return [...names];
53
+ }
54
+
55
+ /**
56
+ * Whether any script invokes `command` as a whole word: at the start, after
57
+ * whitespace, a quote, `&&`/`||`/`;`/`(`, or a path such as node_modules/.bin/.
58
+ */
59
+ export function scriptsUse(scripts, command) {
60
+ const pattern = new RegExp(
61
+ `(?:^|[\\s'"/(;&|])${escapeRegex(command)}(?:$|[\\s'"/);&|])`
62
+ );
63
+ return scripts.some((script) => pattern.test(script));
64
+ }
65
+
66
+ export function findScriptReferences(directory, dependencyNames, scriptsObject = {}) {
67
+ const scripts = Object.values(scriptsObject);
68
+ const referenced = new Set();
69
+ if (scripts.length === 0) return referenced;
70
+
71
+ for (const dep of dependencyNames) {
72
+ if (commandNames(directory, dep).some((cmd) => scriptsUse(scripts, cmd))) {
73
+ referenced.add(dep);
74
+ }
75
+ }
76
+ return referenced;
77
+ }