deploy.mjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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 与**华为云 KooCLI**(注意:PATH 里的 `hcloud` 可能是 Hetzner 的同名 CLI,
  12. * 直接用 `HCLOUD_BIN` 指定完整路径);AK/SK 已内置在本脚本顶部,无需提前 configure
  13. * (`obsutil` 自己的 `~/.obsutilconfig` 仍需配好,用于 OBS 上传)
  14. * ② 构建配置 `npm run build` 可用(production)
  15. *
  16. * 🔴 与旧 deploy.ps1 的差异:
  17. * - 项目名从 `nova-aigc` 改为 `fmode-app-v2`,产物路径改为 `dist/fmode-app-v2/browser`
  18. * - 异常时不静默继续:任何一步失败即 `process.exit(1)`
  19. * - 增加构建产物自检(防 demo/mock 包误发线上)
  20. */
  21. import { execFileSync } from 'node:child_process';
  22. import { existsSync, readFileSync, readdirSync } from 'node:fs';
  23. import { dirname, join, resolve } from 'node:path';
  24. import { fileURLToPath } from 'node:url';
  25. const here = dirname(fileURLToPath(import.meta.url));
  26. const projectRoot = resolve(here, '..');
  27. const distDir = join(projectRoot, 'dist/fmode-app-v2/browser');
  28. const BUCKET = 'obs://www-ai.fmode.cn';
  29. const CDN_BASE = 'https://ai.fmode.cn';
  30. const OBS_EP = 'obs.cn-south-1.myhuaweicloud.com';
  31. const CDN_REGION = 'cn-north-1';
  32. /*
  33. * 华为云 AK/SK(2026-11-14)。
  34. *
  35. * 按 CLAUDE.md 黄金规则 9 集中存放于此(用户已裁决「Token 与密钥可明文存放」)。
  36. * 来源:`deploy.ps1`(华为云控制台创建的那一对,20 位 AK)。
  37. *
  38. * ⚠️ **不要**从 `~/.obsutilconfig` 取:那里是 OBS 的 43 位 AK,
  39. * 与本对不是同一套;KooCLI 的 `cli-access-key` 长度限制 20 位,取了会直接报错。
  40. */
  41. const HW_AK = process.env.HW_AK || '2BFF7JWXAIJ0UGNJ0OSB';
  42. const HW_SK = process.env.HW_SK || 'NaPCiJCGmD3nklCzX65s8mSK1Py13ueyhgepa0s1';
  43. const args = new Set(process.argv.slice(2));
  44. const skipBuild = args.has('--skip-build');
  45. const dryRun = args.has('--dry-run');
  46. /**
  47. * 执行命令并回显。
  48. *
  49. * 🔴 Windows 上必须对 `.cmd`/`.bat`(如 `npm`、`npx`)走 shell(2026-11-18 修复)。
  50. *
  51. * `execFileSync('npm', ...)` 在 Windows 上抛 **ENOENT** —— 因为 `npm` 实际是
  52. * `npm.cmd`,而 `execFileSync` 不经过 shell,不做 PATHEXT 扩展。
  53. * 以前没暴露是因为当时 deploy 的调用方不同;改用 pnpm + 新环境后就必然失败:
  54. *
  55. * $ npm run build
  56. * ❌ 命令失败:npm run build
  57. * [ELIFECYCLE] Command failed with exit code 1.
  58. *
  59. * 而单独在终端跑 `npm run build` 却完全正常 —— 差别就在这里。
  60. *
  61. * 处理:命令名以 .cmd/.bat 结尾时(或本身就是 `npm`/`npx`)用 `shell: true`,
  62. * 其余(obsutil / hcloud 等原生 exe)保持原样,避免多一层 shell 转义。
  63. */
  64. function needsShell(cmd) {
  65. if (process.platform !== 'win32') return false;
  66. return /\.(cmd|bat)$/i.test(cmd) || cmd === 'npm' || cmd === 'npx';
  67. }
  68. function run(cmd, argv, opts = {}) {
  69. const printable = `${cmd} ${argv.join(' ')}`;
  70. console.log(`\n$ ${printable}`);
  71. if (dryRun) return '';
  72. const useShell = needsShell(cmd);
  73. try {
  74. return execFileSync(cmd, argv, {
  75. cwd: projectRoot,
  76. stdio: 'inherit',
  77. ...(useShell ? { shell: true } : {}),
  78. ...opts,
  79. });
  80. } catch (e) {
  81. console.error(`\n❌ 命令失败:${printable}`);
  82. process.exit(1);
  83. }
  84. }
  85. /**
  86. * 探活用 Node 原生 fetch,不依赖 curl。
  87. * Windows 上的 curl 是原生程序,`-o /dev/null` 会被当成文件路径写盘,不能拿来判状态码。
  88. */
  89. async function probe(url, timeoutMs = 30_000) {
  90. const ac = new AbortController();
  91. const timer = setTimeout(() => ac.abort(), timeoutMs);
  92. try {
  93. const res = await fetch(url, { signal: ac.signal, redirect: 'follow' });
  94. return { status: res.status, body: await res.text() };
  95. } catch {
  96. return { status: 0, body: '' };
  97. } finally {
  98. clearTimeout(timer);
  99. }
  100. }
  101. // ── 1. 构建 ────────────────────────────────────────────────────────────────
  102. if (!skipBuild) {
  103. console.log('\n=== [1/5] 构建 production ===');
  104. run('npm', ['run', 'build']);
  105. } else {
  106. console.log('\n=== [1/5] 跳过构建(--skip-build)===');
  107. }
  108. // ── 2. 产物自检 ────────────────────────────────────────────────────────────
  109. console.log('\n=== [2/5] 构建产物自检 ===');
  110. if (!existsSync(distDir)) {
  111. console.error(`❌ 产物目录不存在:${distDir}`);
  112. process.exit(1);
  113. }
  114. const files = readdirSync(distDir);
  115. const indexHtml = join(distDir, 'index.html');
  116. if (!files.includes('index.html')) {
  117. console.error('❌ 缺少 index.html');
  118. process.exit(1);
  119. }
  120. const html = readFileSync(indexHtml, 'utf8');
  121. if (!/app-root/.test(html)) {
  122. console.error('❌ index.html 不含 <app-root>,产物异常');
  123. process.exit(1);
  124. }
  125. // 主包与依赖 chunk 中若含演示数据开关且为 true,说明误发了 mock 包
  126. const jsFiles = files.filter((f) => f.endsWith('.js'));
  127. let sawMockSwitch = false;
  128. for (const f of jsFiles) {
  129. const src = readFileSync(join(distDir, f), 'utf8');
  130. const m = src.match(/useMockData\s*:\s*!?[01]/);
  131. if (!m) continue;
  132. sawMockSwitch = true;
  133. if (/!\s*0/.test(m[0])) {
  134. console.error(`❌ 检测到演示数据包(${f} 中 useMockData: true),拒绝部署到线上`);
  135. console.error(' 线上请用 `npm run build`;演示包请用 `npm run build:mock` 走本地 mock 服务');
  136. process.exit(1);
  137. }
  138. }
  139. if (sawMockSwitch) {
  140. console.log(' ✓ 数据源开关 = 真实(useMockData: false)');
  141. } else {
  142. console.warn(' ⚠ 未在产物中找到 useMockData 开关(可能已被 tree-shake),跳过校验');
  143. }
  144. console.log(` ✓ index.html + ${files.length} 个文件`);
  145. // ── 3. 上传 OBS ────────────────────────────────────────────────────────────
  146. console.log('\n=== [3/5] 同步到 OBS ===');
  147. /*
  148. * 先 sync 覆盖、再清多余文件:不用先清空桶,避免「清空后上传失败」导致站点空窗。
  149. * 🔴 `obsutil sync` **没有 `-f` 参数**(2026-11-14 踩坑:`Error: flag provided but not
  150. * defined: -f`)。同步默认不询问覆盖,需要时用 `-u`(增量上传已存在文件)。
  151. * **不传 `-delete`** —— 桶里可能还有非本站资源(assets/ 等),
  152. * 本应删除的旧产物需人工确认,见 README「部署」一节。
  153. * OBS 兼容 S3 协议,AK/SK 由 obsutil 自身的配置(`obsutil config`)提供,不写在脚本里。
  154. */
  155. run('obsutil', ['sync', distDir, BUCKET, `-e=${OBS_EP}`]);
  156. run('obsutil', ['chattri', BUCKET, '-r', '-f', `-e=${OBS_EP}`, '-acl=public-read']);
  157. /*
  158. * 🔴 index.html 必须显式禁缓存(2026-11-24 踩坑):
  159. * sync 不带 Cache-Control,浏览器可能启发式缓存旧 index.html →
  160. * 引用已被覆盖删除的旧 hash chunk(404)→ 用户一直跑旧版应用。
  161. * sync 不支持 -meta,需单独 cp 覆盖写元数据。
  162. * ⚠️ cp 会把对象 ACL 重置为**私有**(实测整站 403),必须紧跟着补 public-read。
  163. */
  164. run('obsutil', [
  165. 'cp', join(distDir, 'index.html'), `${BUCKET}/index.html`,
  166. '-meta=Cache-Control:no-cache', `-e=${OBS_EP}`,
  167. ]);
  168. run('obsutil', ['chattri', `${BUCKET}/index.html`, '-acl=public-read', `-e=${OBS_EP}`]);
  169. // ── 4. 刷新 CDN ────────────────────────────────────────────────────────────
  170. console.log('\n=== [4/5] 刷新 CDN ===');
  171. /*
  172. * 🔴 必须用**华为云 KooCLI**的完整路径(2026-11-14 踩坑)。
  173. *
  174. * PATH 里的 `hcloud` 是 **Hetzner Cloud CLI**(`hcloud 1.51.0`),与华为云
  175. * KooCLI 同名不同物。直接调 PATH 会报 `unknown flag: --cli-region`,
  176. * 而这时候 OBS 上传已经成功了 —— 只是 CDN 没刷,用户拿到的还是旧缓存。
  177. *
  178. * 可用 `HCLOUD_BIN` 环境变量覆盖。
  179. *
  180. * 🔴 2026-11-18:原硬编码路径 `E:\coding-environment\huaweicloud-koocli\hcloud.exe`
  181. * 在换机/换环境后不存在,导致第 4 步必然失败(OBS 已上传成功,但 CDN 没刷)。
  182. * 现改为「环境变量 → 常见安装位置 → PATH」依次探测,找不到才报错。
  183. *
  184. * 注意:PATH 里的 `hcloud` **可能是 Hetzner Cloud CLI**(同名不同物),
  185. * 所以探测到 PATH 里的可执行文件后先跑 `version` 确认是华为云 KooCLI。
  186. */
  187. function resolveHcloud() {
  188. const candidates = [
  189. process.env.HCLOUD_BIN,
  190. 'E:\\coding-environment\\huaweicloud-koocli\\hcloud.exe',
  191. `${process.env.LOCALAPPDATA}\\huaweicloud\\hcloud.exe`,
  192. `${process.env.USERPROFILE}\\tools\\hcloud\\hcloud.exe`,
  193. '/usr/local/bin/hcloud',
  194. 'hcloud',
  195. ].filter(Boolean);
  196. for (const bin of candidates) {
  197. try {
  198. const out = execFileSync(bin, ['version'], { encoding: 'utf8', timeout: 15_000 });
  199. // 华为云 KooCLI 输出含 "KooCLI";Hetzner 的是 "hcloud version x.y.z"
  200. if (/KooCLI/i.test(out)) return bin;
  201. } catch {
  202. /* 探测失败就试下一个 */
  203. }
  204. }
  205. return null;
  206. }
  207. const HCLOUD_BIN = resolveHcloud();
  208. /*
  209. * 🔴 必须同时刷新「固定文件名的资源」(2026-11-13 实测踩坑)。
  210. *
  211. * 带 hash 的 chunk(main-XXXX.js)换 hash 就等于换 URL,天然绕过 CDN 缓存。
  212. * 但下面这些是**固定文件名**,内容变了 URL 却没变 →
  213. * CDN 会一直吐旧版本,用户拿到的还是老代码:
  214. *
  215. * · pdf.worker.js —— pdfjs 升级/降级时最容易中招
  216. * (实测:换了 pdfjs 4.10 后,线上仍是 6.4 的旧 worker,
  217. * 真机 PDF 预览一直报 getOrInsertComputed 不是函数)
  218. *
  219. * 新增固定名资源时,记得同步加到这里。
  220. */
  221. const FIXED_NAME_ASSETS = ['/pdf.worker.js', '/favicon.ico'];
  222. const refreshUrls = [`${CDN_BASE}/`, `${CDN_BASE}/index.html`, ...FIXED_NAME_ASSETS.map((p) => `${CDN_BASE}${p}`)];
  223. const refreshArgs = [
  224. 'CDN',
  225. 'CreateRefreshTasks/v2',
  226. /*
  227. * 🔴 `--cli-region` 必须**内联在数组里**(2026-11-14)。
  228. * `run()` 用的是 `execFileSync`(无 shell),数组元素原样作为独立 argv 传入,
  229. * 所以这里不能写成 shell 风格的 `--cli-region=xxx` 之外的形态,
  230. * 也不能依赖 shell 的引号处理 —— 与 deploy.ps1 的写法保持等价。
  231. */
  232. `--cli-region=${CDN_REGION}`,
  233. `--refresh_task.type=file`,
  234. ...refreshUrls.map((u, i) => `--refresh_task.urls.${i + 1}=${u}`),
  235. /*
  236. * 🔴 直接传 AK/SK,**不依赖 `--cli-profile`**(2026-11-14)。
  237. *
  238. * KooCLI 会先尝试读凭证文件;没配 profile 时报 `[USE_ERROR]不存在配置项 default`,
  239. * 然后**静默跳过** —— CDN 没刷,但脚本继续探活,探活仍然打旧缓存后命中 200,
  240. * 看起来"部署成功",用户实际拿到的还是老代码(隐蔽失败,代价极大)。
  241. */
  242. `--cli-access-key=${HW_AK}`,
  243. `--cli-secret-key=${HW_SK}`,
  244. ];
  245. console.log(' 刷新 URL:');
  246. for (const u of refreshUrls) console.log(` ${u}`);
  247. if (!HCLOUD_BIN) {
  248. /*
  249. * 🔴 找不到华为云 KooCLI 时**不能静默跳过**(2026-11-18)。
  250. *
  251. * 跳过的话 OBS 已上传、CDN 却没刷,用户拿到的仍是旧文件,而且没有任何提示。
  252. * 这里明确报错并给出替代做法,让人知道接下来该做什么。
  253. */
  254. console.error('\n❌ 未找到华为云 KooCLI(hcloud)');
  255. console.error(' 文件已上传到 OBS,但 CDN 未刷新。请二选一:');
  256. console.error(' ① 安装 KooCLI 后重跑:pnpm run deploy --skip-build');
  257. console.error(' ② 或在华为云 CDN 控制台手动刷新以上 URL');
  258. console.error(' 也可用环境变量指定:HCLOUD_BIN=<hcloud 完整路径>');
  259. process.exit(1);
  260. }
  261. // KooCLI 首次运行会交互式询问《隐私政策声明》,无人值守时会卡死并报 USE_ERROR
  262. run(HCLOUD_BIN, refreshArgs, { input: 'y\ny\ny\n' });
  263. // ── 5. 探活 ────────────────────────────────────────────────────────────────
  264. console.log('\n=== [5/5] 线上探活 ===');
  265. if (dryRun) {
  266. console.log(' (dry-run,跳过)');
  267. } else {
  268. /*
  269. * 每个 URL 轮询至多 3 分钟(CDN 刷新实际有 1-5 分钟延迟),
  270. * 命中 200 / 内容是本次构建时才判通过 —— 只发请求不看结果的「探活」等于没探。
  271. */
  272. const indexHtmlContent = readFileSync(indexHtml, 'utf8');
  273. const title = indexHtmlContent.match(/<title>([^<]*)<\/title>/)?.[1] ?? '';
  274. let allOk = true;
  275. for (const path of ['/', '/index.html']) {
  276. let ok = false;
  277. for (let i = 0; i < 18 && !ok; i++) {
  278. const { status } = await probe(`${CDN_BASE}${path}`);
  279. ok = status === 200;
  280. if (!ok) await new Promise((r) => setTimeout(r, 10_000));
  281. }
  282. if (ok) console.log(` ✓ ${path} → 200`);
  283. else {
  284. allOk = false;
  285. console.log(` ❌ ${path} 轮询 3 分钟仍未返回 200,请手动确认 CDN 状态`);
  286. }
  287. }
  288. if (title) {
  289. const { body } = await probe(`${CDN_BASE}/`);
  290. if (body.includes(title)) console.log(` ✓ 线上标题为本次构建:${title}`);
  291. else {
  292. allOk = false;
  293. console.log(` ⚠ 线上标题非本次构建(期望「${title}」),CDN 可能尚未刷新完`);
  294. }
  295. }
  296. /*
  297. * SPA 深链:OBS 静态网站托管用 ErrorDocument=index.html 回落 ——
  298. * **状态码仍是 404**(OBS/S3 的标准行为),但响应体是 index.html,浏览器据此正常启动。
  299. * 故判据是「响应体含本次构建的 <title>」,而不是状态码。
  300. * 若将来换到 CDN 回源改写(状态码 200),这条断言同样成立。
  301. */
  302. const deep = await probe(`${CDN_BASE}/desktop/chat`);
  303. if (title && deep.body.includes(title)) {
  304. console.log(' ✓ SPA 深链 /desktop/chat 回落到 index.html');
  305. } else {
  306. allOk = false;
  307. console.log(' ❌ SPA 深链 /desktop/chat 未回落(需在 OBS 桶「静态网站托管」把错误文档设为 index.html)');
  308. }
  309. if (!allOk) {
  310. console.error('\n❌ 部署完成但线上校验未全部通过,见上方 ❌ / ⚠ 项');
  311. process.exit(1);
  312. }
  313. }
  314. console.log(`\n✅ 部署完成 → ${CDN_BASE}\n`);