check-local-ui-runtime-deps.mjs
2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { readdir, readFile } from 'node:fs/promises';
import { extname, relative, resolve } from 'node:path';
import ts from 'typescript';
const sourceRoot = resolve('src');
const supportedExtensions = new Set(['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx']);
const enforce = process.argv.includes('--enforce');
async function collectSourceFiles(directory) {
const entries = await readdir(directory, { withFileTypes: true });
const files = await Promise.all(entries.map(async (entry) => {
const path = resolve(directory, entry.name);
if (entry.isDirectory()) return collectSourceFiles(path);
if (!supportedExtensions.has(extname(entry.name)) || /\.test\.[^.]+$/.test(entry.name)) return [];
return [path];
}));
return files.flat();
}
const files = await collectSourceFiles(sourceRoot);
const matches = [];
for (const file of files) {
const source = await readFile(file, 'utf8');
const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
const addMatch = (moduleSpecifier) => {
if (!ts.isStringLiteralLike(moduleSpecifier) || !moduleSpecifier.text.includes('packages/ui')) return;
const { line } = sourceFile.getLineAndCharacterOfPosition(moduleSpecifier.getStart(sourceFile));
matches.push({
file: relative(process.cwd(), file),
line: line + 1,
specifier: moduleSpecifier.text,
});
};
const visit = (node) => {
if (ts.isImportDeclaration(node)) {
const importClause = node.importClause;
const namedBindings = importClause?.namedBindings;
const hasOnlyTypeSpecifiers = namedBindings
&& ts.isNamedImports(namedBindings)
&& namedBindings.elements.length > 0
&& namedBindings.elements.every((specifier) => specifier.isTypeOnly);
if (!importClause?.isTypeOnly && !hasOnlyTypeSpecifiers) addMatch(node.moduleSpecifier);
} else if (ts.isExportDeclaration(node) && !node.isTypeOnly && node.moduleSpecifier) {
addMatch(node.moduleSpecifier);
} else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
addMatch(node.arguments[0]);
}
ts.forEachChild(node, visit);
};
visit(sourceFile);
}
console.log(`本地 packages/ui 运行时 import:${matches.length} 条,涉及 ${new Set(matches.map((match) => match.file)).size} 个文件。`);
for (const match of matches) {
console.log(`${match.file}:${match.line} -> ${match.specifier}`);
}
if (enforce && matches.length > 0) {
console.error('检测失败:web/src 仍存在指向 packages/ui 的运行时 import。');
process.exitCode = 1;
}