Files
ai-platform/scripts/check-module-independence.mjs
dongskandClaude Sonnet 4.6 noreply@anthropic.com> 8699798ea5 feat: 模组全维度独立,消除全局 DOM/Portal/存储污染
- jieya-ibp/welltrust-qap ThemeContext 改为作用域容器承载 CSS 变量与背景色,不再写 document
- 删除 order-cost CostCockpit 对 documentElement 的死变量写入
- bomx Drawer createPortal 挂载点内移到 .bomx-app,移除 document.body 兜底
- knowledge-graph 拖拽 cursor 改为根容器 ref
- 新增 check-module-independence 门禁并接入 build
- SOP 与融合技能文档补充「模组完全独立互不影响」章节

Co-Authored-By: Claude Sonnet 4.6 noreply@anthropic.com>
2026-10-19 09:10:30 +08:00

350 lines
11 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/**
* 模组独立性检查(门禁脚本)
*
* 平台规则:src/modules 下每个模组必须完全独立、互不影响,禁止运行时写入全局 DOM、
* 向 head 注入全局样式/脚本、将 Portal 挂到 document.body、使用无前缀的 storage key。
*
* 实现:先做词法剥离(注释 + 字符串/模板字面量),再用正则检测违规模式。
* 零依赖,Node >= 18。
*/
import { readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const MODULES_DIR = path.join(ROOT, 'src', 'modules');
const EXTS = new Set(['.ts', '.tsx', '.js', '.jsx']);
// 平台级共享 storage key 白名单(不计模组前缀)
const STORAGE_WHITELIST = new Set(['userToken', 'userInfo']);
/* ---------------------------------- 文件收集 ---------------------------------- */
function collectFiles(dir, out = []) {
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return out;
}
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
collectFiles(full, out);
} else if (entry.isFile() && EXTS.has(path.extname(entry.name))) {
out.push(full);
}
}
return out;
}
/* -------------------------------- 词法剥离 -------------------------------- */
/**
* 剥离源码中的注释与字符串/模板字面量,保留换行以维持行号对齐。
* 返回两份结果:
* - commentStripped:仅去掉 // 与 /* *\/ 注释,字符串内容保留(用于需要读取
* 字符串字面量的检查,如 storage key、createElement 标签名)。
* - fullyStripped:注释 + 字符串/模板全部替换为空格(用于避免字符串内关键字误报)。
*
* 被剥离的非换行字符统一替换为空格,保证字符偏移与行号不变。
*/
function stripSource(source) {
let commentStripped = '';
let fullyStripped = '';
let inBlockComment = false;
let inTemplate = false;
let i = 0;
const pushSpace = (ch) => {
const sp = ch === '\n' ? '\n' : ' ';
commentStripped += sp;
fullyStripped += sp;
};
while (i < source.length) {
const ch = source[i];
const next = source[i + 1];
if (inBlockComment) {
if (ch === '*' && next === '/') {
inBlockComment = false;
commentStripped += ' ';
fullyStripped += ' ';
i += 2;
} else {
pushSpace(ch);
i++;
}
continue;
}
if (inTemplate) {
if (ch === '\\') {
// 转义字符整体跳过
commentStripped += ch + (next || '');
fullyStripped += ' ' + (next === '\n' ? '\n' : ' ');
i += 2;
continue;
}
if (ch === '`') {
inTemplate = false;
pushSpace(ch);
i++;
continue;
}
if (ch === '$' && next === '{') {
// 模板插值:按大括号深度跳过(插值内代码也一并剥离)
let depth = 1;
commentStripped += ' ';
fullyStripped += ' ';
i += 2;
while (i < source.length && depth > 0) {
const c = source[i];
if (c === '{') depth++;
else if (c === '}') depth--;
pushSpace(c);
i++;
}
continue;
}
pushSpace(ch);
i++;
continue;
}
// —— 普通代码态 ——
if (ch === '/' && next === '/') {
// 行注释:跳到行尾
while (i < source.length && source[i] !== '\n') {
commentStripped += ' ';
fullyStripped += ' ';
i++;
}
continue;
}
if (ch === '/' && next === '*') {
inBlockComment = true;
commentStripped += ' ';
fullyStripped += ' ';
i += 2;
continue;
}
if (ch === '`') {
inTemplate = true;
pushSpace(ch);
i++;
continue;
}
if (ch === '"' || ch === "'") {
const quote = ch;
commentStripped += ch; // commentStripped 保留字符串内容
fullyStripped += ' ';
i++;
while (i < source.length) {
const c = source[i];
if (c === '\\') {
commentStripped += c + (source[i + 1] || '');
fullyStripped += ' ' + (source[i + 1] === '\n' ? '\n' : ' ');
i += 2;
continue;
}
if (c === quote) {
commentStripped += quote;
fullyStripped += ' ';
i++;
break;
}
if (c === '\n') {
// 字符串跨行(非法 JS,但容错)
commentStripped += '\n';
fullyStripped += '\n';
i++;
continue;
}
commentStripped += c;
fullyStripped += ' ';
i++;
}
continue;
}
commentStripped += ch;
fullyStripped += ch;
i++;
}
return { commentStripped, fullyStripped };
}
/* ------------------------------ 工具:顶层逗号切分 ------------------------------ */
/** 按顶层逗号切分参数列表,括号/方括号/花括号内的逗号不切分。 */
function splitTopLevel(s) {
const parts = [];
let cur = '';
let paren = 0, bracket = 0, brace = 0;
for (const ch of s) {
if (ch === '(') paren++;
else if (ch === ')') paren--;
else if (ch === '[') bracket++;
else if (ch === ']') bracket--;
else if (ch === '{') brace++;
else if (ch === '}') brace--;
if (ch === ',' && paren === 0 && bracket === 0 && brace === 0) {
parts.push(cur);
cur = '';
continue;
}
cur += ch;
}
parts.push(cur);
return parts;
}
/** 计算字符串中 index 位置对应的行号(1-based)。 */
function lineAt(text, index) {
let line = 1;
for (let k = 0; k < index && k < text.length; k++) {
if (text[k] === '\n') line++;
}
return line;
}
/* -------------------------------- 违规判定 -------------------------------- */
/**
* 判定 storage key 是否合规:
* - 在白名单内;或
* - 包含 - / _ / . ;或
* - 匹配小写驼峰模块前缀 ^[a-z]{2,}[A-Z](如 ocDataSourceMode)。
*/
function isStorageKeyCompliant(key) {
if (STORAGE_WHITELIST.has(key)) return true;
if (/[-_.]/.test(key)) return true;
if (/^[a-z]{2,}[A-Z]/.test(key)) return true;
return false;
}
/**
* 扫描单个文件,返回违规列表 [{ line, reason }]。
*/
function scanFile(source) {
const violations = [];
const { commentStripped, fullyStripped } = stripSource(source);
const commentLines = commentStripped.split('\n');
const fullyLines = fullyStripped.split('\n');
// —— 预扫描:收集被赋值为 createElement('link'|'style'|'script') 的变量名 ——
// 用于跨行判定 document.head.appendChild(var) 是否为注入全局样式/脚本。
const injectVars = new Set();
const assignRe = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*document\.createElement\s*\(\s*['"`](link|style|script)['"`]/g;
for (const line of commentLines) {
let m;
while ((m = assignRe.exec(line)) !== null) {
injectVars.add(m[1]);
}
}
// —— 逐行检测(a / b / c / e)——
for (let idx = 0; idx < fullyLines.length; idx++) {
const lineNo = idx + 1;
const fLine = fullyLines[idx];
const cLine = commentLines[idx];
// a. document.body.(style|classList).
if (/document\.body\.(style|classList)\./.test(fLine)) {
violations.push({ line: lineNo, reason: '写入 document.body 的 style/classList(应仅作用于模组根容器)' });
}
// b. document.documentElement.(style|setAttribute|classList).
if (/document\.documentElement\.(style|setAttribute|classList)\./.test(fLine)) {
violations.push({ line: lineNo, reason: '写入 document.documentElement 的 style/setAttribute/classList(CSS 变量应挂在模组根容器)' });
}
// c. document.head.appendChild/insertBefore 注入 link/style/script
if (/document\.head\.(appendChild|insertBefore)\s*\(/.test(cLine)) {
// 同行内是否直接 createElement('link'|'style'|'script')
const inlineInject = /createElement\s*\(\s*['"`](link|style|script)['"`]/.test(cLine);
// 或参数为前面收集到的注入变量
let varInject = false;
if (!inlineInject) {
const argMatch = cLine.match(/document\.head\.(?:appendChild|insertBefore)\s*\(\s*([A-Za-z_$][\w$]*)/);
if (argMatch && injectVars.has(argMatch[1])) varInject = true;
}
if (inlineInject || varInject) {
violations.push({ line: lineNo, reason: '向 document.head 注入 link/style/script 元素(禁止模组注入全局样式/脚本)' });
}
}
// e. localStorage/sessionStorage key 无前缀
const storageRe = /(local|session)Storage\.(getItem|setItem|removeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g;
let sm;
while ((sm = storageRe.exec(cLine)) !== null) {
const key = sm[3];
if (!isStorageKeyCompliant(key)) {
violations.push({ line: lineNo, reason: `storage key「${key}」未带模组前缀(需含 -/_/. 或以小写驼峰模块名开头)` });
}
}
}
// —— 整段检测(d. createPortal 第二参数为 document.body,可能跨多行)——
const portalRe = /createPortal\s*\(/g;
let pm;
while ((pm = portalRe.exec(fullyStripped)) !== null) {
const start = pm.index;
let depth = 1;
let j = start + pm[0].length;
while (j < fullyStripped.length && depth > 0) {
const c = fullyStripped[j];
if (c === '(') depth++;
else if (c === ')') depth--;
j++;
}
if (depth === 0) {
const args = fullyStripped.slice(start + pm[0].length, j - 1);
const parts = splitTopLevel(args);
// 第二参数为 Portal 挂载容器:若其中出现 document.body(含兜底表达式
// 如 portalMount ?? document.body),即视为挂到全局 body,判违规。
if (parts.length >= 2 && /\bdocument\.body\b/.test(parts[1])) {
const lineNo = lineAt(fullyStripped, start);
violations.push({ line: lineNo, reason: 'createPortal 挂载点含 document.body(Portal 应挂在模组根容器内,禁止兜底到全局 body)' });
}
}
}
return violations;
}
/* ------------------------------------ 主流程 ----------------------------------- */
function main() {
const files = collectFiles(MODULES_DIR).sort();
const violations = [];
for (const file of files) {
const rel = path.relative(ROOT, file).split(path.sep).join('/');
const source = readFileSync(file, 'utf8');
const fileViolations = scanFile(source);
for (const v of fileViolations) {
violations.push(`[违规] ${rel}:${v.line} ${v.reason}`);
}
}
if (violations.length > 0) {
for (const v of violations) console.log(v);
const badFiles = new Set(violations.map((v) => v.split(':')[0].replace('[违规] ', ''))).size;
console.log(
`[汇总] 模组独立检查失败:共 ${violations.length} 条违规,涉及 ${badFiles} 个文件(共扫描 ${files.length} 个文件)`,
);
process.exit(1);
}
console.log(`✓ 模组独立检查通过(扫描 ${files.length} 个文件)`);
process.exit(0);
}
main();