- 任何含 export…from 的模块按桶处理(不只 index.ts;constants.ts 是具名再导出门面) - 桶的再导出边不再无条件传播;按名 import 才解析到落点,export * / namespace / 副作用导入保守判活 - 解析前剥离注释(字符串感知),避免注释里的示例导入骗过 export…from 正则 - 新增 dead-modules.selftest.mjs(6 情景),check:dead 改为「自证 + 报告」 - 真树浮出 5 个 barrel-only 模块,登记 OPEN-18,未擅删
358 lines
16 KiB
JavaScript
358 lines
16 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* 站内模块可达性判定:从真实入口(app/**\/page.tsx、layout、api route)做 import 闭包,
|
||
* 报出「没有任何入口能到达」的模块。
|
||
*
|
||
* 为什么要这么判,而不是 grep 文件名:
|
||
* 1. 相对导入 `from './micro-interactions'` 用全路径正则扫不出来 —— 第一版就因此把
|
||
* detail-hero.tsx 正在用的组件误判成死码。**判死码判错 = 误删活代码。**
|
||
* 2. 桶文件(detail/index.ts 再导出)会让"谁引用了它"的答案变成"引用了桶",
|
||
* 必须顺着一个真实 specifier 解析到落点文件再判。
|
||
* 3. 只看"有没有 import 方"也不够:A 引 B、B 引 C,但 A 自己没人引 —— 整条链都是死的。
|
||
* 可达性闭包才回答"这文件有没有可能进产物"。
|
||
*
|
||
* 输出退出码:0 有死码 / 2 判定不可信(入口为 0、解析报错)。**不判 1**:
|
||
* 死码存在不是构建失败,而是台账 DEC-P-2 的存量,判红会让这道检查永远进不了 CI。
|
||
*/
|
||
import { readFileSync, readdirSync, existsSync, statSync } from 'node:fs';
|
||
import path from 'node:path';
|
||
|
||
// 扫描根可以有多个:只扫 src 会漏掉**门禁脚本与 e2e 对 src 的引用**
|
||
// (scripts/utils/check-color-contrast.ts 就 import 了 src/lib/color-contrast.ts,
|
||
// 只扫 src 时它被误判成死码)。入口仍只取 app/ 约定文件,其余根只贡献"谁在引"。
|
||
// `prisma/` 必须在内:`prisma/seed.ts` 是 `src/lib/seed-target.ts` 的**唯一**消费方
|
||
// (2026-11-25 实测误报:漏掉这个根后 seed-target.ts 被判「仅测试/死链引用」,
|
||
// 而它正是 seed 沙盒保护闸的实体 —— 按那个结论删掉,写错库的保护就没有了)。
|
||
const ROOTS = process.argv.length > 2 ? process.argv.slice(2) : ['src', 'scripts', 'e2e', 'config', 'prisma'];
|
||
const ROOT = 'src';
|
||
const missing = ROOTS.filter((r) => !existsSync(r));
|
||
if (missing.length) { console.error(`未能度量:根目录不存在 ${missing.join(', ')}`); process.exit(2); }
|
||
|
||
function walk(dir, acc = []) {
|
||
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
||
if (['node_modules', '.git', 'dist', '_archive', '.next'].includes(e.name)) continue;
|
||
const p = path.join(dir, e.name);
|
||
if (e.isDirectory()) walk(p, acc);
|
||
else if (/\.(tsx?|mjs)$/.test(e.name)) acc.push(p);
|
||
}
|
||
return acc;
|
||
}
|
||
|
||
const files = ROOTS.flatMap((r) => walk(r));
|
||
const texts = new Map(files.map((f) => [path.normalize(f), readFileSync(f, 'utf8')]));
|
||
const EXT = ['', '.ts', '.tsx', '.js', '.mjs', '/index.ts', '/index.tsx'];
|
||
|
||
/**
|
||
* 注释剥离(字符串感知)。不剥离会把注释里的示例代码当成真语句:
|
||
* `src/lib/constants.ts` 的注释里写着 `` `import { getHeroTheme } from '@/lib/constants'` ``,
|
||
* 其中 `}` 会让 `export { … } from` 的正则提前收口,真正的 `from './constants/index'`
|
||
* 因此漏匹配、门面被误判成无再导出 —— 判死码的判据自己被一段注释骗了。
|
||
*/
|
||
function stripComments(src) {
|
||
let out = '';
|
||
let i = 0;
|
||
let mode = null; // "'" | '"' | '`' | '//' | '/*'
|
||
while (i < src.length) {
|
||
const c = src[i];
|
||
const n = src[i + 1];
|
||
if (mode === null) {
|
||
if (c === '/' && n === '/') { mode = '//'; i += 2; continue; }
|
||
if (c === '/' && n === '*') { mode = '/*'; i += 2; continue; }
|
||
if (c === "'" || c === '"' || c === '`') { mode = c; out += c; i += 1; continue; }
|
||
out += c; i += 1; continue;
|
||
}
|
||
if (mode === '//') { if (c === '\n') { mode = null; out += c; } i += 1; continue; }
|
||
if (mode === '/*') {
|
||
if (c === '*' && n === '/') { mode = null; i += 2; continue; }
|
||
if (c === '\n') out += c;
|
||
i += 1; continue;
|
||
}
|
||
out += c;
|
||
if (c === '\\') { if (i + 1 < src.length) { out += src[i + 1]; i += 2; continue; } }
|
||
if (c === mode) mode = null;
|
||
i += 1;
|
||
}
|
||
return out;
|
||
}
|
||
|
||
const scan = new Map([...texts].map(([f, txt]) => [f, stripComments(txt)]));
|
||
|
||
/** specifier → 站内落点文件(解析不到=第三方包或资源文件,返回 null) */
|
||
function resolve(spec, fromFile) {
|
||
let base;
|
||
if (spec.startsWith('@/')) base = path.join(ROOT, spec.slice(2));
|
||
// ⚠ 必须用 path.join 而不是 path.resolve:resolve 会拼上 cwd 变成**绝对路径**,
|
||
// 而模块表 texts 的 key 是 walk 出来的相对路径 ⇒ 所有 `./x` 相对导入都匹配不上、
|
||
// 边被静默丢弃(`@/` 开头的反而正常,于是可达数看着像个数、其实是半瞎的)。
|
||
// 本仓页面组件多用相对导入,第一版因此把 home-content-v16 报成死码。
|
||
else if (spec.startsWith('./') || spec.startsWith('../')) base = path.normalize(path.join(path.dirname(fromFile), spec));
|
||
else return null;
|
||
for (const e of EXT) {
|
||
const cand = path.normalize(base + e);
|
||
if (existsSync(cand) && statSync(cand).isFile()) return cand;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* 静态 from、再导出 from、**动态 import()**、require() 都要算边。
|
||
* 第一版只匹配 `from '...'`,于是 GoogleAnalyticsWrapper 里的
|
||
* const GoogleAnalytics = dynamic(() => import('./GoogleAnalytics'))
|
||
* 这条边不存在 ⇒ GA 组件被报成"零引用死码"。按那结果删掉它,
|
||
* GA4 会在没有单测、没有 e2e 断言渲染的情况下从页面上消失。
|
||
* 动态导入的 specifier 是字符串字面量,这里一并抓(模式串无法静态解析,按字面量解析)。
|
||
*/
|
||
const IMPORT_RE = /(?:from|import|require)\s*\(?\s*['"]([^'"]+)['"]/g;
|
||
const IMPORT_STMT_RE = /\bimport\s+(?:type\s+)?(\{[^}]*\}|\*\s+as\s+\w+|\w+)\s*from\s*['"]([^'"]+)['"]/g;
|
||
const REEXPORT_RE = /\bexport\s+(?:type\s+)?(\{[^}]*\}|\*\s+as\s+\w+|\*)\s*from\s*['"]([^'"]+)['"]/g;
|
||
const SIDE_IMPORT_RE = /\bimport\s+['"]([^'"]+)['"]|\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)|\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
|
||
|
||
const isBarrel = (f) => /(^|\/)index\.ts$/.test(f);
|
||
|
||
/**
|
||
* 「桶」不等于文件名 index.ts:`src/lib/constants.ts` 就是一份具名再导出门面
|
||
* (`export { PRODUCTS } from './constants/index'`)。只认 index.ts 会让门面
|
||
* 被当成普通模块 ⇒ 它的再导出边无条件传播,symbol 级判据又退回瞎的。
|
||
* 判据改为「该文件含 export … from 语句」,并在符号解析时沿桶链递归。
|
||
*/
|
||
const hubFiles = new Set();
|
||
for (const [f, txt] of scan) {
|
||
if (isBarrel(f) || [...txt.matchAll(REEXPORT_RE)].length > 0) hubFiles.add(f);
|
||
}
|
||
const isHub = (f) => hubFiles.has(f);
|
||
|
||
/**
|
||
* 桶的再导出表。符号级可达性的前提:
|
||
* `export { X } from './x'` 只是**通道**,不等于有人用了 X。
|
||
* 只有某个可达模块真的按名 import 了 X,落点文件 ./x 才算活。
|
||
* `export *` 无法静态枚举符号,按保守方向算活(宁可漏判死码,不可误删活码)。
|
||
* 这条判据对应 OPEN-16:barrel 再导出曾让 `detail/` 下 3 个零渲染点组件
|
||
* 被算作"有引用",删掉实例之后判据仍然是瞎的。
|
||
*/
|
||
const barrelExports = new Map(); // barrel -> Map<对外符号, Set<落点文件>>
|
||
const barrelStars = new Map(); // barrel -> Set<star 落点>
|
||
for (const f of texts.keys()) {
|
||
if (!isHub(f)) continue;
|
||
const table = new Map();
|
||
const stars = new Set();
|
||
for (const m of scan.get(f).matchAll(REEXPORT_RE)) {
|
||
const target = resolve(m[2], f);
|
||
if (!target || !texts.has(target)) continue;
|
||
const clause = m[1].trim();
|
||
if (clause.startsWith('{')) {
|
||
for (const piece of clause.slice(1, -1).split(',')) {
|
||
const p = piece.trim();
|
||
if (!p) continue;
|
||
// `export { A as B }` 对外提供的是 B
|
||
const exported = p.split(/\s+as\s+/).pop().trim();
|
||
if (!exported) continue;
|
||
if (!table.has(exported)) table.set(exported, new Set());
|
||
table.get(exported).add(target);
|
||
}
|
||
} else {
|
||
stars.add(target);
|
||
}
|
||
}
|
||
barrelExports.set(f, table);
|
||
barrelStars.set(f, stars);
|
||
}
|
||
|
||
/** 在桶里查一个符号的真实落点;`export *` 链递归展开。查不到=符号可能定义在桶自身。 */
|
||
function resolveBarrelSymbol(barrelFile, name, seen = new Set()) {
|
||
const out = new Set();
|
||
if (seen.has(barrelFile)) return out;
|
||
seen.add(barrelFile);
|
||
const direct = barrelExports.get(barrelFile)?.get(name);
|
||
if (direct) {
|
||
for (const src of direct) {
|
||
out.add(src);
|
||
// 门面 → 子桶是常见形状(constants.ts → constants/index.ts):继续往里找落点
|
||
if (isHub(src)) for (const x of resolveBarrelSymbol(src, name, seen)) out.add(x);
|
||
}
|
||
return out;
|
||
}
|
||
for (const src of barrelStars.get(barrelFile) || []) {
|
||
if (isHub(src)) {
|
||
out.add(src); // 桶 → 桶仍是真实的模块依赖
|
||
for (const x of resolveBarrelSymbol(src, name, seen)) out.add(x);
|
||
} else {
|
||
out.add(src);
|
||
}
|
||
}
|
||
return out;
|
||
}
|
||
|
||
const expandBarrel = (set, barrelFile, seen = new Set()) => {
|
||
if (seen.has(barrelFile)) return;
|
||
seen.add(barrelFile);
|
||
for (const srcs of barrelExports.get(barrelFile)?.values() || []) {
|
||
for (const src of srcs) {
|
||
set.add(src);
|
||
if (isHub(src)) expandBarrel(set, src, seen);
|
||
}
|
||
}
|
||
for (const src of barrelStars.get(barrelFile) || []) {
|
||
set.add(src);
|
||
if (isHub(src)) expandBarrel(set, src, seen);
|
||
}
|
||
};
|
||
|
||
const edgeCache = new Map();
|
||
/**
|
||
* 出边。**桶的再导出边不算**——那是 OPEN-16 的盲区:桶把组件 export 出去,
|
||
* 闭包就把它们全算成"可达",哪怕没有任何模块真的 import 过那个符号。
|
||
* 桶只保留自己的 import;消费者对桶的按名 import 由 resolveBarrelSymbol
|
||
* 展开成到落点文件的直接边。副作用/动态导入桶按执行语义整桶算活。
|
||
*/
|
||
const edgesFrom = (file) => {
|
||
if (edgeCache.has(file)) return edgeCache.get(file);
|
||
const txt = scan.get(file);
|
||
if (txt === undefined) {
|
||
edgeCache.set(file, []);
|
||
return [];
|
||
}
|
||
|
||
const out = new Set();
|
||
if (!isHub(file)) {
|
||
for (const m of txt.matchAll(IMPORT_RE)) {
|
||
const t = resolve(m[1], file);
|
||
if (t && texts.has(t)) out.add(t);
|
||
}
|
||
} else {
|
||
for (const m of txt.matchAll(IMPORT_STMT_RE)) {
|
||
const t = resolve(m[2], file);
|
||
if (t && texts.has(t)) out.add(t);
|
||
}
|
||
// 桶 → 桶 是真实的模块依赖(门面 → 子桶),保留;桶 → 叶子不传播(OPEN-16)
|
||
for (const m of txt.matchAll(REEXPORT_RE)) {
|
||
const t = resolve(m[2], file);
|
||
if (t && texts.has(t) && isHub(t)) out.add(t);
|
||
}
|
||
}
|
||
|
||
// 任何文件对桶的按名导入:连到符号落点;桶本身也保留为模块依赖
|
||
for (const m of txt.matchAll(IMPORT_STMT_RE)) {
|
||
const target = resolve(m[2], file);
|
||
if (!target || !texts.has(target) || !isHub(target)) continue;
|
||
out.add(target);
|
||
const clause = m[1].trim();
|
||
if (clause.startsWith('{')) {
|
||
for (const piece of clause.slice(1, -1).split(',')) {
|
||
const p = piece.trim();
|
||
if (!p) continue;
|
||
const imported = p.split(/\s+as\s+/)[0].trim();
|
||
if (!imported) continue;
|
||
for (const src of resolveBarrelSymbol(target, imported)) out.add(src);
|
||
}
|
||
} else {
|
||
// default / namespace:无法知道用了哪个符号,整桶算活
|
||
expandBarrel(out, target);
|
||
}
|
||
}
|
||
|
||
// 副作用 / 动态导入 / require 桶:执行语义会拉入整桶再导出
|
||
for (const m of txt.matchAll(SIDE_IMPORT_RE)) {
|
||
const target = resolve(m[1] || m[2] || m[3], file);
|
||
if (!target || !texts.has(target)) continue;
|
||
out.add(target);
|
||
if (isHub(target)) expandBarrel(out, target);
|
||
}
|
||
|
||
edgeCache.set(file, [...out]);
|
||
return edgeCache.get(file);
|
||
};
|
||
|
||
/**
|
||
* App Router 的入口 = 位于 app/ 之下、文件名属于 Next 约定的那些模块。
|
||
* ⚠ 第一版写成 /(^|\/)app\/.*(^|\/)layout\.tsx$/ —— 中间的 (^|\/) 强制要求
|
||
* `layout.tsx` 前面有一个 `/`,于是 src/app/layout.tsx 这种**根级约定文件根本没被认成入口**,
|
||
* 连带它 import 的整棵树全部误判成死码(实测把 home-content-v16、layout 自己都报成"零引用")。
|
||
* 带着那版结果去删码就是删活码。判据改成按目录段 + 基名精确匹配。
|
||
*/
|
||
const NEXT_CONVENTION_BASENAMES = new Set([
|
||
'page.tsx', 'page.ts', 'layout.tsx', 'layout.ts', 'template.tsx', 'loading.tsx',
|
||
'error.tsx', 'global-error.tsx', 'not-found.tsx', 'route.ts', 'route.tsx',
|
||
'sitemap.ts', 'robots.ts', 'manifest.ts', 'opengraph-image.tsx', 'icon.tsx',
|
||
]);
|
||
const isEntry = (f) => {
|
||
const segments = f.split(path.sep);
|
||
if (!segments.includes('app')) return false;
|
||
const base = segments[segments.length - 1];
|
||
if (NEXT_CONVENTION_BASENAMES.has(base)) return true;
|
||
// 应用级非 import 入口:根 layout 之外的约定文件与 instrumentation/proxy 同理靠文件名而非路径深度
|
||
return segments.length === 2 && segments[0] === 'src'
|
||
&& /^(instrumentation|proxy)\.ts$/.test(base);
|
||
};
|
||
|
||
const norm = files.map((f) => path.normalize(f));
|
||
const entries = norm.filter(isEntry);
|
||
// 非 src 根(scripts/e2e/config)里的每个文件都当成一个使用者种子:
|
||
// 它们引用的 src 模块不是死码,哪怕页面 import 图到不了。
|
||
const consumerSeeds = norm.filter((f) => !f.startsWith(ROOT + path.sep));
|
||
if (entries.length === 0) { console.error('未能度量:找不到任何入口文件'); process.exit(2); }
|
||
|
||
const reachable = new Set();
|
||
const stack = [...entries, ...consumerSeeds];
|
||
while (stack.length) {
|
||
const cur = stack.pop();
|
||
if (reachable.has(cur)) continue;
|
||
reachable.add(cur);
|
||
for (const t of edgesFrom(cur)) if (!reachable.has(t)) stack.push(t);
|
||
}
|
||
|
||
// 反向引用表(含测试与桶文件,供报告用)
|
||
const importers = new Map();
|
||
for (const f of texts.keys()) for (const t of edgesFrom(f)) {
|
||
if (!importers.has(t)) importers.set(t, new Set());
|
||
importers.get(t).add(f);
|
||
}
|
||
|
||
const testFile = (f) => /\.test\.|__tests__/.test(f);
|
||
|
||
const all = [...texts.keys()].filter((f) => !reachable.has(f)).sort();
|
||
|
||
/**
|
||
* 关键一步:不可达 ≠ 死码。第一版直接把 48 个不可达文件全列成"死码",
|
||
* 里面混着三类**必须**排除的东西 —— 照单删就会删掉在跑的生产代码:
|
||
* · 框架约定文件:由 Next/运行时按文件名加载,永远不会出现在 import 图里
|
||
* (proxy.ts = Next 16 的中间件约定、instrumentation*.ts、*.d.ts 是环境声明)
|
||
* · 生成物:src/generated/** 由 prisma generate 产出,不在入口闭包内
|
||
* · 组件库库存:src/components/ui/** 的 shadcn/Radix 原语是**故意**给后台与未来页面用的
|
||
* (avatar/switch/slider/progress/scroll-area 等还承载 check:grammar R2/R9 的"功能性的圆"),
|
||
* 删它们是个产品决定,不是清理。
|
||
*/
|
||
const CATEGORY_RULES = [
|
||
['convention', (f) => /(^|\/)(proxy|instrumentation|instrumentation-client)\.ts$/.test(f)
|
||
|| /\.d\.ts$/.test(f)
|
||
|| /(^|\/)(not-found|global-error|error|loading|template)\.tsx?$/.test(f)],
|
||
['generated', (f) => /(^|\/)generated\//.test(f)],
|
||
['library', (f) => /(^|\/)components\/ui\//.test(f)],
|
||
['test', (f) => testFile(f)],
|
||
];
|
||
const buckets = new Map();
|
||
for (const f of all) {
|
||
const cat = CATEGORY_RULES.find(([, pred]) => pred(f))?.[0] ?? 'dead';
|
||
if (!buckets.has(cat)) buckets.set(cat, []);
|
||
buckets.get(cat).push(f);
|
||
}
|
||
|
||
console.log(`入口 ${entries.length} 个 · 站内模块 ${texts.size} 个 · 可达 ${reachable.size} 个 · 不可达 ${all.length} 个`);
|
||
for (const cat of ['convention', 'generated', 'library', 'test', 'dead']) {
|
||
const list = buckets.get(cat) || [];
|
||
const label = {
|
||
convention: '框架约定/环境声明(不可达属正常,勿删)',
|
||
generated: '生成物(不在 import 图内,勿删)',
|
||
library: '组件库库存(未被引用但是库存,删除是产品决定)',
|
||
test: '测试文件本身',
|
||
dead: '*** 可判为死码 ***',
|
||
}[cat];
|
||
console.log(`\n[${cat}] ${list.length} 个 — ${label}`);
|
||
if (cat === 'dead' || cat === 'library') {
|
||
for (const f of list) {
|
||
const refBy = [...(importers.get(f) || [])];
|
||
const onlyDeadOrTests = refBy.length === 0 || refBy.every((r) => testFile(r) || isHub(r) || !reachable.has(r));
|
||
console.log(` ${f} ← ${refBy.length === 0 ? '零引用' : onlyDeadOrTests ? '仅测试/死链引用' : '被可达文件引用?!'}`);
|
||
}
|
||
}
|
||
}
|