mo3ta-coverage 1.0.11 → 1.0.12
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 +0 -7
- package/coverage/clover.xml +318 -127
- package/coverage/coverage-final.json +3 -2
- package/coverage/lcov-report/cli.js.html +178 -16
- package/coverage/lcov-report/fileUtils.js.html +423 -9
- package/coverage/lcov-report/gitUtils.js.html +1 -1
- package/coverage/lcov-report/importer.js.html +1051 -0
- package/coverage/lcov-report/index.html +43 -28
- package/coverage/lcov.info +609 -226
- package/index.js +24 -0
- package/package.json +3 -2
- package/src/cli.js +55 -5
- package/src/fileUtils.js +138 -0
- package/src/fileUtils.test.js +32 -1
- package/src/importer.js +323 -0
package/index.js
CHANGED
|
@@ -35,6 +35,7 @@ program
|
|
|
35
35
|
.option('--limit <percent>', 'Minimum required coverage percentage for all changed lines (e.g., 80)', '80')
|
|
36
36
|
.option('--showCovered <bool>', 'Show covered changed lines in the output', false)
|
|
37
37
|
.option('--mode <mode>', 'Execution mode: fast, smart, or full', 'smart')
|
|
38
|
+
.option('--maxDepth <number>', 'Maximum reverse dependency depth for smart mode', '3')
|
|
38
39
|
.enablePositionalOptions(); // used to allow using same options in subcommands
|
|
39
40
|
|
|
40
41
|
|
|
@@ -43,6 +44,7 @@ program
|
|
|
43
44
|
.description('Set or get configuration options')
|
|
44
45
|
.option('--base <branch>', 'Set default base branch')
|
|
45
46
|
.option('--mode <mode>', 'Set default mode (fast/smart/full)')
|
|
47
|
+
.option('--maxDepth <number>', 'Set default reverse dependency depth for smart mode')
|
|
46
48
|
.action((opts) => {
|
|
47
49
|
let config = readConfig();
|
|
48
50
|
|
|
@@ -66,6 +68,18 @@ program
|
|
|
66
68
|
updated = true;
|
|
67
69
|
console.log(`Default mode set to: ${config.mode}`);
|
|
68
70
|
}
|
|
71
|
+
|
|
72
|
+
if (opts.maxDepth !== undefined) {
|
|
73
|
+
const parsedMaxDepth = parseInt(opts.maxDepth, 10);
|
|
74
|
+
if (!Number.isInteger(parsedMaxDepth) || parsedMaxDepth < 0) {
|
|
75
|
+
console.error(`Invalid maxDepth: ${opts.maxDepth}. Expected a non-negative integer.`);
|
|
76
|
+
process.exit(1);
|
|
77
|
+
}
|
|
78
|
+
config.maxDepth = parsedMaxDepth;
|
|
79
|
+
updated = true;
|
|
80
|
+
console.log(`Default max depth set to: ${config.maxDepth}`);
|
|
81
|
+
}
|
|
82
|
+
|
|
69
83
|
if (updated) {
|
|
70
84
|
writeConfig(config);
|
|
71
85
|
} else {
|
|
@@ -91,12 +105,22 @@ program.action((opts) => {
|
|
|
91
105
|
options.mode = config.mode;
|
|
92
106
|
}
|
|
93
107
|
|
|
108
|
+
if ((options.maxDepth === undefined || options.maxDepth === '3') && config.maxDepth !== undefined) {
|
|
109
|
+
options.maxDepth = config.maxDepth;
|
|
110
|
+
}
|
|
111
|
+
|
|
94
112
|
options.mode = String(options.mode || 'smart').toLowerCase();
|
|
95
113
|
if (!['fast', 'smart', 'full'].includes(options.mode)) {
|
|
96
114
|
console.error(`Invalid mode: ${options.mode}. Expected one of: fast, smart, full.`);
|
|
97
115
|
process.exit(1);
|
|
98
116
|
}
|
|
99
117
|
|
|
118
|
+
options.maxDepth = parseInt(options.maxDepth ?? 3, 10);
|
|
119
|
+
if (!Number.isInteger(options.maxDepth) || options.maxDepth < 0) {
|
|
120
|
+
console.error(`Invalid maxDepth: ${options.maxDepth}. Expected a non-negative integer.`);
|
|
121
|
+
process.exit(1);
|
|
122
|
+
}
|
|
123
|
+
|
|
100
124
|
console.log(`Final options: ${JSON.stringify(options, null, 2)}`);
|
|
101
125
|
|
|
102
126
|
main(options);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mo3ta-coverage",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.12",
|
|
4
4
|
"description": "Run tests and report uncovered changed lines in a PR",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"bin": {
|
|
@@ -37,6 +37,7 @@
|
|
|
37
37
|
"jest": "^30.0.5"
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"commander": "^14.0.0"
|
|
40
|
+
"commander": "^14.0.0",
|
|
41
|
+
"typescript": "^5.8.3"
|
|
41
42
|
}
|
|
42
43
|
}
|
package/src/cli.js
CHANGED
|
@@ -4,6 +4,41 @@ import path from 'path';
|
|
|
4
4
|
import { exit } from 'process';
|
|
5
5
|
import { verifyBaseBranchExists, verifyGitRepoExists } from './gitUtils.js';
|
|
6
6
|
import { getJsOnlyFiles, separateSourceAndTestFiles, findTestFilesForSource } from './fileUtils.js';
|
|
7
|
+
import { findImportersForMany } from './importer.js';
|
|
8
|
+
|
|
9
|
+
function findReverseDepsForSourceFiles(sourceFiles, maxDepth) {
|
|
10
|
+
if (sourceFiles.length === 0) return [];
|
|
11
|
+
const importerResults = findImportersForMany(sourceFiles, maxDepth, {
|
|
12
|
+
projectDir: process.cwd()
|
|
13
|
+
});
|
|
14
|
+
const testFilesForReverseDeps = new Set();
|
|
15
|
+
const debugResults = [];
|
|
16
|
+
|
|
17
|
+
importerResults.forEach((result, targetFile) => {
|
|
18
|
+
const importers = result.importers.map(node => node.file);
|
|
19
|
+
|
|
20
|
+
debugResults.push({
|
|
21
|
+
targetFile,
|
|
22
|
+
importerCount: importers.length,
|
|
23
|
+
maxDepthReached: result.maxDepthReached,
|
|
24
|
+
importers: result.importers.map(node => ({
|
|
25
|
+
file: node.file,
|
|
26
|
+
depth: node.depth,
|
|
27
|
+
importedBy: node.importedBy
|
|
28
|
+
}))
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
importers.forEach(file => {
|
|
32
|
+
const tests = findTestFilesForSource(file);
|
|
33
|
+
tests.forEach(test => testFilesForReverseDeps.add(test));
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
reverseDepsTests: Array.from(testFilesForReverseDeps),
|
|
39
|
+
debugResults
|
|
40
|
+
};
|
|
41
|
+
}
|
|
7
42
|
|
|
8
43
|
export function main(options) {
|
|
9
44
|
try {
|
|
@@ -15,11 +50,12 @@ export function main(options) {
|
|
|
15
50
|
const COVERAGE_LIMIT = parseFloat(options.limit);
|
|
16
51
|
const SHOW_COVERED = options.showCovered === true || options.showCovered === 'true';
|
|
17
52
|
const MODE = options.mode;
|
|
53
|
+
const MAX_DEPTH = options.maxDepth;
|
|
18
54
|
|
|
19
|
-
console.log(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nMode: ${MODE}`);
|
|
55
|
+
console.log(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nMode: ${MODE} \nMax Depth: ${MAX_DEPTH}`);
|
|
20
56
|
|
|
21
57
|
const changedFiles = getChangedFiles(BASE_BRANCH);
|
|
22
|
-
runRelatedTests(changedFiles, MODE);
|
|
58
|
+
runRelatedTests(changedFiles, MODE, MAX_DEPTH);
|
|
23
59
|
reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED);
|
|
24
60
|
} catch (error) {
|
|
25
61
|
console.error('❌ An unexpected error occurred:', error.message || error);
|
|
@@ -50,7 +86,7 @@ function getChangedFiles(BASE_BRANCH) {
|
|
|
50
86
|
}
|
|
51
87
|
}
|
|
52
88
|
|
|
53
|
-
function runRelatedTests(files, mode) {
|
|
89
|
+
function runRelatedTests(files, mode, maxDepth) {
|
|
54
90
|
if (files.length === 0) {
|
|
55
91
|
console.log('✅ No changed source files found.');
|
|
56
92
|
exit(0);
|
|
@@ -119,11 +155,25 @@ function runRelatedTests(files, mode) {
|
|
|
119
155
|
exit(1);
|
|
120
156
|
}
|
|
121
157
|
} else if (mode === 'smart') {
|
|
122
|
-
console.log(`\n📝 Test strategy: smart (Combine source and mapped test files,
|
|
158
|
+
console.log(`\n📝 Test strategy: smart (Combine source and mapped test files, plus reverse deps up to depth ${maxDepth})`);
|
|
123
159
|
console.log(` Test files: ${finalTestFiles.length}`);
|
|
124
160
|
console.log(` Source files for coverage: ${sourceFiles.length}`);
|
|
125
|
-
const
|
|
161
|
+
const { reverseDepsTests, debugResults } = findReverseDepsForSourceFiles(sourceFiles, maxDepth);
|
|
162
|
+
const uniqueAllFiles = new Set([...sourceFiles, ...finalTestFiles, ...reverseDepsTests]);
|
|
163
|
+
const allFiles = Array.from(uniqueAllFiles);
|
|
126
164
|
console.log(` Total files passed to Jest: ${allFiles.length}`);
|
|
165
|
+
if (reverseDepsTests.length > 0) {
|
|
166
|
+
console.log(` Test files for files that import changes (reverse deps): ${reverseDepsTests.length}`);
|
|
167
|
+
}
|
|
168
|
+
if (debugResults.length > 0) {
|
|
169
|
+
console.log(' Reverse dependency debug:');
|
|
170
|
+
debugResults.forEach(({ targetFile, importerCount, maxDepthReached, importers }) => {
|
|
171
|
+
console.log(` - ${targetFile}: importers=${importerCount}, maxDepthReached=${maxDepthReached}`);
|
|
172
|
+
importers.forEach(({ file, depth, importedBy }) => {
|
|
173
|
+
console.log(` depth=${depth} file=${file}${importedBy ? ` importedBy=${importedBy}` : ''}`);
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
}
|
|
127
177
|
console.log(' Files passed to Jest:');
|
|
128
178
|
allFiles.forEach(file => console.log(` - ${file}`));
|
|
129
179
|
const command = `npx jest --passWithNoTests --coverage ${allFiles.join(' ')}`;
|
package/src/fileUtils.js
CHANGED
|
@@ -90,3 +90,141 @@ export function findTestFilesForSource(sourceFile) {
|
|
|
90
90
|
// Check which test files actually exist
|
|
91
91
|
return testFiles.filter(testFile => fs.existsSync(testFile));
|
|
92
92
|
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Extracts import paths from a file (ESM and CommonJS)
|
|
96
|
+
* @param {string} filePath - Path to source file
|
|
97
|
+
* @returns {string[]} - Array of imported file paths
|
|
98
|
+
*/
|
|
99
|
+
export function extractImports(filePath) {
|
|
100
|
+
try {
|
|
101
|
+
const content = fs.readFileSync(filePath, 'utf8');
|
|
102
|
+
const imports = new Set();
|
|
103
|
+
|
|
104
|
+
// ESM imports: import x from 'path'
|
|
105
|
+
const esmRegex = /import\s+(?:.*?)\s+from\s+['"`]([^'"`]+)['"`]/g;
|
|
106
|
+
let match;
|
|
107
|
+
while ((match = esmRegex.exec(content)) !== null) {
|
|
108
|
+
imports.add(match[1]);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ESM side-effect imports: import 'path'
|
|
112
|
+
const sideEffectImportRegex = /import\s+['"`]([^'"`]+)['"`]/g;
|
|
113
|
+
while ((match = sideEffectImportRegex.exec(content)) !== null) {
|
|
114
|
+
imports.add(match[1]);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// CommonJS requires: require('path')
|
|
118
|
+
const cjsRegex = /require\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g;
|
|
119
|
+
while ((match = cjsRegex.exec(content)) !== null) {
|
|
120
|
+
imports.add(match[1]);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return Array.from(imports);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
return [];
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Resolves relative imports to absolute file paths
|
|
131
|
+
* @param {string} importPath - Import path (relative or module name)
|
|
132
|
+
* @param {string} fromFile - File doing the importing
|
|
133
|
+
* @returns {string|null} - Resolved file path or null if not found
|
|
134
|
+
*/
|
|
135
|
+
export function resolveImportPath(importPath, fromFile) {
|
|
136
|
+
// Skip node_modules and external packages
|
|
137
|
+
if (importPath.startsWith('.') === false) {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const fromDir = path.dirname(fromFile);
|
|
142
|
+
let resolvedPath = path.resolve(fromDir, importPath);
|
|
143
|
+
|
|
144
|
+
// Try with file extensions if no extension provided
|
|
145
|
+
const extensions = ['.js', '.ts', '.jsx', '.tsx', '/index.js', '/index.ts'];
|
|
146
|
+
for (const ext of extensions) {
|
|
147
|
+
const candidate = resolvedPath + ext;
|
|
148
|
+
if (fs.existsSync(candidate)) {
|
|
149
|
+
return candidate;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Also try without adding extension
|
|
154
|
+
if (fs.existsSync(resolvedPath)) {
|
|
155
|
+
return resolvedPath;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Finds all files that import the given files (reverse dependencies)
|
|
163
|
+
* up to a specified depth
|
|
164
|
+
* @param {string[]} changedFiles - Changed files to find reverse deps for
|
|
165
|
+
* @param {number} maxDepth - Maximum depth to traverse (default 3)
|
|
166
|
+
* @returns {string[]} - Array of files that import changed files
|
|
167
|
+
*/
|
|
168
|
+
export function findReverseDeps(changedFiles, maxDepth = 3) {
|
|
169
|
+
const reverseDeps = new Set();
|
|
170
|
+
const visited = new Set();
|
|
171
|
+
|
|
172
|
+
// Get all source files to check
|
|
173
|
+
let allSourceFiles = [];
|
|
174
|
+
try {
|
|
175
|
+
const srcDir = 'src';
|
|
176
|
+
if (fs.existsSync(srcDir)) {
|
|
177
|
+
const walk = (dir) => {
|
|
178
|
+
const files = fs.readdirSync(dir);
|
|
179
|
+
files.forEach(file => {
|
|
180
|
+
const fullPath = path.join(dir, file);
|
|
181
|
+
const stat = fs.statSync(fullPath);
|
|
182
|
+
|
|
183
|
+
if (stat.isDirectory() && !file.startsWith('.') && file !== 'node_modules') {
|
|
184
|
+
walk(fullPath);
|
|
185
|
+
} else if (file.match(/\.(js|ts|jsx|tsx)$/) && !file.match(/(\.test|\.spec)\./)) {
|
|
186
|
+
allSourceFiles.push(fullPath);
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
};
|
|
190
|
+
walk(srcDir);
|
|
191
|
+
}
|
|
192
|
+
} catch (error) {
|
|
193
|
+
return [];
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// BFS to find reverse deps up to maxDepth
|
|
197
|
+
let currentLevel = new Set(changedFiles.map(f => path.resolve(f)));
|
|
198
|
+
let depth = 0;
|
|
199
|
+
|
|
200
|
+
while (depth < maxDepth && currentLevel.size > 0) {
|
|
201
|
+
const nextLevel = new Set();
|
|
202
|
+
|
|
203
|
+
allSourceFiles.forEach(sourceFile => {
|
|
204
|
+
const absoluteSourceFile = path.resolve(sourceFile);
|
|
205
|
+
|
|
206
|
+
if (visited.has(absoluteSourceFile)) return;
|
|
207
|
+
|
|
208
|
+
const imports = extractImports(sourceFile);
|
|
209
|
+
let importsCurrentLevel = false;
|
|
210
|
+
|
|
211
|
+
imports.forEach(imp => {
|
|
212
|
+
const resolved = resolveImportPath(imp, sourceFile);
|
|
213
|
+
if (resolved && currentLevel.has(path.resolve(resolved))) {
|
|
214
|
+
importsCurrentLevel = true;
|
|
215
|
+
}
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
if (importsCurrentLevel) {
|
|
219
|
+
nextLevel.add(absoluteSourceFile);
|
|
220
|
+
reverseDeps.add(absoluteSourceFile);
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
currentLevel.forEach(f => visited.add(f));
|
|
225
|
+
currentLevel = nextLevel;
|
|
226
|
+
depth++;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
return Array.from(reverseDeps);
|
|
230
|
+
}
|
package/src/fileUtils.test.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import { getJsOnlyFiles, separateSourceAndTestFiles, findTestFilesForSource } from './fileUtils';
|
|
1
|
+
import { getJsOnlyFiles, separateSourceAndTestFiles, findReverseDeps, findTestFilesForSource } from './fileUtils';
|
|
2
2
|
import fs from 'fs';
|
|
3
|
+
import os from 'os';
|
|
4
|
+
import path from 'path';
|
|
3
5
|
|
|
4
6
|
describe('getJsOnlyFiles', () => {
|
|
5
7
|
const files = [
|
|
@@ -231,4 +233,33 @@ describe('findTestFilesForSource', () => {
|
|
|
231
233
|
|
|
232
234
|
expect(result).toContain('src/components/Button.test.jsx');
|
|
233
235
|
});
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
describe('findReverseDeps', () => {
|
|
239
|
+
const originalCwd = process.cwd();
|
|
240
|
+
|
|
241
|
+
beforeEach(() => {
|
|
242
|
+
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mo3ta-reverse-deps-'));
|
|
243
|
+
process.chdir(tempDir);
|
|
244
|
+
fs.mkdirSync('src', { recursive: true });
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
afterEach(() => {
|
|
248
|
+
process.chdir(originalCwd);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it('limits traversal to the configured depth', () => {
|
|
252
|
+
fs.writeFileSync('src/leaf.js', 'export const leaf = 1;\n');
|
|
253
|
+
fs.writeFileSync('src/mid.js', "import './leaf.js';\nexport const mid = 1;\n");
|
|
254
|
+
fs.writeFileSync('src/top.js', "import './mid.js';\nexport const top = 1;\n");
|
|
255
|
+
|
|
256
|
+
const depthOne = findReverseDeps(['src/leaf.js'], 1);
|
|
257
|
+
const depthTwo = findReverseDeps(['src/leaf.js'], 2);
|
|
258
|
+
|
|
259
|
+
expect(depthOne).toEqual([path.resolve('src/mid.js')]);
|
|
260
|
+
expect(depthTwo).toEqual([
|
|
261
|
+
path.resolve('src/mid.js'),
|
|
262
|
+
path.resolve('src/top.js')
|
|
263
|
+
]);
|
|
264
|
+
});
|
|
234
265
|
});
|
package/src/importer.js
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import ts from 'typescript';
|
|
4
|
+
|
|
5
|
+
// =============================================================================
|
|
6
|
+
// AST -> import specifiers
|
|
7
|
+
// =============================================================================
|
|
8
|
+
|
|
9
|
+
function inferScriptKind(filePath) {
|
|
10
|
+
if (filePath.endsWith('.tsx')) return ts.ScriptKind.TSX;
|
|
11
|
+
if (filePath.endsWith('.jsx')) return ts.ScriptKind.JSX;
|
|
12
|
+
if (
|
|
13
|
+
filePath.endsWith('.js') ||
|
|
14
|
+
filePath.endsWith('.mjs') ||
|
|
15
|
+
filePath.endsWith('.cjs')
|
|
16
|
+
) {
|
|
17
|
+
return ts.ScriptKind.JS;
|
|
18
|
+
}
|
|
19
|
+
return ts.ScriptKind.TS;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function getImportSpecifiers(filePath, opts) {
|
|
23
|
+
let sourceCode;
|
|
24
|
+
try {
|
|
25
|
+
sourceCode = fs.readFileSync(filePath, 'utf-8');
|
|
26
|
+
} catch {
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const sourceFile = ts.createSourceFile(
|
|
31
|
+
filePath,
|
|
32
|
+
sourceCode,
|
|
33
|
+
ts.ScriptTarget.Latest,
|
|
34
|
+
/* setParentNodes */ true,
|
|
35
|
+
inferScriptKind(filePath)
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
const specifiers = [];
|
|
39
|
+
|
|
40
|
+
function visit(node) {
|
|
41
|
+
// import ... from '...'
|
|
42
|
+
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
|
|
43
|
+
specifiers.push(node.moduleSpecifier.text);
|
|
44
|
+
}
|
|
45
|
+
// export ... from '...'
|
|
46
|
+
else if (
|
|
47
|
+
opts.includeReExports &&
|
|
48
|
+
ts.isExportDeclaration(node) &&
|
|
49
|
+
node.moduleSpecifier &&
|
|
50
|
+
ts.isStringLiteral(node.moduleSpecifier)
|
|
51
|
+
) {
|
|
52
|
+
specifiers.push(node.moduleSpecifier.text);
|
|
53
|
+
}
|
|
54
|
+
// import('...') dynamic
|
|
55
|
+
else if (
|
|
56
|
+
opts.includeDynamicImports &&
|
|
57
|
+
ts.isCallExpression(node) &&
|
|
58
|
+
node.expression.kind === ts.SyntaxKind.ImportKeyword &&
|
|
59
|
+
node.arguments[0] &&
|
|
60
|
+
ts.isStringLiteral(node.arguments[0])
|
|
61
|
+
) {
|
|
62
|
+
specifiers.push(node.arguments[0].text);
|
|
63
|
+
}
|
|
64
|
+
// require('...')
|
|
65
|
+
else if (
|
|
66
|
+
opts.includeDynamicImports &&
|
|
67
|
+
ts.isCallExpression(node) &&
|
|
68
|
+
ts.isIdentifier(node.expression) &&
|
|
69
|
+
node.expression.text === 'require' &&
|
|
70
|
+
node.arguments.length === 1 &&
|
|
71
|
+
ts.isStringLiteral(node.arguments[0])
|
|
72
|
+
) {
|
|
73
|
+
specifiers.push(node.arguments[0].text);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
ts.forEachChild(node, visit);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
visit(sourceFile);
|
|
80
|
+
return specifiers;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// =============================================================================
|
|
84
|
+
// tsconfig + module resolution
|
|
85
|
+
// =============================================================================
|
|
86
|
+
|
|
87
|
+
function loadCompilerOptions(projectDir, tsconfigPath) {
|
|
88
|
+
const configPath =
|
|
89
|
+
tsconfigPath ||
|
|
90
|
+
ts.findConfigFile(projectDir, ts.sys.fileExists, 'tsconfig.json');
|
|
91
|
+
|
|
92
|
+
if (!configPath) {
|
|
93
|
+
return {
|
|
94
|
+
options: { allowJs: true, esModuleInterop: true },
|
|
95
|
+
configDir: path.resolve(projectDir),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
|
|
100
|
+
if (configFile.error) {
|
|
101
|
+
throw new Error(
|
|
102
|
+
`Failed to read tsconfig: ${ts.flattenDiagnosticMessageText(
|
|
103
|
+
configFile.error.messageText,
|
|
104
|
+
'\n'
|
|
105
|
+
)}`
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const configDir = path.dirname(path.resolve(configPath));
|
|
110
|
+
const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, configDir);
|
|
111
|
+
|
|
112
|
+
return {
|
|
113
|
+
options: Object.assign({ allowJs: true }, parsed.options),
|
|
114
|
+
configDir,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function resolveImport(specifier, containingFile, options, host, cache) {
|
|
119
|
+
const result = ts.resolveModuleName(
|
|
120
|
+
specifier,
|
|
121
|
+
containingFile,
|
|
122
|
+
options,
|
|
123
|
+
host,
|
|
124
|
+
cache
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
const resolved = result.resolvedModule;
|
|
128
|
+
if (!resolved) return null;
|
|
129
|
+
if (resolved.isExternalLibraryImport) return null; // skip node_modules
|
|
130
|
+
if (resolved.extension === ts.Extension.Dts) return null; // skip .d.ts
|
|
131
|
+
return path.resolve(resolved.resolvedFileName);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// =============================================================================
|
|
135
|
+
// File walking
|
|
136
|
+
// =============================================================================
|
|
137
|
+
|
|
138
|
+
const DEFAULT_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'];
|
|
139
|
+
const DEFAULT_IGNORE = ['node_modules', '.git', 'dist', 'build', 'coverage'];
|
|
140
|
+
|
|
141
|
+
function findSourceFiles(rootDir, extensions, ignore) {
|
|
142
|
+
const out = [];
|
|
143
|
+
const absRoot = path.resolve(rootDir);
|
|
144
|
+
|
|
145
|
+
function walk(dir) {
|
|
146
|
+
let entries;
|
|
147
|
+
try {
|
|
148
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
149
|
+
} catch {
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
for (const entry of entries) {
|
|
154
|
+
const full = path.join(dir, entry.name);
|
|
155
|
+
|
|
156
|
+
if (ignore.some((pat) => full.includes(pat))) continue;
|
|
157
|
+
|
|
158
|
+
if (entry.isDirectory()) {
|
|
159
|
+
if (entry.name.startsWith('.')) continue;
|
|
160
|
+
walk(full);
|
|
161
|
+
} else if (entry.isFile()) {
|
|
162
|
+
if (entry.name.endsWith('.d.ts')) continue;
|
|
163
|
+
if (extensions.some((ext) => entry.name.endsWith(ext))) {
|
|
164
|
+
out.push(full);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
walk(absRoot);
|
|
171
|
+
return out;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// =============================================================================
|
|
175
|
+
// Build the reverse-dependency graph
|
|
176
|
+
// =============================================================================
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* @typedef {Object} ImporterGraphOptions
|
|
180
|
+
* @property {string} projectDir
|
|
181
|
+
* @property {string} [tsconfigPath]
|
|
182
|
+
* @property {string[]} [extensions]
|
|
183
|
+
* @property {string[]} [ignore]
|
|
184
|
+
* @property {boolean} [includeReExports]
|
|
185
|
+
* @property {boolean} [includeDynamicImports]
|
|
186
|
+
*/
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* @typedef {Object} ReverseGraph
|
|
190
|
+
* @property {Map<string, Set<string>>} edges file -> direct importers
|
|
191
|
+
* @property {string[]} allFiles
|
|
192
|
+
*/
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* @param {ImporterGraphOptions} opts
|
|
196
|
+
* @returns {ReverseGraph}
|
|
197
|
+
*/
|
|
198
|
+
export function buildReverseGraph(opts) {
|
|
199
|
+
const {
|
|
200
|
+
projectDir,
|
|
201
|
+
tsconfigPath,
|
|
202
|
+
extensions = DEFAULT_EXTENSIONS,
|
|
203
|
+
ignore = DEFAULT_IGNORE,
|
|
204
|
+
includeReExports = true,
|
|
205
|
+
includeDynamicImports = true,
|
|
206
|
+
} = opts;
|
|
207
|
+
|
|
208
|
+
const { options, configDir } = loadCompilerOptions(projectDir, tsconfigPath);
|
|
209
|
+
const host = ts.createCompilerHost(options, /* setParentNodes */ true);
|
|
210
|
+
const cache = ts.createModuleResolutionCache(configDir, (s) => s, options);
|
|
211
|
+
|
|
212
|
+
const allFiles = findSourceFiles(projectDir, extensions, ignore);
|
|
213
|
+
const edges = new Map();
|
|
214
|
+
|
|
215
|
+
const specOpts = { includeReExports, includeDynamicImports };
|
|
216
|
+
|
|
217
|
+
for (const file of allFiles) {
|
|
218
|
+
const specifiers = getImportSpecifiers(file, specOpts);
|
|
219
|
+
for (const spec of specifiers) {
|
|
220
|
+
const resolved = resolveImport(spec, file, options, host, cache);
|
|
221
|
+
if (!resolved) continue;
|
|
222
|
+
let importers = edges.get(resolved);
|
|
223
|
+
if (!importers) {
|
|
224
|
+
importers = new Set();
|
|
225
|
+
edges.set(resolved, importers);
|
|
226
|
+
}
|
|
227
|
+
importers.add(file);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
return { edges, allFiles };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// =============================================================================
|
|
235
|
+
// Main API: find importers up to a max depth (BFS)
|
|
236
|
+
// =============================================================================
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* @typedef {Object} ImporterNode
|
|
240
|
+
* @property {string} file
|
|
241
|
+
* @property {number} depth
|
|
242
|
+
* @property {string} [importedBy]
|
|
243
|
+
*/
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* @typedef {Object} FindImportersResult
|
|
247
|
+
* @property {string} target
|
|
248
|
+
* @property {ImporterNode[]} importers
|
|
249
|
+
* @property {number} maxDepthReached
|
|
250
|
+
*/
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* @param {string} targetFile
|
|
254
|
+
* @param {number} maxDepth
|
|
255
|
+
* @param {ReverseGraph} graph
|
|
256
|
+
* @returns {FindImportersResult}
|
|
257
|
+
*/
|
|
258
|
+
export function findImportersWithDepth(targetFile, maxDepth, graph) {
|
|
259
|
+
if (maxDepth < 1) {
|
|
260
|
+
throw new Error(`maxDepth must be >= 1, got ${maxDepth}`);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const target = path.resolve(targetFile);
|
|
264
|
+
const visited = new Map(); // file -> ImporterNode
|
|
265
|
+
const queue = [{ file: target, depth: 0, importedBy: undefined }];
|
|
266
|
+
let maxDepthReached = 0;
|
|
267
|
+
|
|
268
|
+
while (queue.length > 0) {
|
|
269
|
+
const { file, depth, importedBy } = queue.shift();
|
|
270
|
+
|
|
271
|
+
if (visited.has(file)) continue;
|
|
272
|
+
|
|
273
|
+
if (file !== target) {
|
|
274
|
+
visited.set(file, { file, depth, importedBy });
|
|
275
|
+
if (depth > maxDepthReached) maxDepthReached = depth;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
if (depth >= maxDepth) continue;
|
|
279
|
+
|
|
280
|
+
const directImporters = graph.edges.get(file);
|
|
281
|
+
if (!directImporters) continue;
|
|
282
|
+
|
|
283
|
+
for (const importer of directImporters) {
|
|
284
|
+
if (!visited.has(importer) && importer !== target) {
|
|
285
|
+
queue.push({ file: importer, depth: depth + 1, importedBy: file });
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const importers = Array.from(visited.values()).sort(
|
|
291
|
+
(a, b) => a.depth - b.depth || a.file.localeCompare(b.file)
|
|
292
|
+
);
|
|
293
|
+
|
|
294
|
+
return { target, importers, maxDepthReached };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Convenience: build graph + query in one call.
|
|
299
|
+
* @param {string} targetFile
|
|
300
|
+
* @param {number} maxDepth
|
|
301
|
+
* @param {ImporterGraphOptions} opts
|
|
302
|
+
* @returns {FindImportersResult}
|
|
303
|
+
*/
|
|
304
|
+
export function findImporters(targetFile, maxDepth, opts) {
|
|
305
|
+
const graph = buildReverseGraph(opts);
|
|
306
|
+
return findImportersWithDepth(targetFile, maxDepth, graph);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Convenience: query many targets against the same graph.
|
|
311
|
+
* @param {string[]} targets
|
|
312
|
+
* @param {number} maxDepth
|
|
313
|
+
* @param {ImporterGraphOptions} opts
|
|
314
|
+
* @returns {Map<string, FindImportersResult>}
|
|
315
|
+
*/
|
|
316
|
+
export function findImportersForMany(targets, maxDepth, opts) {
|
|
317
|
+
const graph = buildReverseGraph(opts);
|
|
318
|
+
const results = new Map();
|
|
319
|
+
for (const t of targets) {
|
|
320
|
+
results.set(path.resolve(t), findImportersWithDepth(t, maxDepth, graph));
|
|
321
|
+
}
|
|
322
|
+
return results;
|
|
323
|
+
}
|