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
@@ -1,62 +1,69 @@
1
- import https from "https";
2
- import axios from "axios";
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import axios from 'axios';
4
+ import { mapWithConcurrency } from './util/concurrency.js';
3
5
 
4
- export async function checkVulnerabilities(dependencies) {
5
- const vulnerabilities = {};
6
+ const OSV_ENDPOINT = 'https://api.osv.dev/v1/query';
7
+ const CONCURRENCY = 8;
6
8
 
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;
9
+ function fixedVersions(vuln, packageName) {
10
+ const fixed = new Set();
11
+ for (const affected of vuln.affected ?? []) {
12
+ if (affected.package?.name !== packageName) continue;
13
+ for (const range of affected.ranges ?? []) {
14
+ for (const event of range.events ?? []) {
15
+ if (event.fixed) fixed.add(event.fixed);
12
16
  }
13
- } catch (error) {
14
- console.error(
15
- `Failed to check vulnerabilities for ${depName}: ${error.message}`
16
- );
17
17
  }
18
18
  }
19
+ return fixed.size > 0 ? [...fixed].join(', ') : null;
20
+ }
19
21
 
20
- return vulnerabilities;
22
+ export function mapOsvVulns(vulns = [], packageName) {
23
+ return vulns.map((v) => ({
24
+ id: v.id ?? null,
25
+ severity: v.database_specific?.severity ?? 'UNKNOWN',
26
+ title: v.summary ?? v.id ?? 'Unknown vulnerability',
27
+ fixedIn: fixedVersions(v, packageName),
28
+ url: v.id ? `https://osv.dev/vulnerability/${v.id}` : null,
29
+ }));
21
30
  }
22
31
 
23
- export async function checkPackageVulnerabilities(packageName, version) {
32
+ export function resolveInstalledVersion(directory, dep) {
24
33
  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
- );
34
+ const pkgPath = path.join(directory, 'node_modules', dep, 'package.json');
35
+ return JSON.parse(fs.readFileSync(pkgPath, 'utf8')).version || null;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
40
 
41
- const vulnerabilities = response.data.issues.vulnerabilities;
41
+ export async function checkVulnerabilities(dependencies, directory) {
42
+ const deps = Object.keys(dependencies);
43
+ const vulnerabilities = {};
44
+ const skipped = [];
45
+ let attempted = 0;
46
+ let errored = 0;
42
47
 
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
- );
48
+ await mapWithConcurrency(deps, CONCURRENCY, async (dep) => {
49
+ const version = resolveInstalledVersion(directory, dep);
50
+ if (!version) {
51
+ skipped.push(dep);
52
+ return;
59
53
  }
60
- return [];
61
- }
54
+ attempted++;
55
+ try {
56
+ const res = await axios.post(OSV_ENDPOINT, {
57
+ version,
58
+ package: { name: dep, ecosystem: 'npm' },
59
+ });
60
+ const issues = mapOsvVulns(res.data?.vulns, dep);
61
+ if (issues.length > 0) vulnerabilities[dep] = issues;
62
+ } catch {
63
+ errored++;
64
+ }
65
+ });
66
+
67
+ const failed = attempted > 0 && errored === attempted;
68
+ return { vulnerabilities, skipped, failed };
62
69
  }
@@ -1,71 +1,69 @@
1
- //const fs = require('fs');
2
- //const path = require('path');
3
- //const glob = require('glob');
1
+ import path from 'path';
2
+ import { glob } from 'glob';
3
+ import { parseFileImports } from './ast-parser.js';
4
+ import { scanConfigFiles } from './config-scanner.js';
5
+ import { findScriptReferences } from './script-scanner.js';
4
6
 
5
- import fs from "fs"
6
- import path from "path"
7
- import { glob } from "glob"
7
+ export function resolveTypesUsage(referenced, deps) {
8
+ const used = new Set();
9
+ for (const dep of deps) {
10
+ if (!dep.startsWith('@types/')) continue;
11
+ if (dep === '@types/node') {
12
+ used.add(dep);
13
+ continue;
14
+ }
15
+ const base = dep.slice('@types/'.length);
16
+ // @types encodes scoped packages as `scope__name` → `@scope/name`
17
+ const baseName = base.includes('__') ? '@' + base.replace('__', '/') : base;
18
+ if (referenced.has(baseName)) used.add(dep);
19
+ }
20
+ return used;
21
+ }
8
22
 
9
- export async function findUnusedDependencies(directory, dependencies) {
10
- const unusedDeps = [];
23
+ export async function findUnusedDependencies(directory, dependencies, packageJson) {
11
24
  const allDeps = Object.keys(dependencies);
25
+ const warnings = [];
12
26
 
13
- // Get all JavaScript/TypeScript files in the project
14
- const files = glob.sync('**/*.{js,jsx,ts,tsx}', {
27
+ const files = await glob('**/*.{js,jsx,ts,tsx,mjs,cjs}', {
15
28
  cwd: directory,
16
29
  ignore: ['**/node_modules/**', '**/dist/**', '**/build/**'],
17
30
  });
18
31
 
19
- const fileContents = files.map(file =>
20
- fs.readFileSync(path.join(directory, file), 'utf8')
32
+ const parsed = await Promise.all(
33
+ files.map((file) => parseFileImports(path.join(directory, file)))
21
34
  );
22
35
 
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
- }
36
+ const allDepsSet = new Set(allDeps);
37
+ const referenced = new Set();
38
+ const allReferenced = new Set();
39
+ for (const { referenced: fileRefs, warnings: fileWarnings } of parsed) {
40
+ for (const pkg of fileRefs) {
41
+ allReferenced.add(pkg);
42
+ if (allDepsSet.has(pkg)) referenced.add(pkg);
49
43
  }
44
+ warnings.push(...fileWarnings);
45
+ }
50
46
 
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 || {};
47
+ const configReferenced = await scanConfigFiles(directory, allDeps, packageJson);
48
+ for (const pkg of configReferenced) referenced.add(pkg);
54
49
 
55
- if (!isUsed) {
56
- // Check if it's used in npm scripts
57
- isUsed = Object.values(scripts).some(script => script.includes(dep));
58
- }
50
+ const scriptReferenced = findScriptReferences(directory, allDeps, packageJson.scripts);
51
+ for (const pkg of scriptReferenced) referenced.add(pkg);
52
+
53
+ // @types/* resolution: use the full referenced set (all imports, not only deps)
54
+ const typesUsed = resolveTypesUsage(allReferenced, allDeps);
55
+ for (const dep of typesUsed) referenced.add(dep);
59
56
 
60
- // If the dependency is still not found to be used, add it to the unused list
61
- if (!isUsed) {
57
+ const unusedDeps = [];
58
+ for (const dep of allDeps) {
59
+ if (!referenced.has(dep)) {
62
60
  unusedDeps.push({
63
61
  name: dep,
64
- version,
65
- reason: `Not imported or used in scripts`,
62
+ version: dependencies[dep],
63
+ reason: 'Not imported in any source or config file',
66
64
  });
67
65
  }
68
- });
66
+ }
69
67
 
70
- return unusedDeps;
71
- }
68
+ return { unusedDeps, warnings };
69
+ }
@@ -0,0 +1,15 @@
1
+ export async function mapWithConcurrency(items, limit, fn) {
2
+ const results = new Array(items.length);
3
+ let index = 0;
4
+
5
+ async function worker() {
6
+ while (index < items.length) {
7
+ const current = index++;
8
+ results[current] = await fn(items[current], current);
9
+ }
10
+ }
11
+
12
+ const workerCount = Math.min(limit, items.length);
13
+ await Promise.all(Array.from({ length: workerCount }, () => worker()));
14
+ return results;
15
+ }
@@ -0,0 +1,28 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { extractDeprecation } from '../src/alternative-suggester.js';
4
+
5
+ test('extractDeprecation returns message for deprecated latest version', () => {
6
+ const doc = {
7
+ 'dist-tags': { latest: '2.88.2' },
8
+ versions: { '2.88.2': { deprecated: 'request has been deprecated' } },
9
+ time: { modified: '2020-01-01T00:00:00.000Z' },
10
+ };
11
+ assert.deepEqual(extractDeprecation(doc), {
12
+ deprecated: 'request has been deprecated',
13
+ lastUpdated: '2020-01-01T00:00:00.000Z',
14
+ });
15
+ });
16
+
17
+ test('extractDeprecation returns null for a healthy package', () => {
18
+ const doc = {
19
+ 'dist-tags': { latest: '5.0.0' },
20
+ versions: { '5.0.0': {} },
21
+ time: { modified: '2024-01-01T00:00:00.000Z' },
22
+ };
23
+ assert.equal(extractDeprecation(doc), null);
24
+ });
25
+
26
+ test('extractDeprecation returns null when latest is missing', () => {
27
+ assert.equal(extractDeprecation({}), null);
28
+ });
@@ -0,0 +1,97 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { spawnSync } from 'node:child_process';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { runAnalysis, exitCodeFor } from '../src/analyzer.js';
9
+
10
+ const cli = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'index.js');
11
+
12
+ // Packages are never installed in these projects, so the security check skips
13
+ // them and, with suggestions off, no network calls are made.
14
+ function tempProject(packageJson, files = {}) {
15
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dd-analyzer-'));
16
+ if (packageJson) {
17
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(packageJson));
18
+ }
19
+ for (const [name, content] of Object.entries(files)) {
20
+ fs.writeFileSync(path.join(dir, name), content);
21
+ }
22
+ return dir;
23
+ }
24
+
25
+ function runCli(args) {
26
+ const res = spawnSync(process.execPath, [cli, ...args], { encoding: 'utf8' });
27
+ return { code: res.status, stdout: res.stdout, stderr: res.stderr };
28
+ }
29
+
30
+ const emptyReport = {
31
+ unused: [],
32
+ vulnerabilities: [],
33
+ deprecated: [],
34
+ };
35
+
36
+ test('exitCodeFor is 0 for a clean report', () => {
37
+ assert.equal(exitCodeFor(emptyReport), 0);
38
+ });
39
+
40
+ test('exitCodeFor is 1 when there are unused deps or vulnerabilities', () => {
41
+ assert.equal(exitCodeFor({ ...emptyReport, unused: [{ name: 'x' }] }), 1);
42
+ assert.equal(exitCodeFor({ ...emptyReport, vulnerabilities: [{ name: 'x', issues: [{}] }] }), 1);
43
+ });
44
+
45
+ test('exitCodeFor ignores deprecated packages', () => {
46
+ assert.equal(exitCodeFor({ ...emptyReport, deprecated: [{ name: 'request' }] }), 0);
47
+ });
48
+
49
+ test('runAnalysis returns a plain report object', async () => {
50
+ const dir = tempProject(
51
+ { dependencies: { express: '^4.0.0', lodash: '^4.0.0' } },
52
+ { 'index.js': "import express from 'express';\n" }
53
+ );
54
+ const report = await runAnalysis({ directory: dir, suggestions: false });
55
+ assert.deepEqual(report.unused, [{ name: 'lodash', version: '^4.0.0' }]);
56
+ assert.deepEqual(report.vulnerabilities, []);
57
+ assert.deepEqual(report.notChecked.sort(), ['express', 'lodash']);
58
+ assert.equal(report.securityCheckFailed, false);
59
+ assert.equal(report.deprecated, null);
60
+ assert.deepEqual(report.summary, { unused: 1, vulnerable: 0, deprecated: 0 });
61
+ });
62
+
63
+ test('--json prints only JSON and exits 1 when unused deps are found', () => {
64
+ const dir = tempProject(
65
+ { dependencies: { lodash: '^4.0.0' } },
66
+ { 'index.js': 'console.log(1);\n' }
67
+ );
68
+ const { code, stdout } = runCli(['--json', '--no-suggestions', '-d', dir]);
69
+ assert.equal(code, 1);
70
+ const report = JSON.parse(stdout);
71
+ assert.deepEqual(report.unused, [{ name: 'lodash', version: '^4.0.0' }]);
72
+ });
73
+
74
+ test('--json exits 0 for a clean project', () => {
75
+ const dir = tempProject(
76
+ { dependencies: { lodash: '^4.0.0' } },
77
+ { 'index.js': "require('lodash');\n" }
78
+ );
79
+ const { code, stdout } = runCli(['--json', '--no-suggestions', '-d', dir]);
80
+ assert.equal(code, 0);
81
+ assert.deepEqual(JSON.parse(stdout).unused, []);
82
+ });
83
+
84
+ test('missing package.json exits 2, with a JSON error in --json mode', () => {
85
+ const dir = tempProject(null);
86
+ const json = runCli(['--json', '-d', dir]);
87
+ assert.equal(json.code, 2);
88
+ assert.match(JSON.parse(json.stdout).error, /package\.json/);
89
+
90
+ const human = runCli(['-d', dir]);
91
+ assert.equal(human.code, 2);
92
+ });
93
+
94
+ test('human-readable mode also exits 1 when unused deps are found', () => {
95
+ const dir = tempProject({ dependencies: { lodash: '^4.0.0' } }, { 'a.js': '1;\n' });
96
+ assert.equal(runCli(['--no-suggestions', '-d', dir]).code, 1);
97
+ });
@@ -0,0 +1,32 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { extractPackageName, parseFileImports } from '../src/ast-parser.js';
6
+
7
+ const here = path.dirname(fileURLToPath(import.meta.url));
8
+
9
+ test('extractPackageName handles bare, scoped, subpath, relative', () => {
10
+ assert.equal(extractPackageName('express'), 'express');
11
+ assert.equal(extractPackageName('lodash/get'), 'lodash');
12
+ assert.equal(extractPackageName('@babel/core'), '@babel/core');
13
+ assert.equal(extractPackageName('@babel/core/lib/x'), '@babel/core');
14
+ assert.equal(extractPackageName('./local'), './local');
15
+ });
16
+
17
+ test('parseFileImports captures import, require, dynamic import, export-from', async () => {
18
+ const { referenced, warnings } = await parseFileImports(
19
+ path.join(here, 'fixtures', 'sample-imports.js')
20
+ );
21
+ assert.ok(referenced.has('express'));
22
+ assert.ok(referenced.has('chalk'));
23
+ assert.ok(referenced.has('ora'));
24
+ assert.ok(referenced.has('lodash'));
25
+ assert.deepEqual(warnings, []);
26
+ });
27
+
28
+ test('parseFileImports returns empty result for missing file', async () => {
29
+ const { referenced, warnings } = await parseFileImports('/no/such/file.js');
30
+ assert.equal(referenced.size, 0);
31
+ assert.deepEqual(warnings, []);
32
+ });
@@ -0,0 +1,24 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mapWithConcurrency } from '../src/util/concurrency.js';
4
+
5
+ test('maps all items preserving input order', async () => {
6
+ const out = await mapWithConcurrency([1, 2, 3, 4], 2, async (x) => x * 2);
7
+ assert.deepEqual(out, [2, 4, 6, 8]);
8
+ });
9
+
10
+ test('never runs more than `limit` concurrently', async () => {
11
+ let active = 0;
12
+ let max = 0;
13
+ await mapWithConcurrency([1, 2, 3, 4, 5, 6], 2, async () => {
14
+ active++;
15
+ max = Math.max(max, active);
16
+ await new Promise((r) => setTimeout(r, 10));
17
+ active--;
18
+ });
19
+ assert.ok(max <= 2, `observed max concurrency ${max} exceeded 2`);
20
+ });
21
+
22
+ test('empty input returns empty array', async () => {
23
+ assert.deepEqual(await mapWithConcurrency([], 4, async (x) => x), []);
24
+ });
@@ -0,0 +1,87 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { isReferenced, eslintShortNames, isEslintReference, scanConfigFiles } from '../src/config-scanner.js';
7
+
8
+ test('matches quoted references and subpaths', () => {
9
+ assert.ok(isReferenced(`import x from 'tailwindcss'`, 'tailwindcss'));
10
+ assert.ok(isReferenced(`require('tailwindcss/plugin')`, 'tailwindcss'));
11
+ assert.ok(isReferenced(`plugins: ["@tailwindcss/forms"]`, '@tailwindcss/forms'));
12
+ });
13
+
14
+ test('does not match unrelated substrings', () => {
15
+ assert.ok(!isReferenced(`// tailwindcss-typography notes`, 'tailwindcss'));
16
+ assert.ok(!isReferenced(`const tailwindcssHelper = 1`, 'tailwindcss'));
17
+ });
18
+
19
+ test('eslintShortNames maps plugin and config packages to their short names', () => {
20
+ assert.deepEqual(eslintShortNames('eslint-plugin-react'), ['react']);
21
+ assert.deepEqual(eslintShortNames('eslint-config-airbnb'), ['airbnb']);
22
+ assert.deepEqual(eslintShortNames('@typescript-eslint/eslint-plugin'), ['@typescript-eslint']);
23
+ assert.deepEqual(eslintShortNames('@scope/eslint-plugin-foo'), ['@scope/foo']);
24
+ assert.deepEqual(eslintShortNames('@vue/eslint-config-typescript'), ['@vue/typescript']);
25
+ assert.deepEqual(eslintShortNames('@scope/eslint-config'), ['@scope']);
26
+ assert.deepEqual(eslintShortNames('react'), []);
27
+ assert.deepEqual(eslintShortNames('eslint'), []);
28
+ });
29
+
30
+ test('isEslintReference matches short names in legacy JSON and YAML configs', () => {
31
+ assert.ok(isEslintReference(`{ "plugins": ["react"] }`, 'eslint-plugin-react'));
32
+ assert.ok(isEslintReference(`{ "extends": ["plugin:react/recommended"] }`, 'eslint-plugin-react'));
33
+ assert.ok(isEslintReference(`{ "rules": { "react/jsx-key": "error" } }`, 'eslint-plugin-react'));
34
+ assert.ok(isEslintReference(`extends:\n - airbnb\n`, 'eslint-config-airbnb'));
35
+ assert.ok(isEslintReference(`extends: airbnb/hooks`, 'eslint-config-airbnb'));
36
+ assert.ok(isEslintReference(`{ "extends": ["plugin:@typescript-eslint/recommended"] }`, '@typescript-eslint/eslint-plugin'));
37
+ assert.ok(isEslintReference(`{ "plugins": ["eslint-plugin-react"] }`, 'eslint-plugin-react'));
38
+ });
39
+
40
+ test('isEslintReference does not match other packages sharing a prefix', () => {
41
+ assert.ok(!isEslintReference(`{ "plugins": ["react-hooks"] }`, 'eslint-plugin-react'));
42
+ assert.ok(!isEslintReference(`{ "extends": ["airbnb-base"] }`, 'eslint-config-airbnb'));
43
+ });
44
+
45
+ function tempProject(files) {
46
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dd-eslint-'));
47
+ for (const [name, content] of Object.entries(files)) {
48
+ fs.writeFileSync(path.join(dir, name), content);
49
+ }
50
+ return dir;
51
+ }
52
+
53
+ test('scanConfigFiles reads eslint.config.mjs flat config', async () => {
54
+ const dir = tempProject({
55
+ 'eslint.config.mjs': `import js from '@eslint/js';\nimport react from 'eslint-plugin-react';\nexport default [js.configs.recommended, react.configs.flat.recommended];\n`,
56
+ });
57
+ const found = await scanConfigFiles(dir, ['@eslint/js', 'eslint-plugin-react', 'lodash']);
58
+ assert.deepEqual([...found].sort(), ['@eslint/js', 'eslint-plugin-react']);
59
+ });
60
+
61
+ test('scanConfigFiles resolves short names in .eslintrc.yml', async () => {
62
+ const dir = tempProject({
63
+ '.eslintrc.yml': `extends:\n - airbnb\n - plugin:react/recommended\nplugins:\n - "@typescript-eslint"\n`,
64
+ });
65
+ const found = await scanConfigFiles(dir, [
66
+ 'eslint-config-airbnb',
67
+ 'eslint-plugin-react',
68
+ '@typescript-eslint/eslint-plugin',
69
+ 'eslint-plugin-vue',
70
+ ]);
71
+ assert.deepEqual([...found].sort(), [
72
+ '@typescript-eslint/eslint-plugin',
73
+ 'eslint-config-airbnb',
74
+ 'eslint-plugin-react',
75
+ ]);
76
+ });
77
+
78
+ test('scanConfigFiles reads the eslintConfig field of package.json', async () => {
79
+ const dir = tempProject({});
80
+ const packageJson = { eslintConfig: { extends: ['prettier'], plugins: ['import'] } };
81
+ const found = await scanConfigFiles(
82
+ dir,
83
+ ['eslint-config-prettier', 'eslint-plugin-import', 'eslint-plugin-vue'],
84
+ packageJson
85
+ );
86
+ assert.deepEqual([...found].sort(), ['eslint-config-prettier', 'eslint-plugin-import']);
87
+ });
@@ -0,0 +1,6 @@
1
+ import express from 'express';
2
+ const chalk = require('chalk');
3
+ import('ora').then(() => {});
4
+ export { get } from 'lodash/get';
5
+ import fs from 'fs';
6
+ import local from './local.js';
@@ -0,0 +1,61 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { commandNames, scriptsUse, findScriptReferences } from '../src/script-scanner.js';
7
+
8
+ function tempProject(installed = {}) {
9
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dd-scripts-'));
10
+ for (const [name, pkg] of Object.entries(installed)) {
11
+ const pkgDir = path.join(dir, 'node_modules', name);
12
+ fs.mkdirSync(pkgDir, { recursive: true });
13
+ fs.writeFileSync(path.join(pkgDir, 'package.json'), JSON.stringify({ name, ...pkg }));
14
+ }
15
+ return dir;
16
+ }
17
+
18
+ test('commandNames reads object and string bin fields from node_modules', () => {
19
+ const dir = tempProject({
20
+ typescript: { bin: { tsc: './bin/tsc', tsserver: './bin/tsserver' } },
21
+ '@scope/tool': { bin: './cli.js' },
22
+ });
23
+ assert.deepEqual(commandNames(dir, 'typescript').sort(), ['tsc', 'tsserver', 'typescript']);
24
+ assert.deepEqual(commandNames(dir, '@scope/tool').sort(), ['@scope/tool', 'tool']);
25
+ });
26
+
27
+ test('commandNames falls back to known commands when the package is not installed', () => {
28
+ const dir = tempProject();
29
+ assert.ok(commandNames(dir, 'typescript').includes('tsc'));
30
+ assert.ok(commandNames(dir, 'npm-run-all').includes('run-s'));
31
+ assert.deepEqual(commandNames(dir, 'left-pad'), ['left-pad']);
32
+ });
33
+
34
+ test('scriptsUse matches commands chained, prefixed, or via npx and .bin paths', () => {
35
+ const uses = (script, cmd) => scriptsUse([script], cmd);
36
+ assert.ok(uses('tsc -p .', 'tsc'));
37
+ assert.ok(uses('npm run clean&&tsc', 'tsc'));
38
+ assert.ok(uses('cross-env NODE_ENV=production tsc', 'tsc'));
39
+ assert.ok(uses('npx tsc --noEmit', 'tsc'));
40
+ assert.ok(uses('node_modules/.bin/tsc', 'tsc'));
41
+ assert.ok(uses('(tsc; echo done)', 'tsc'));
42
+ assert.ok(uses('lint-staged || exit 1', 'lint-staged'));
43
+ });
44
+
45
+ test('scriptsUse does not match other words containing the command', () => {
46
+ assert.ok(!scriptsUse(['tsc-watch src'], 'tsc'));
47
+ assert.ok(!scriptsUse(['echo mytsc'], 'tsc'));
48
+ assert.ok(!scriptsUse(['run-script build'], 'run-s'));
49
+ });
50
+
51
+ test('findScriptReferences returns packages whose commands appear in scripts', () => {
52
+ const dir = tempProject({
53
+ typescript: { bin: { tsc: './bin/tsc' } },
54
+ '@biomejs/biome': { bin: { biome: './bin/biome' } },
55
+ rimraf: { bin: { rimraf: './dist/bin.js' } },
56
+ lodash: {},
57
+ });
58
+ const scripts = { build: 'rimraf dist && tsc', lint: 'biome check .' };
59
+ const found = findScriptReferences(dir, ['typescript', '@biomejs/biome', 'rimraf', 'lodash'], scripts);
60
+ assert.deepEqual([...found].sort(), ['@biomejs/biome', 'rimraf', 'typescript']);
61
+ });
@@ -0,0 +1,55 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mapOsvVulns } from '../src/security-checker.js';
4
+
5
+ test('mapOsvVulns maps OSV entries to a short display shape', () => {
6
+ const vulns = [
7
+ {
8
+ id: 'GHSA-1',
9
+ summary: 'Prototype pollution',
10
+ details: 'A very long markdown write-up that should not be printed',
11
+ database_specific: { severity: 'HIGH' },
12
+ affected: [
13
+ {
14
+ package: { ecosystem: 'npm', name: 'lodash' },
15
+ ranges: [{ type: 'SEMVER', events: [{ introduced: '0' }, { fixed: '4.17.21' }] }],
16
+ },
17
+ ],
18
+ },
19
+ ];
20
+ assert.deepEqual(mapOsvVulns(vulns, 'lodash'), [
21
+ {
22
+ id: 'GHSA-1',
23
+ severity: 'HIGH',
24
+ title: 'Prototype pollution',
25
+ fixedIn: '4.17.21',
26
+ url: 'https://osv.dev/vulnerability/GHSA-1',
27
+ },
28
+ ]);
29
+ });
30
+
31
+ test('mapOsvVulns only reads fixed versions for the queried package', () => {
32
+ const [mapped] = mapOsvVulns(
33
+ [
34
+ {
35
+ id: 'GHSA-3',
36
+ affected: [
37
+ { package: { name: 'other' }, ranges: [{ events: [{ fixed: '9.9.9' }] }] },
38
+ ],
39
+ },
40
+ ],
41
+ 'lodash'
42
+ );
43
+ assert.equal(mapped.fixedIn, null);
44
+ });
45
+
46
+ test('mapOsvVulns falls back when fields are missing', () => {
47
+ const [mapped] = mapOsvVulns([{ id: 'GHSA-2' }], 'x');
48
+ assert.equal(mapped.severity, 'UNKNOWN');
49
+ assert.equal(mapped.title, 'GHSA-2');
50
+ assert.equal(mapped.fixedIn, null);
51
+ });
52
+
53
+ test('mapOsvVulns handles undefined input', () => {
54
+ assert.deepEqual(mapOsvVulns(), []);
55
+ });