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

/**
 * 架构边界闸门(CI 必跑)。
 *
 * 本仓库有两条独立技术栈,护栏分别设置:
 *  - web lane(apps/web):主壳 + wujie 微前端子应用,受下方「web 子应用」四条硬约束;
 *  - mp lane(apps/mp):原生小程序,自带 wx.request,不经主壳代理,受「小程序」护栏约束。
 *
 * ESLint 只能看 import 语句,看不住配置与全局变量;这里从磁盘事实复查硬约束:
 *  【web 子应用】不得:引用 @uj/platform-core(host 独占运行时)/ 出现 PEM 虚拟模块或签名密钥
 *  env(请求层不下放)/ vite.config 挂 /api 代理或读密钥 / 直接 import wujie core /
 *  运行时 import axios / 跨子应用依赖 @uj/web-* / 自行落地文件下载(下载中心唯一出口)。
 *  【小程序】不得:反向引用 web/host 独占运行时(platform-core / platform-sdk / vite-config /
 *  @uj/web-* / wujie)—— 小程序复用 @uj/api-core(createWxSender),但不耦合 web lane。
 *
 * 这些约束任何一条破了,症状都不是编译错误,而是「登录 10011」「两份签名状态」
 * 「两份 Context」这类运行时故障,必须静态拦住。
 */
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
// web lane:主壳 + wujie 子应用。小程序 lane 在 apps/mp,单独处理,不混入本扫描根。
const SUBAPPS_ROOT = path.join(ROOT, 'apps', 'web', 'subapps');
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',
    // 通用匹配所有 @uj/web-*(含 shell),新增子应用零维护。
    // 曾写死 web-(system|store),导致新增的第三个子应用之间互相引用会漏检。
    re: /@uj\/web-/,
    message: '引用了主壳或另一个子应用的包;业务域之间禁止直接依赖',
  },
  {
    id: 'download-direct',
    // 下载中心是全系统唯一下载网关:子应用自行落地文件会绕过主壳加签 / 401 统一登出,
    // 且丢掉轮询 / 全站通知 / 面板历史 / 去重 / 取消。只拦「明确的文件落地」写法,
    // 不误伤 window.location.href 这类路由跳转,也不误伤注释文字;
    // <a href> / <UButton href> 触发下载的语义判定见 docs/PORT_CONVERSION.md §14.7。
    re: /\bcreateObjectURL\s*\(|\bwindow\.open\s*\(|\.download\s*=\s*[^=]|\ba\.click\s*\(/,
    message:
      '子应用自行落地下载;所有下载必须经 @uj/platform-sdk 的 downloadCenter 登记到主壳下载中心(见 docs/PORT_CONVERSION.md §14)',
  },
];

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。
  // 「.uj-xxx .ant-yyy」这类带自有类祖先的局部限定只动自己的样式,与新巡检脚本同口径放行。
  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('/');
    const bareAnt = [...text.matchAll(/(^|\n)\s*([^{}]+)\{/g)].some((m) =>
      m[2].split(',').some((part) => {
        const chain = part
          .trim()
          .split(/\s+|>|\+|~/)
          .filter(Boolean);
        return chain.length > 0 && chain.every((s) => /^\.ant-/.test(s));
      }),
    );
    if (bareAnt) {
      warnings.push(`[css] ${rel}: 含裸 .ant-* 选择器,确认未覆盖组件内部几何属性`);
    }
  }
}

// ---------------------------------------------------------------------------
// 小程序 lane(apps/mp):与 web 子应用是两条独立技术栈,分别设护栏。
// web 子应用的「请求层不下放」规则不适用于 mp(mp 自带 wx.request,不经主壳代理),
// 但 mp 也不得反向耦合 web/host 独占运行时(axios/RSA/PEM/vite/wujie/主壳子应用包)。
// 这条护栏保证「mp 引入 @uj/api-core 复用请求/签名适配」不会退化成「mp 偷偷引 web 运行时」。
// ---------------------------------------------------------------------------
const MP_ROOT = path.join(ROOT, 'apps', 'mp');
const MP_RULES = [
  {
    id: 'host-runtime',
    re: /@uj\/platform-core/,
    message:
      '小程序引用了 host 独占运行时 @uj/platform-core;请改用 @uj/api-core(createWxSender)。',
  },
  {
    id: 'web-sdk',
    re: /@uj\/platform-sdk/,
    message: '小程序不经由主壳 props.request,请勿引用 web 子应用 SDK @uj/platform-sdk。',
  },
  {
    id: 'web-build',
    re: /@uj\/vite-config/,
    message: '小程序不跑 vite 构建,请勿引用 @uj/vite-config。',
  },
  {
    id: 'cross-lane',
    re: /@uj\/web-/,
    message: '小程序不得直接依赖 web 子应用 / 主壳包(@uj/web-*)。',
  },
  {
    id: 'wujie-core',
    re: /from\s+['"]wujie['"]/,
    message: '小程序无 wujie 微前端容器,请勿直接 import wujie。',
  },
];

if (fs.existsSync(MP_ROOT)) {
  const mpDirs = fs
    .readdirSync(MP_ROOT, { withFileTypes: true })
    .filter((e) => e.isDirectory())
    .map((e) => path.join(MP_ROOT, e.name));
  for (const appDir of mpDirs) {
    const files = collect(path.join(appDir, 'src'), ['.ts', '.tsx']);
    for (const file of files) {
      const text = fs.readFileSync(file, 'utf8');
      const rel = path.relative(ROOT, file).split(path.sep).join('/');
      for (const rule of MP_RULES) {
        if (rule.re.test(text)) errors.push(`[${rule.id}] ${rel}: ${rule.message}`);
      }
    }
  }
  console.log(`[boundaries] 扫描 ${mpDirs.length} 个小程序`);
}

// 反向检查:只有 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] 通过');