release-affected.mjs 21.6 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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
#!/usr/bin/env node
/**
 * 受影响增量发版 —— 「只改了哪些子系统,就只发哪些」。
 *
 *   pnpm release:affected --base origin/master --version 1.3.0 [选项]
 *
 * 原理(业界叫 affected / impacted build):
 *   1. 定基线(默认 origin/master),取 base 之后「所有改动文件」= 已提交 + 工作区未提交。
 *   2. 每个改动文件 → 反查归属哪个 workspace 包。
 *   3. 反查依赖闭包 → 哪些「可部署子应用」(system / store) 被波及。
 *      - 改动落在某个 micro-app 目录内 → 该子应用直接受影响。
 *      - 改动落在 packages/* 共享包 → 所有(传递)依赖它的 micro-app 受影响。
 *      - 改动落在根构建配置(pnpm-workspace.yaml / pnpm-lock.yaml / turbo.json /
 *        tsconfig.base.json / .npmrc / 根 package.json)→ 全部 micro-app 受影响
 *        (保守,因这些是 turbo globalDependencies 或依赖解析真源)。
 *        纯文档/格式/编辑器/示例配置(docs 目录、*.md、.gitignore、.gitlab-ci.yml、
 *        .env.example 等)不改变 bundle,已排除,见 NON_BUILD_ROOT_RE。
 *   4. 逐个对受影响子应用调 scripts/release/release.mjs(构建 + 版本化目录 + 清单增量更新原样复用);
 *      全部成功后才跑一次上传钩子(整包 dist 只传一遍,幂等)。
 *
 * ⚠ 级联本质:micro-app 是把共享包打进 bundle 的,不是运行时远程引用;
 *    但级联严格按真实依赖图,不是「packages 目录一动就全发」:
 *      - 改 @uj/biz(system/store 都依赖)→ store + system 都发;
 *      - 改 @uj/platform-core(只有 shell 依赖)→ 无子应用受影响,仅提示 shellChanged。
 *    这是精确判定,不是漏发。
 *
 * shell(host)是独立部署单元,不走版本化清单,本命令不处理;若 shell 目录有改动会单独提示。
 */

import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { deployHost, hostRelOf } from './host-deploy.mjs';
import { assertBaseline } from './release-spec.mjs';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');

function die(message) {
  console.error(`\n[release:affected] ✗ ${message}\n`);
  process.exit(1);
}

function info(message) {
  console.log(`[release:affected] ${message}`);
}

function parseArgs(argv) {
  const flags = new Set(['dry-run', 'force', 'help', 'skip-build']);
  const out = {};
  for (let i = 0; i < argv.length; i += 1) {
    const token = argv[i];
    if (token === '--') continue; // 容忍 pnpm 把 -- 分隔符透传给脚本
    if (!token.startsWith('--')) throw new Error(`无法识别的参数:${token}`);
    const eq = token.indexOf('=');
    const key = eq > 0 ? token.slice(2, eq) : token.slice(2);
    if (flags.has(key)) {
      out[key] = true;
      continue;
    }
    const value = eq > 0 ? token.slice(eq + 1) : argv[++i];
    if (value === undefined || value.startsWith('--')) throw new Error(`参数 --${key} 缺少取值`);
    out[key] = value;
  }
  return out;
}

// ---- git 辅助:统一用 execFileSync 避免 shell 引号问题 ----
function git(args) {
  try {
    return spawnSync('git', args, { cwd: ROOT, encoding: 'utf8' }).stdout.trim();
  } catch {
    return '';
  }
}

function gitOrDie(args, what) {
  const res = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8' });
  if (res.status !== 0)
    die(
      `git ${args.join(' ')} 失败:${res.stderr?.trim() || res.error?.message || '未知错误'}(${what})`,
    );
  return res.stdout.trim();
}

/**
 * 收集 base 之后的所有改动文件(已提交 + 工作区未提交 + 未 git add 的新文件)。
 *
 * ⚠ 两个都实证过的坑:
 *   1. porcelain 状态码是固定两列(XY ),首列的空格是数据、不是填充。绝不能对
 *      status 输出调 .trim():它会吃掉第一行的前导空格,使 xy 错位、文件名被切掉
 *      首字母(' M docs/DEPLOY.md' → 'ocs/DEPLOY.md')。错名匹配不到任何包目录,
 *      会被误判成「根级改动」从而触发全量重发。故这里单独取原始 stdout,不走 git()。
 *   2. git diff 抓不到 untracked,而新增子应用常是整目录未跟踪,必须用
 *      status -uall 的 ?? 行补上,否则会被判定「无改动」而漏发。
 *   已跟踪文件的改动交给两条 diff(含 rename / staged),比抠 status 的 xy 可靠。
 */
export function collectChangedFiles(base) {
  const committed = gitOrDie(['diff', '--name-only', `${base}...HEAD`], '读取已提交改动')
    .split('\n')
    .filter(Boolean);
  const unstaged = git(['diff', '--name-only']).split('\n').filter(Boolean);
  const staged = git(['diff', '--cached', '--name-only']).split('\n').filter(Boolean);

  const res = spawnSync('git', ['status', '--porcelain=1', '-uall'], {
    cwd: ROOT,
    encoding: 'utf8',
  });
  const untracked = [];
  for (const line of (res.stdout ?? '').split('\n')) {
    if (!line) continue;
    if (line.slice(0, 2) !== '??') continue;
    const raw = line.slice(3).trim();
    // porcelain 对含空格/特殊字符的路径会加双引号
    untracked.push(raw.startsWith('"') && raw.endsWith('"') ? raw.slice(1, -1) : raw);
  }

  return [...new Set([...committed, ...unstaged, ...staged, ...untracked])];
}

/**
 * 扫描 workspace,构建:
 *   - pkgs: name -> { name, dir, isMicroApp, microAppName, isShell }
 *   - deps: name -> [依赖的 @uj/* 名](dependencies + devDependencies 合并,与 turbo affected 口径一致)
 *   - dependents: name -> [依赖它的包名](反向图)
 */
export function scanWorkspace() {
  const pkgs = new Map();
  const walk = (dir) => {
    for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
      if (!entry.isDirectory()) continue;
      if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name.startsWith('.'))
        continue;
      const full = path.join(dir, entry.name);
      const pkgFile = path.join(full, 'package.json');
      if (fs.existsSync(pkgFile)) {
        const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
        const rel = path.relative(ROOT, full).replace(/\\/g, '/');
        const isMicroApp =
          rel.startsWith('apps/web/subapps/') && pkg.name === `@uj/web-${entry.name}`;
        const isShell = rel === 'apps/web/shell';
        pkgs.set(pkg.name, {
          name: pkg.name,
          dir: rel,
          isMicroApp,
          microAppName: isMicroApp ? entry.name : null,
          isShell,
        });
        walk(full);
      } else {
        walk(full);
      }
    }
  };
  walk(ROOT);

  const deps = new Map();
  const dependents = new Map();
  for (const [name, meta] of pkgs) {
    const pj = JSON.parse(fs.readFileSync(path.join(ROOT, meta.dir, 'package.json'), 'utf8'));
    const all = [...Object.keys(pj.dependencies || {}), ...Object.keys(pj.devDependencies || {})];
    const internal = all.filter((d) => d.startsWith('@uj/') && pkgs.has(d));
    deps.set(name, internal);
    for (const d of internal) {
      if (!dependents.has(d)) dependents.set(d, []);
      dependents.get(d).push(name);
    }
  }
  return { pkgs, deps, dependents };
}

/**
 * 不影响构建产物的根级文件。这些改动不该触发「全量重发」。
 * 采用「排除名单」而非「白名单」:未匹配到的其它根文件一律保守地视为构建配置,
 * 这样将来新增根级构建文件(如 vite.config.base.ts)不会因漏枚举而漏发。
 * 只排除 release-affected.mjs 自己(纯编排,不参与任何构建);release.mjs 不排除,
 * 因为它负责 SUBAPP_BASE 注入,改了会真实改变产物内容。
 */
const NON_BUILD_ROOT_RE =
  /^(?:docs\/|releases\/|scripts\/release-affected\.mjs$|.*\.md$|\.gitignore$|\.editorconfig$|\.prettierrc(?:\.json)?$|\.prettierignore$|\.gitlab-ci\.yml$|\.env\.example$)/;

/**
 * 纯函数:给定改动文件列表,算出受影响的 micro-app 与 shell 标记。
 * 抽成纯函数便于单测(不依赖 git / 文件系统)。
 * @returns {{ affectedApps: string[], changedPackages: string[], shellChanged: boolean, rootChanged: boolean, hostAffected: boolean, ignoredRootFiles: string[], fileOwners: Map<string, string|null> }}
 */
export function computeAffected(changedFiles, workspace) {
  const { pkgs, dependents } = workspace;
  const microApps = [...pkgs.values()].filter((p) => p.isMicroApp);
  const shellName = [...pkgs.values()].find((p) => p.isShell)?.name;

  // 每个改动文件 → 归属包(取最长路径前缀匹配的包)
  const changedPackages = new Set();
  const ignoredRootFiles = [];
  const fileOwners = new Map(); // file -> ownerPackageName | null(null = 根级、非包目录)
  let rootChanged = false;
  let shellChanged = false;
  let hostAffected = false; // 主壳受影响:shell 自身 / 其依赖闭包 / 根构建配置 任一变动

  // 预计算各包 dir 前缀,按长度降序匹配
  const dirs = [...pkgs.values()]
    .map((p) => ({ name: p.name, dir: p.dir }))
    .sort((a, b) => b.dir.length - a.dir.length);

  for (const file of changedFiles) {
    const f = file.replace(/\\/g, '/');
    // 不属于任何包目录 → 视为根级改动(pnpm-workspace.yaml / tsconfig.base.json / turbo.json / 根 package.json / README ...)
    const owner = dirs.find((d) => f === d.dir || f.startsWith(d.dir + '/'));
    fileOwners.set(f, owner ? owner.name : null);
    if (!owner) {
      if (NON_BUILD_ROOT_RE.test(f)) ignoredRootFiles.push(f);
      else {
        rootChanged = true;
        hostAffected = true; // 根构建配置影响所有 app,含主壳
      }
      continue;
    }
    const meta = pkgs.get(owner.name);
    if (meta.isShell) {
      shellChanged = true;
      hostAffected = true;
      changedPackages.add(owner.name); // shell 不计入 micro-app 级联,仅标记
      continue;
    }
    changedPackages.add(owner.name);
  }

  // 反查:被改包 → 传递依赖它的所有 micro-app
  const affected = new Set();
  const visit = (pkgName, seen) => {
    if (seen.has(pkgName)) return;
    seen.add(pkgName);
    for (const parent of dependents.get(pkgName) || []) {
      const pm = pkgs.get(parent);
      if (pm?.isMicroApp) affected.add(pm.microAppName);
      if (parent === shellName) hostAffected = true; // 被主壳依赖的包变动 → 主壳需重建
      visit(parent, seen); // 继续向上,覆盖传递依赖
    }
  };
  for (const cp of changedPackages) {
    const meta = pkgs.get(cp);
    if (meta?.isMicroApp) affected.add(meta.microAppName); // 自身直接改 → 自身受影响
    visit(cp, new Set());
  }

  // 根构建配置改动 → 全部 micro-app 受影响(保守,因是 turbo globalDependencies)
  if (rootChanged) for (const m of microApps) affected.add(m.microAppName);

  const affectedApps = [...affected].sort();
  return {
    affectedApps,
    changedPackages: [...changedPackages].sort(),
    shellChanged,
    rootChanged,
    hostAffected,
    ignoredRootFiles: ignoredRootFiles.sort(),
    fileOwners,
  };
}

// ---- 主流程 ----
function main() {
  let args;
  try {
    args = parseArgs(process.argv.slice(2));
  } catch (e) {
    die(e.message);
  }
  if (args.help) {
    console.log(`
用法:
  pnpm release:affected --base <ref> --version <ver> [选项]

选项:
  --base <ref>        对比基线,默认 origin/master。可填 main / 某 tag / HEAD~3 等。
  --version <ver>     本次发布的版本号(所有受影响子应用共用,如 1.3.0)。必填。
  --public-base <url> 产物对外根地址,透传给 release.mjs(如 https://cdn.example.com)。
  --out <dir>         产物目录,透传给 release.mjs(默认 dist)。镜像部署根、每次重建。
  --state <dir>       manifest 累积状态目录(默认 .release-state / MFE_STATE_DIR),透传。
  --upload-cmd <cmd>  上传钩子,透传给最终一次性上传({dir} 即产物根,覆盖部署根)。
                      也可用环境变量 MFE_UPLOAD_CMD 提供。
  --force             允许覆盖已存在版本目录,透传给 release.mjs。
  --skip-build        复用已有 dist,不重新构建(CI 里 build job 已构建时用;host 与子应用均生效)。
  --dry-run           只打印受影响分析与将执行的命令,不构建、不落盘、不上传。
  --help              显示本帮助

说明:
  - 改动判定 = 基线之后「已提交 + 工作区未提交(含 untracked)」的全部文件。
  - 级联严格按真实依赖图:改共享包只会重发真正(传递)依赖它的子应用,
    不是「packages 目录一动就全发」。改 platform-core 只影响 shell,不动子应用。
  - 根构建配置(pnpm-workspace.yaml / pnpm-lock.yaml / turbo.json / tsconfig.base.json /
    .npmrc / 根 package.json)改动会保守地全量重发;纯文档、*.md、docs 目录、
    格式/编辑器/CI 配置、.env.example 不触发全量。
  - 主壳(host) 改动会自动构建并部署:shell 自身文件、被 shell 依赖的共享包
    (platform-core / contracts / ui / biz / design-tokens,按真实依赖图判定)、或根构建配置
    任一变动,都会触发主壳重建;主壳产物落到 /mfe/host/<version>/(与子应用同构的不可变目录),
    站点根只覆盖一个指向它的 index.html,与子应用一并、一次性上传。
    无需再单独跑 deploy:shell。
  - ⚠ 默认基线是 origin/master:未 push 的本地提交也会被算进「改动」,
    第一次跑若不想全量,先 push/fetch 或用 --base HEAD~N 指定真实基线。
`);
    process.exit(0);
  }

  const base = args.base || 'origin/master';
  const version = args.version;
  if (!version) die('缺少 --version。用 --help 查看用法。');
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(version) || version.includes('..')) {
    die(`版本号 "${version}" 非法:只允许字母数字 . _ -,且不得含 ".."`);
  }

  // 确认基线存在
  const verify = spawnSync('git', ['rev-parse', '--verify', base], { cwd: ROOT, encoding: 'utf8' });
  if (verify.status !== 0) {
    die(`基线 ${base} 不存在或无法解析。可用 --base 指定其它 ref(如 main / 某 tag)。`);
  }

  const changedFiles = collectChangedFiles(base);
  if (changedFiles.length === 0) {
    info(`基线 ${base} 之后没有任何改动,无需发布。`);
    process.exit(0);
  }

  const workspace = scanWorkspace();
  const { affectedApps, changedPackages, rootChanged, hostAffected, ignoredRootFiles } =
    computeAffected(changedFiles, workspace);

  const isWin = process.platform === 'win32';
  const pnpmBin = isWin ? 'pnpm.cmd' : 'pnpm';
  const outRoot = path.resolve(ROOT, args.out ?? process.env.MFE_OUT_DIR ?? 'dist');
  const stateDir = args.state ?? process.env.MFE_STATE_DIR;
  const skipBuild = Boolean(args['skip-build']);
  const shellName = [...workspace.pkgs.values()].find((p) => p.isShell)?.name;

  // ---- 打印计划 ----
  console.log('\n[release:affected] ==== 受影响分析 ====');
  console.log(`  基线        : ${base}`);
  console.log(`  改动文件数  : ${changedFiles.length}`);
  console.log(
    `  改动包      : ${changedPackages.length ? changedPackages.join(', ') : '(无)'}${rootChanged ? '  [含根构建配置 → 全量]' : ''}`,
  );
  if (ignoredRootFiles.length) {
    console.log(`  忽略文档类  : ${ignoredRootFiles.length} 个(不改变产物,不触发全量)`);
  }
  console.log(`  受影响子系统: ${affectedApps.length ? affectedApps.join(', ') : '(无)'}`);
  if (hostAffected) {
    console.log(`  ⚠ 主壳(host) 受影响 → 将一并构建并部署(${shellName} → mfe/host/${version}/)`);
  }
  const skipped = [...workspace.pkgs.values()]
    .filter((p) => p.isMicroApp && !affectedApps.includes(p.microAppName))
    .map((p) => p.microAppName);
  if (skipped.length) console.log(`  跳过子系统  : ${skipped.join(', ')}(未受影响)`);
  console.log('');

  if (affectedApps.length === 0 && !hostAffected) {
    info('没有受影响的子系统,也未改动主壳,结束。');
    process.exit(0);
  }

  const dryRun = Boolean(args['dry-run']);
  const publicBase = args['public-base'];
  const out = args.out;
  const force = Boolean(args.force);
  const uploadCmd = args['upload-cmd'] ?? process.env.MFE_UPLOAD_CMD;
  const remoteManifest = args['remote-manifest'] ?? process.env.MFE_REMOTE_MANIFEST;

  if (dryRun) {
    console.log('[release:affected] --dry-run:以下动作不会执行。');
    console.log(`  0. 重建产物目录 ${path.relative(ROOT, outRoot)}/(只装本次要覆盖的文件)`);
    let step = 1;
    for (const [i, app] of affectedApps.entries()) {
      const cmd = [
        'node scripts/release/release.mjs',
        `--app ${app}`,
        `--version ${version}`,
        publicBase ? `--public-base ${publicBase}` : '',
        out ? `--out ${out}` : '',
        stateDir ? `--state ${stateDir}` : '',
        force ? '--force' : '',
        skipBuild ? '--skip-build' : '',
        i > 0 ? '--no-clean' : '',
      ]
        .filter(Boolean)
        .join(' ');
      console.log(`  ${step}. ${cmd}`);
      step += 1;
    }
    if (hostAffected) {
      console.log(
        `  ${step}. 主壳 ${shellName} 构建(SHELL_BASE=/${hostRelOf(version)})→ 整目录落 ${hostRelOf(version)},根 index.html 只写指针`,
      );
      step += 1;
    }
    console.log(
      `  ${step}. 一次性上传({dir}=${outRoot} 覆盖部署根):${uploadCmd ?? '(未配置,仅产出入参)'}`,
    );
    console.log('');
    process.exit(0);
  }

  // ---- 增量发版前必须确认能拼出完整清单(与 release:spec 同一道拦截)----
  assertBaseline({
    tag: 'release:affected',
    apps: affectedApps,
    allApps: [...workspace.pkgs.values()].filter((p) => p.isMicroApp).map((p) => p.microAppName),
    remoteManifest,
    stateDir: path.resolve(ROOT, stateDir ?? process.env.MFE_STATE_DIR ?? '.release-state'),
  });

  // ---- 逐个发版 ----
  // 产物目录由**第一个**子应用负责清空(release.mjs 在构建与资源校验都过了才清),
  // 后续一律 --no-clean 共用同一份产物树 —— 否则后一个会把前一个的产物删掉。
  for (const [i, app] of affectedApps.entries()) {
    info(`发版子系统 ${app}(${version})...`);
    const cmd = ['node', 'scripts/release/release.mjs', '--app', app, '--version', version];
    // 同 release:spec:整批应用一起保护,避免后续子应用用线上旧值覆盖前面已发的条目。
    if (affectedApps.length) cmd.push('--keep-local', affectedApps.join(','));
    if (publicBase) cmd.push('--public-base', publicBase);
    if (out) cmd.push('--out', out);
    if (stateDir) cmd.push('--state', stateDir);
    if (force) cmd.push('--force');
    if (skipBuild) cmd.push('--skip-build');
    if (remoteManifest) cmd.push('--remote-manifest', remoteManifest);
    if (i > 0) cmd.push('--no-clean');
    const res = spawnSync(cmd[0], cmd.slice(1), { cwd: ROOT, stdio: 'inherit' });
    if (res.status !== 0) die(`子系统 ${app} 发版失败(exit ${res.status}),已中止,未执行上传。`);
  }

  // 只发主壳时没有子应用负责清空,这里补一次(产物根只装主壳产物)。
  if (affectedApps.length === 0) {
    fs.rmSync(outRoot, { recursive: true, force: true });
    fs.mkdirSync(outRoot, { recursive: true });
    info(`产物目录已重建:${path.relative(ROOT, outRoot)}/`);
  }

  // ---- 主壳(host)受影响时 → /mfe/host/<version>/,站点根只写指针 ----
  // 与 release:spec 共用 host-deploy.mjs,不另写一份(否则两边必然分叉)。
  if (hostAffected) {
    info(`主壳 ${shellName} 受影响 → 构建并落到 ${hostRelOf(version)}...`);
    deployHost({
      root: ROOT,
      outRoot,
      version,
      shellName,
      workspace: workspace.pkgs,
      skipBuild,
      pnpmBin,
      isWin,
      info,
      die,
    });
  }
  // 主壳未受影响 → 产物根不会有它的文件(目录已重建),无需额外清理

  // ---- 成功后一次性上传:产物是一棵镜像部署根的树,{dir} 一个变量覆盖过去 ----
  if (uploadCmd) {
    const manifestFile = path.join(outRoot, 'mfe', 'manifest.json');
    const template = String(uploadCmd);
    if (!/\{dir\}/.test(template)) {
      info('⚠ 上传钩子未包含 {dir}:产物是镜像部署根的一棵树,一个 {dir} 覆盖过去即可。');
    }
    const cmd = template
      .replaceAll('{dir}', outRoot)
      .replaceAll('{target}', outRoot)
      .replaceAll('{remote}', '')
      .replaceAll('{host}', outRoot) // 兼容旧钩子:主壳已落在产物根
      .replaceAll('{file}', manifestFile);
    info(`执行一次性上传钩子:${cmd}`);
    const res = spawnSync(cmd, { cwd: ROOT, stdio: 'inherit', shell: true });
    if (res.status !== 0)
      die(`上传失败(exit ${res.status})。各子系统与 host 已落盘到 ${outRoot},远端尚未生效。`);
  }

  console.log('\n[release:affected] ==== 完成 ====');
  console.log(
    `  已发版子系统: ${affectedApps.length ? affectedApps.join(', ') : '(无)'} @ ${version}`,
  );
  if (hostAffected)
    console.log(`  主壳(host)  : ${shellName} → ${hostRelOf(version)}(站点根 index.html 是指针)`);
  console.log(
    `  产物        : ${path.relative(ROOT, outRoot)}/ 只含本次内容,覆盖进部署根即生效;未出现的模块保持线上老版本。`,
  );
  console.log(
    '  发布生效:浏览器必须【整页刷新】;manifest.json 与 host index.html 建议 no-cache。',
  );
  console.log('');
}

// 直接运行时执行 main;被 import 时只导出纯函数(便于测试)
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  main();
}