deploy.mjs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. #!/usr/bin/env node
  2. /**
  3. * 构建 + 部署到华为云 OBS(www-ai.fmode.cn)+ 刷新 CDN(ai.fmode.cn)
  4. *
  5. * 用法:
  6. * node scripts/deploy.mjs # 完整:构建 → 校验 → 上传 → 刷新 CDN → 探活
  7. * node scripts/deploy.mjs --skip-build # 跳过构建,直接上传已有 dist
  8. * node scripts/deploy.mjs --dry-run # 只打印将要执行的动作,不执行
  9. *
  10. * 前置条件:
  11. * ① 已安装 obsutil 与 hcloud CLI,且在 `hcloud configure list` 中已配置 profile
  12. * ② 构建配置 `npm run build` 可用(production)
  13. *
  14. * 🔴 与旧 deploy.ps1 的差异:
  15. * - 项目名从 `nova-aigc` 改为 `fmode-app-v2`,产物路径改为 `dist/fmode-app-v2/browser`
  16. * - 异常时不静默继续:任何一步失败即 `process.exit(1)`
  17. * - 增加构建产物自检(防 demo/mock 包误发线上)
  18. */
  19. import { execFileSync } from 'node:child_process';
  20. import { existsSync, readFileSync, readdirSync } from 'node:fs';
  21. import { dirname, join, resolve } from 'node:path';
  22. import { fileURLToPath } from 'node:url';
  23. const here = dirname(fileURLToPath(import.meta.url));
  24. const projectRoot = resolve(here, '..');
  25. const distDir = join(projectRoot, 'dist/fmode-app-v2/browser');
  26. const BUCKET = 'obs://www-ai.fmode.cn';
  27. const CDN_BASE = 'https://ai.fmode.cn';
  28. const OBS_EP = 'obs.cn-south-1.myhuaweicloud.com';
  29. const CDN_REGION = 'cn-north-1';
  30. const args = new Set(process.argv.slice(2));
  31. const skipBuild = args.has('--skip-build');
  32. const dryRun = args.has('--dry-run');
  33. /** 执行命令并回显 */
  34. function run(cmd, argv, opts = {}) {
  35. const printable = `${cmd} ${argv.join(' ')}`;
  36. console.log(`\n$ ${printable}`);
  37. if (dryRun) return '';
  38. try {
  39. return execFileSync(cmd, argv, { cwd: projectRoot, stdio: 'inherit', ...opts });
  40. } catch (e) {
  41. console.error(`\n❌ 命令失败:${printable}`);
  42. process.exit(1);
  43. }
  44. }
  45. /**
  46. * 探活用 Node 原生 fetch,不依赖 curl。
  47. * Windows 上的 curl 是原生程序,`-o /dev/null` 会被当成文件路径写盘,不能拿来判状态码。
  48. */
  49. async function probe(url, timeoutMs = 30_000) {
  50. const ac = new AbortController();
  51. const timer = setTimeout(() => ac.abort(), timeoutMs);
  52. try {
  53. const res = await fetch(url, { signal: ac.signal, redirect: 'follow' });
  54. return { status: res.status, body: await res.text() };
  55. } catch {
  56. return { status: 0, body: '' };
  57. } finally {
  58. clearTimeout(timer);
  59. }
  60. }
  61. // ── 1. 构建 ────────────────────────────────────────────────────────────────
  62. if (!skipBuild) {
  63. console.log('\n=== [1/5] 构建 production ===');
  64. run('npm', ['run', 'build']);
  65. } else {
  66. console.log('\n=== [1/5] 跳过构建(--skip-build)===');
  67. }
  68. // ── 2. 产物自检 ────────────────────────────────────────────────────────────
  69. console.log('\n=== [2/5] 构建产物自检 ===');
  70. if (!existsSync(distDir)) {
  71. console.error(`❌ 产物目录不存在:${distDir}`);
  72. process.exit(1);
  73. }
  74. const files = readdirSync(distDir);
  75. const indexHtml = join(distDir, 'index.html');
  76. if (!files.includes('index.html')) {
  77. console.error('❌ 缺少 index.html');
  78. process.exit(1);
  79. }
  80. const html = readFileSync(indexHtml, 'utf8');
  81. if (!/app-root/.test(html)) {
  82. console.error('❌ index.html 不含 <app-root>,产物异常');
  83. process.exit(1);
  84. }
  85. // 主包与依赖 chunk 中若含演示数据开关且为 true,说明误发了 mock 包
  86. const jsFiles = files.filter((f) => f.endsWith('.js'));
  87. let sawMockSwitch = false;
  88. for (const f of jsFiles) {
  89. const src = readFileSync(join(distDir, f), 'utf8');
  90. const m = src.match(/useMockData\s*:\s*!?[01]/);
  91. if (!m) continue;
  92. sawMockSwitch = true;
  93. if (/!\s*0/.test(m[0])) {
  94. console.error(`❌ 检测到演示数据包(${f} 中 useMockData: true),拒绝部署到线上`);
  95. console.error(' 线上请用 `npm run build`;演示包请用 `npm run build:mock` 走本地 mock 服务');
  96. process.exit(1);
  97. }
  98. }
  99. if (sawMockSwitch) {
  100. console.log(' ✓ 数据源开关 = 真实(useMockData: false)');
  101. } else {
  102. console.warn(' ⚠ 未在产物中找到 useMockData 开关(可能已被 tree-shake),跳过校验');
  103. }
  104. console.log(` ✓ index.html + ${files.length} 个文件`);
  105. // ── 3. 上传 OBS ────────────────────────────────────────────────────────────
  106. console.log('\n=== [3/5] 同步到 OBS ===');
  107. /*
  108. * 先 sync 覆盖、再清多余文件:不用先清空桶,避免「清空后上传失败」导致站点空窗。
  109. * `-f` 跳过确认;**不传 `-delete`** —— 桶里可能还有非本站资源(assets/ 等),
  110. * 本应删除的旧产物需人工确认,见 README「部署」一节。
  111. * OBS 兼容 S3 协议,AK/SK 由 obsutil 自身的配置(`obsutil config`)提供,不写在脚本里。
  112. */
  113. run('obsutil', ['sync', distDir, BUCKET, '-f', `-e=${OBS_EP}`]);
  114. run('obsutil', ['chattri', BUCKET, '-r', '-f', `-e=${OBS_EP}`, '-acl=public-read']);
  115. // ── 4. 刷新 CDN ────────────────────────────────────────────────────────────
  116. console.log('\n=== [4/5] 刷新 CDN ===');
  117. const profile = process.env.HCLOUD_PROFILE || 'default';
  118. const refreshArgs = [
  119. 'CDN',
  120. 'CreateRefreshTasks/v2',
  121. `--cli-region=${CDN_REGION}`,
  122. `--refresh_task.urls.1=${CDN_BASE}/`,
  123. `--refresh_task.urls.2=${CDN_BASE}/index.html`,
  124. `--cli-profile=${profile}`,
  125. ];
  126. // KooCLI 首次运行会交互式询问《隐私政策声明》,无人值守时会卡死并报 USE_ERROR
  127. run('hcloud', refreshArgs, { input: 'y\ny\ny\n' });
  128. // ── 5. 探活 ────────────────────────────────────────────────────────────────
  129. console.log('\n=== [5/5] 线上探活 ===');
  130. if (dryRun) {
  131. console.log(' (dry-run,跳过)');
  132. } else {
  133. /*
  134. * 每个 URL 轮询至多 3 分钟(CDN 刷新实际有 1-5 分钟延迟),
  135. * 命中 200 / 内容是本次构建时才判通过 —— 只发请求不看结果的「探活」等于没探。
  136. */
  137. const indexHtmlContent = readFileSync(indexHtml, 'utf8');
  138. const title = indexHtmlContent.match(/<title>([^<]*)<\/title>/)?.[1] ?? '';
  139. let allOk = true;
  140. for (const path of ['/', '/index.html']) {
  141. let ok = false;
  142. for (let i = 0; i < 18 && !ok; i++) {
  143. const { status } = await probe(`${CDN_BASE}${path}`);
  144. ok = status === 200;
  145. if (!ok) await new Promise((r) => setTimeout(r, 10_000));
  146. }
  147. if (ok) console.log(` ✓ ${path} → 200`);
  148. else {
  149. allOk = false;
  150. console.log(` ❌ ${path} 轮询 3 分钟仍未返回 200,请手动确认 CDN 状态`);
  151. }
  152. }
  153. if (title) {
  154. const { body } = await probe(`${CDN_BASE}/`);
  155. if (body.includes(title)) console.log(` ✓ 线上标题为本次构建:${title}`);
  156. else {
  157. allOk = false;
  158. console.log(` ⚠ 线上标题非本次构建(期望「${title}」),CDN 可能尚未刷新完`);
  159. }
  160. }
  161. /*
  162. * SPA 深链:OBS 静态网站托管用 ErrorDocument=index.html 回落 ——
  163. * **状态码仍是 404**(OBS/S3 的标准行为),但响应体是 index.html,浏览器据此正常启动。
  164. * 故判据是「响应体含本次构建的 <title>」,而不是状态码。
  165. * 若将来换到 CDN 回源改写(状态码 200),这条断言同样成立。
  166. */
  167. const deep = await probe(`${CDN_BASE}/desktop/chat`);
  168. if (title && deep.body.includes(title)) {
  169. console.log(' ✓ SPA 深链 /desktop/chat 回落到 index.html');
  170. } else {
  171. allOk = false;
  172. console.log(' ❌ SPA 深链 /desktop/chat 未回落(需在 OBS 桶「静态网站托管」把错误文档设为 index.html)');
  173. }
  174. if (!allOk) {
  175. console.error('\n❌ 部署完成但线上校验未全部通过,见上方 ❌ / ⚠ 项');
  176. process.exit(1);
  177. }
  178. }
  179. console.log(`\n✅ 部署完成 → ${CDN_BASE}\n`);