serve-dist.mjs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. /**
  2. * 本地静态开发服务器(用于跑**生产构建**做真实环境回归)
  3. *
  4. * ## 与 `npm start` 的分工
  5. *
  6. * | 命令 | 用途 |
  7. * |---|---|
  8. * | `npm start` | `ng serve` + `proxy.conf.js`,日常开发,热更新 |
  9. * | `npm run serve:dist` | 托管 `dist/` 里的构建产物,**接近线上**的运行形态 |
  10. * | `npm run dev:logged-in` | 同上 + 自动注入登录态 → 打开即已登录,可自动化 |
  11. *
  12. * ## 为什么要单独一个服务器
  13. *
  14. * `scripts/smoke-imhub.mjs` 里内联的静态服务只够冒烟用(无 SPA 回退以外的细节)。
  15. * 手工回归时需要一个**能长期开着**的服务器,并且要能在不改源文件的前提下注入
  16. * 登录态 —— 这就是本脚本的第二个职责(见 `scripts/dev-login.mjs`)。
  17. *
  18. * ## 用法
  19. *
  20. * ```bash
  21. * npm run build # 先构建
  22. * npm run serve:dist # http://127.0.0.1:4300/?mode=desktop
  23. * npm run dev:logged-in # 同上,且自动登录
  24. * PORT=4400 npm run serve:dist # 换端口
  25. * ```
  26. */
  27. import { createServer } from 'node:http';
  28. import { readFile, stat } from 'node:fs/promises';
  29. import { existsSync } from 'node:fs';
  30. import { join, extname, resolve, dirname } from 'node:path';
  31. import { fileURLToPath } from 'node:url';
  32. import { loadDevLogin, injectIntoHtml } from './dev-login.mjs';
  33. const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  34. const distDir = resolve(root, 'dist/fmode-app-v2/browser');
  35. const port = Number(process.env.PORT ?? 4300);
  36. const wantLogin = process.argv.includes('--login') || process.env.DEV_LOGIN === '1';
  37. const MIME = {
  38. '.html': 'text/html; charset=utf-8',
  39. '.js': 'text/javascript; charset=utf-8',
  40. '.mjs': 'text/javascript; charset=utf-8',
  41. '.css': 'text/css; charset=utf-8',
  42. '.json': 'application/json; charset=utf-8',
  43. '.svg': 'image/svg+xml',
  44. '.woff2': 'font/woff2',
  45. '.woff': 'font/woff',
  46. '.ttf': 'font/ttf',
  47. '.ico': 'image/x-icon',
  48. '.png': 'image/png',
  49. '.jpg': 'image/jpeg',
  50. '.webp': 'image/webp',
  51. '.map': 'application/json; charset=utf-8',
  52. };
  53. if (!existsSync(distDir)) {
  54. console.error(`❌ 未找到构建产物:${distDir}\n 先执行 npm run build`);
  55. process.exit(2);
  56. }
  57. let login = { enabled: false, reason: '未启用(加 --login 或 DEV_LOGIN=1 才注入)' };
  58. if (wantLogin) login = loadDevLogin();
  59. if (wantLogin && !login.enabled) {
  60. console.error(`❌ 开发态登录未生效:${login.reason}`);
  61. console.error(` 按 docs/05-operations/开发态登录.md 填好 .claude/dev-login.json 后重试。`);
  62. process.exit(2);
  63. }
  64. /** 只在内存里改 HTML,不碰磁盘上的源文件 */
  65. async function readIndex() {
  66. const html = await readFile(join(distDir, 'index.html'), 'utf8');
  67. return login.enabled ? injectIntoHtml(html, login.payload) : html;
  68. }
  69. /** 平台服务地址(与 app 的 `environment.endpoints.functionsBase` 同源) */
  70. const PLATFORM_ORIGIN = 'https://server.fmode.cn';
  71. /**
  72. * 判断是否要转发到平台。
  73. *
  74. * `/api-platform/api/...` → `https://server.fmode.cn/api/...`
  75. * `/api/...` → 原样转到 `https://server.fmode.cn/api/...`(兼容旧路径)
  76. *
  77. * @returns {string|null} 目标 URL;不是平台接口返回 null
  78. */
  79. function platformTarget(urlPath) {
  80. if (urlPath.startsWith('/api-platform/')) {
  81. return PLATFORM_ORIGIN + urlPath.slice('/api-platform'.length);
  82. }
  83. if (urlPath === '/api' || urlPath.startsWith('/api/')) {
  84. return PLATFORM_ORIGIN + urlPath;
  85. }
  86. return null;
  87. }
  88. /** 原样转发(保留请求方法、鉴权头、body),只确保带 Origin 以便上游走 CORS 分支 */
  89. async function proxyToPlatform(req, res, target) {
  90. const chunks = [];
  91. for await (const c of req) chunks.push(c);
  92. const body = Buffer.concat(chunks);
  93. const headers = { ...req.headers };
  94. delete headers.host;
  95. try {
  96. const upstream = await fetch(target, {
  97. method: req.method,
  98. headers,
  99. body: body.length ? body : undefined,
  100. redirect: 'manual',
  101. });
  102. const outHeaders = {};
  103. upstream.headers.forEach((v, k) => {
  104. // 同源请求用不到 CORS 头;上游若吐了两行 ACAO 反而会污染浏览器
  105. if (k.startsWith('access-control-')) return;
  106. outHeaders[k] = v;
  107. });
  108. res.writeHead(upstream.status, outHeaders);
  109. res.end(Buffer.from(await upstream.arrayBuffer()));
  110. } catch (e) {
  111. res.writeHead(502, { 'Content-Type': 'application/json' }).end(
  112. JSON.stringify({ code: 502, mess: `本地转发失败:${e.message}` }),
  113. );
  114. }
  115. }
  116. const server = createServer(async (req, res) => {
  117. try {
  118. const urlPath = decodeURIComponent((req.url ?? '/').split('?')[0]);
  119. /*
  120. * 平台接口转发(CORS 兼容层,2026-11-12)。
  121. *
  122. * 与 `proxy.conf.js` 同口径:`/api-platform/**` 与 `/api/**` 都转发到
  123. * `server.fmode.cn`,让浏览器看到的是**同源请求** —— 平台响应里偶尔出现的
  124. * 两行 `Access-Control-Allow-Origin` 就不会被浏览器拦掉。
  125. * 见 `src/app/core/api/platform-proxy.service.ts`。
  126. */
  127. const forward = platformTarget(urlPath);
  128. if (forward) {
  129. await proxyToPlatform(req, res, forward);
  130. return;
  131. }
  132. const file = join(distDir, urlPath);
  133. // 目录穿越防护:解析后必须仍在 dist 内
  134. if (!resolve(file).startsWith(distDir)) {
  135. res.writeHead(403).end('forbidden');
  136. return;
  137. }
  138. let onDisk = false;
  139. try {
  140. onDisk = (await stat(file)).isFile();
  141. } catch {
  142. onDisk = false;
  143. }
  144. if (onDisk && extname(file) !== '.html') {
  145. const body = await readFile(file);
  146. res.writeHead(200, {
  147. 'Content-Type': MIME[extname(file)] ?? 'application/octet-stream',
  148. // 本地调试时不缓存,避免改了构建产物还看到旧的
  149. 'Cache-Control': 'no-store',
  150. });
  151. res.end(body);
  152. return;
  153. }
  154. // SPA 回退:所有路由都返回 index.html
  155. res.writeHead(200, { 'Content-Type': MIME['.html'], 'Cache-Control': 'no-store' });
  156. res.end(await readIndex());
  157. } catch (e) {
  158. res.writeHead(500).end(`server error: ${e.message}`);
  159. }
  160. });
  161. server.listen(port, '127.0.0.1', () => {
  162. const base = `http://127.0.0.1:${port}`;
  163. console.log(`静态服务:${base}`);
  164. console.log(`产物目录:${distDir}`);
  165. console.log(
  166. login.enabled
  167. ? `🔓 开发态登录已启用(用户:${login.payload.me.name || login.payload.me.id})—— 打开即已登录`
  168. : `🔒 未注入登录态:${login.reason}`,
  169. );
  170. console.log(`\n 桌面端 ${base}/desktop/chat`);
  171. console.log(` 移动端 ${base}/mobile/messages\n`);
  172. });