check-boundaries.mjs 4.43 KB
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

/**
 * 架构边界闸门(CI 必跑)。
 *
 * ESLint 只能看 import 语句,看不住配置与全局变量;这里从磁盘事实复查四条硬约束:
 *  1. 子应用不得引用 @uj/platform-core(host 独占运行时)
 *  2. 子应用不得出现 PEM 虚拟模块 / 签名密钥 env(请求层不下放)
 *  3. 子应用 vite.config 不得挂 /api 代理或读密钥
 *  4. 子应用不得直接 import wujie core(应只用 window.$wujie)
 *
 * 这四条任何一条破了,症状都不是编译错误,而是「登录 10011」「两份签名状态」
 * 「两份 Context」这类运行时故障,必须静态拦住。
 */
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const SUBAPPS_ROOT = path.join(ROOT, 'apps', 'web', 'micro-apps');
const errors = [];
const warnings = [];

const RULES = [
  {
    id: 'host-runtime',
    re: /@uj\/platform-core/,
    message: '引用了 host 独占运行时 @uj/platform-core;请改用 @uj/platform-sdk',
  },
  {
    id: 'virtual-key',
    re: /virtual:(client-private-key|server-public-key)/,
    message: '引用了 PEM 虚拟模块;子应用构建不得注入密钥',
  },
  {
    id: 'secret-env',
    re: /VITE_(CLIENT_PRIVATE_KEY|SERVER_PUBLIC_KEY|API_TARGET|SIGN_ENABLED|STRICT_VERIFY)/,
    message: '读取了签名/后端环境变量;这些只属于 shell',
  },
  {
    id: 'wujie-core',
    re: /from\s+['"]wujie['"]/,
    message: '直接 import wujie core;子应用应只用 window.$wujie.bus / props',
  },
  {
    id: 'axios-runtime',
    re: /^import\s+(?!type\s)[^;]*from\s+['"]axios['"]/m,
    message: '运行时 import axios(type-only 允许);请求必须经 props.request',
  },
  {
    id: 'cross-subapp',
    re: /@uj\/web-(system|store)/,
    message: '引用了另一个子应用的包;业务域之间禁止直接依赖',
  },
];

function collect(dir, exts) {
  const out = [];
  if (!fs.existsSync(dir)) return out;
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    if (entry.name === 'node_modules' || entry.name === 'dist') continue;
    const full = path.join(dir, entry.name);
    if (entry.isDirectory()) out.push(...collect(full, exts));
    else if (exts.some((e) => entry.name.endsWith(e))) out.push(full);
  }
  return out;
}

const subappDirs = fs.existsSync(SUBAPPS_ROOT)
  ? fs
      .readdirSync(SUBAPPS_ROOT, { withFileTypes: true })
      .filter((e) => e.isDirectory())
      .map((e) => path.join(SUBAPPS_ROOT, e.name))
  : [];

for (const appDir of subappDirs) {
  const files = collect(path.join(appDir, 'src'), ['.ts', '.tsx']);
  const viteConfig = path.join(appDir, 'vite.config.ts');

  for (const file of [...files, ...(fs.existsSync(viteConfig) ? [viteConfig] : [])]) {
    const text = fs.readFileSync(file, 'utf8');
    const rel = path.relative(ROOT, file).split(path.sep).join('/');
    for (const rule of RULES) {
      if (rule.re.test(text)) errors.push(`[${rule.id}] ${rel}: ${rule.message}`);
    }
  }

  // CSS:裸 .ant-* 覆盖会改 antd 内部盒模型,项目约定一律走 ConfigProvider token。
  // 旧仓迁过来的 CSS 里可能已有,先只告警,待样式归类中逐条清理。
  for (const file of collect(path.join(appDir, 'src'), ['.css'])) {
    const text = fs.readFileSync(file, 'utf8');
    const rel = path.relative(ROOT, file).split(path.sep).join('/');
    if (/^\s*\.ant-/.test(text) || /\n\s*\.ant-/.test(text)) {
      warnings.push(`[css] ${rel}: 含裸 .ant-* 选择器,确认未覆盖组件内部几何属性`);
    }
  }
}

// 反向检查:只有 shell 允许读 PEM 虚拟模块。
const shellConfig = path.join(ROOT, 'apps/web/shell/vite.config.ts');
if (fs.existsSync(shellConfig)) {
  const text = fs.readFileSync(shellConfig, 'utf8');
  if (!text.includes('createShellConfig')) {
    errors.push('[shell] vite.config.ts 未使用 createShellConfig,PEM 虚拟模块可能缺失');
  }
} else {
  errors.push('[shell] 缺少 apps/web/shell/vite.config.ts');
}

console.log(`[boundaries] 扫描 ${subappDirs.length} 个子应用`);
for (const w of warnings) console.warn(`  ⚠ ${w}`);
for (const e of errors) console.error(`  ✗ ${e}`);
console.log(`[boundaries] 错误 ${errors.length} / 告警 ${warnings.length}`);

if (errors.length) {
  console.error('[boundaries] 架构边界被破坏,请修复后再提交。');
  process.exit(1);
}
console.log('[boundaries] 通过');