server.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. import fs from 'node:fs/promises';
  2. import { URL } from 'node:url';
  3. import { Transform } from 'node:stream';
  4. import { Readable } from 'node:stream';
  5. import { pipeline } from 'node:stream/promises';
  6. import { Hono } from 'hono';
  7. import { cors } from 'hono/cors'
  8. import { logger } from 'hono/logger';
  9. import { createServer as createNodeServer } from 'node:http';
  10. import process from 'node:process';
  11. import { createAdaptorServer } from '@hono/node-server'
  12. // 新增:导入 Socket.IO
  13. import { Server } from 'socket.io';
  14. // 创建 Hono 应用
  15. const app = new Hono();// API路由
  16. // 全局使用 Hono 日志中间件(记录所有请求)
  17. app.use('*', logger());
  18. app.use('*', cors(
  19. // {
  20. // origin: ['http://localhost:3000'],
  21. // allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  22. // credentials: true
  23. // }
  24. ))
  25. // 常量定义
  26. const isProduction = process.env.NODE_ENV === 'production';
  27. const port = process.env.PORT || 8080;
  28. const base = process.env.BASE || '/';
  29. const ABORT_DELAY = 10000;
  30. console.log('========================================');
  31. console.log('开始初始化服务器...');
  32. console.log(`环境: ${isProduction ? '生产环境' : '开发环境'}`);
  33. console.log(`端口: ${port}`);
  34. console.log(`基础路径: ${base}`);
  35. console.log('========================================');
  36. // 解析基础路径为 URL 对象,方便后续处理
  37. const baseUrl = new URL(base, `http://localhost:${port}`);
  38. console.log(`基础URL解析完成: ${baseUrl.href}`);
  39. // 先创建服务器实例
  40. console.log('正在创建服务器实例...');
  41. const parentServer = createAdaptorServer({
  42. fetch: app.fetch,
  43. createServer: createNodeServer,
  44. port: port,
  45. })
  46. console.log('服务器实例创建成功');
  47. // 新增:初始化 Socket.IO 服务器
  48. console.log('正在初始化 Socket.IO 服务器...');
  49. const io = new Server(parentServer, {
  50. // // 配置 CORS,根据实际需求调整
  51. // cors: {
  52. // origin: isProduction ? process.env.FRONTEND_URL || false : "http://localhost:8080",
  53. // methods: ["GET", "POST"],
  54. // credentials: true
  55. // },
  56. // // 路径配置,避免与其他路由冲突
  57. // path: `${base}socket.io`
  58. });
  59. console.log('Socket.IO 服务器初始化完成');
  60. // 生产环境中间件
  61. let compressionMiddleware;
  62. let sirvMiddleware;
  63. if (isProduction) {
  64. console.log('生产环境: 加载压缩和静态文件中间件...');
  65. compressionMiddleware = (await import('compression')).default();
  66. sirvMiddleware = (await import('sirv')).default('./dist/client', {
  67. extensions: [],
  68. baseUrl: base
  69. });
  70. console.log('生产环境中间件加载完成');
  71. }
  72. // Vite 开发服务器
  73. /** @type {import('vite').ViteDevServer | undefined} */
  74. let vite;
  75. if (!isProduction) {
  76. console.log('开发环境: 初始化 Vite 开发服务器...');
  77. const { createServer } = await import('vite');
  78. vite = await createServer({
  79. server: { middlewareMode: {
  80. server: parentServer
  81. },
  82. hmr: {
  83. port: 8081,
  84. clientPort: 443,
  85. path: 'vite-hmr'
  86. },
  87. proxy: {
  88. '/vite-hmr': {
  89. target: 'ws://localhost:8081',
  90. ws: true,
  91. },
  92. },
  93. },
  94. appType: 'custom',
  95. base,
  96. });
  97. console.log('Vite 开发服务器初始化完成');
  98. }
  99. // 加载 API 路由
  100. if (!isProduction) {
  101. console.log('开发环境: 从 Vite 加载 API 路由...');
  102. const apiModule = await vite.ssrLoadModule('./src/server/api.ts');
  103. app.route('/', apiModule.default);
  104. console.log('API 路由加载完成');
  105. }else{
  106. console.log('生产环境: 加载编译后的 API 路由...');
  107. const api = (await import('./dist/api/api.js')).default
  108. app.route('/', api);
  109. console.log('API 路由加载完成');
  110. }
  111. // 新增:加载 Socket.IO 中间件和路由
  112. if (!isProduction) {
  113. console.log('开发环境: 从 Vite 加载 Socket.IO 路由和中间件...');
  114. const socketModule = await vite.ssrLoadModule('./src/server/socket.ts');
  115. // 应用认证中间件
  116. if (socketModule.authMiddleware) {
  117. console.log('应用 Socket.IO 认证中间件');
  118. io.use(socketModule.authMiddleware);
  119. }
  120. // 应用路由
  121. if (socketModule.default) {
  122. console.log('注册 Socket.IO 路由处理');
  123. socketModule.default(io);
  124. }
  125. console.log('Socket.IO 路由和中间件加载完成');
  126. } else {
  127. console.log('生产环境: 加载编译后的 Socket.IO 路由和中间件...');
  128. try {
  129. const socket = (await import('./dist/socket/socket.js')).default;
  130. // 应用认证中间件
  131. if (socket.authMiddleware) {
  132. console.log('应用 Socket.IO 认证中间件');
  133. io.use(socket.authMiddleware);
  134. }
  135. // 应用路由
  136. if (socket.default) {
  137. console.log('注册 Socket.IO 路由处理');
  138. socket.default(io);
  139. }
  140. console.log('Socket.IO 路由和中间件加载完成');
  141. } catch (err) {
  142. console.error('加载 Socket.IO 模块失败:', err);
  143. }
  144. }
  145. // 请求处理中间件 - 通用逻辑
  146. app.use(async (c, next) => {
  147. try {
  148. // 使用 c.env 获取原生请求响应对象
  149. const req = c.env.incoming;
  150. const res = c.env.outgoing;
  151. const url = new URL(req.url, `http://${req.headers.host}`);
  152. const path = url.pathname;
  153. // 检查是否匹配基础路径
  154. if (!path.startsWith(baseUrl.pathname)) {
  155. return c.text('未找到', 404);
  156. }
  157. // 开发环境:使用 Vite 中间件
  158. if (!isProduction && vite) {
  159. // 使用 Vite 中间件处理请求
  160. const handled = await new Promise((resolve) => {
  161. vite.middlewares(req, res, () => resolve(false));
  162. });
  163. // 如果 Vite 中间件已经处理了请求,直接返回
  164. if (handled) {
  165. return c.body;
  166. }
  167. }
  168. // 生产环境:使用 compression 和 sirv 中间件
  169. else if (isProduction) {
  170. // 先尝试 compression 中间件
  171. const compressed = await new Promise((resolve) => {
  172. compressionMiddleware(req, res, () => resolve(false));
  173. });
  174. if (compressed) {
  175. return c.body;
  176. }
  177. // 再尝试 sirv 中间件处理静态文件
  178. const served = await new Promise((resolve) => {
  179. sirvMiddleware(req, res, () => resolve(false));
  180. });
  181. if (served) {
  182. return c.body;
  183. }
  184. }
  185. await next()
  186. } catch (e) {
  187. if (!isProduction && vite) {
  188. vite.ssrFixStacktrace(e);
  189. }
  190. console.error('请求处理中间件错误:', e.stack);
  191. return c.text('服务器内部错误', 500);
  192. }
  193. });
  194. // 请求处理中间件 - SSR 渲染逻辑
  195. app.use(async (c) => {
  196. try {
  197. // 使用 c.env 获取原生请求响应对象
  198. const req = c.env.incoming;
  199. const res = c.env.outgoing;
  200. const url = new URL(req.url, `http://${req.headers.host}`);
  201. const path = url.pathname;
  202. // 检查是否匹配基础路径
  203. if (!path.startsWith(baseUrl.pathname)) {
  204. return c.text('未找到', 404);
  205. }
  206. // 处理基础路径
  207. const normalizedUrl = path.replace(baseUrl.pathname, '/') || '/';
  208. console.log(`处理请求: ${normalizedUrl}`);
  209. // 处理所有其他请求的 SSR 逻辑
  210. /** @type {string} */
  211. let template;
  212. /** @type {import('./src/server/index.tsx').render} */
  213. let render;
  214. if (!isProduction && vite) {
  215. console.log('开发环境: 加载模板和渲染函数...');
  216. // 开发环境:读取最新模板并转换
  217. const module = (await vite.ssrLoadModule('/src/server/index.tsx'));
  218. template = module.template;
  219. template = await vite.transformIndexHtml(normalizedUrl, template);
  220. render = module.render;
  221. console.log('开发环境模板处理完成');
  222. } else {
  223. // 生产环境:使用缓存的模板
  224. console.log('生产环境: 加载编译后的模板和渲染函数...');
  225. const module = await import('./dist/server/index.js');
  226. // 读取 manifest.json 并处理模板
  227. try {
  228. // 读取 manifest
  229. const manifestPath = new URL('./dist/client/.vite/manifest.json', import.meta.url);
  230. const manifestContent = await fs.readFile(manifestPath, 'utf-8');
  231. const manifest = JSON.parse(manifestContent);
  232. console.log('生产环境: 成功读取 manifest.json');
  233. // 获取 index.html 对应的资源信息
  234. const indexManifest = manifest['index.html'];
  235. if (!indexManifest) {
  236. throw new Error('manifest 中未找到 index.html 入口配置');
  237. }
  238. template = module.template;
  239. // 替换 CSS 链接
  240. const cssLinks = indexManifest.css?.map(cssFile => {
  241. // 结合基础路径生成完整 URL(处理 base 前缀)
  242. const cssUrl = new URL(cssFile, baseUrl).pathname;
  243. return `<link href="${cssUrl}" rel="stylesheet" />`;
  244. }).join('\n') || ''; // 无 CSS 则清空
  245. // 替换入口脚本
  246. const jsEntryPath = new URL(indexManifest.file, baseUrl).pathname;
  247. const entryScript = `<script type="module" src="${jsEntryPath}"></script>`;
  248. // 执行替换
  249. template = template
  250. .replace(/<link href="\/src\/style.css" rel="stylesheet"\/>/, cssLinks)
  251. .replace(/<script type="module" src="\/src\/client\/index.tsx"><\/script>/, entryScript);
  252. console.log('生产环境模板处理完成');
  253. } catch (err) {
  254. console.error('生产环境模板处理失败:', err);
  255. throw err; // 终止启动,避免使用错误模板
  256. }
  257. render = module.render;
  258. }
  259. let didError = false;
  260. let abortController;
  261. // 创建一个可读流用于 SSR 渲染内容
  262. const [htmlStart, htmlEnd] = template.split(`<!--app-html-->`);
  263. const ssrStream = new Readable({ read: () => {} });
  264. // 写入 HTML 头部
  265. ssrStream.push(htmlStart);
  266. // 设置响应头和状态码
  267. c.header('Content-Type', 'text/html');
  268. // 处理渲染
  269. const { pipe, abort } = render(normalizedUrl, {
  270. onShellError() {
  271. didError = true;
  272. c.status(500);
  273. ssrStream.push('<h1>服务器渲染出错</h1>');
  274. ssrStream.push(null); // 结束流
  275. },
  276. onShellReady() {
  277. console.log(`开始渲染页面: ${normalizedUrl}`);
  278. // 将渲染结果通过管道传入 ssrStream
  279. const transformStream = new Transform({
  280. transform(chunk, encoding, callback) {
  281. ssrStream.push(chunk, encoding);
  282. callback();
  283. }
  284. });
  285. pipe(transformStream);
  286. // 当 transformStream 完成时,添加 HTML 尾部
  287. transformStream.on('finish', () => {
  288. ssrStream.push(htmlEnd);
  289. ssrStream.push(null); // 结束流
  290. console.log(`页面渲染完成: ${normalizedUrl}`);
  291. });
  292. },
  293. onError(error) {
  294. didError = true;
  295. console.error('渲染过程出错:', error);
  296. },
  297. });
  298. // 设置超时中止
  299. abortController = new AbortController();
  300. const abortTimeout = setTimeout(() => {
  301. console.log(`渲染超时,终止请求: ${normalizedUrl}`);
  302. abort();
  303. abortController.abort();
  304. }, ABORT_DELAY);
  305. // 将流通过 Hono 响应返回
  306. return c.body(ssrStream, {
  307. onEnd: () => {
  308. clearTimeout(abortTimeout);
  309. }
  310. });
  311. } catch (e) {
  312. if (!isProduction && vite) {
  313. vite.ssrFixStacktrace(e);
  314. }
  315. console.error('SSR 处理错误:', e.stack);
  316. return c.text('服务器内部错误', 500);
  317. }
  318. });
  319. // 启动服务器
  320. console.log('准备启动服务器...');
  321. parentServer.listen(port, () => {
  322. console.log('========================================');
  323. console.log(`服务器已成功启动!`);
  324. console.log(`访问地址: http://localhost:${port}`);
  325. console.log(`Socket.IO 路径: ${base}socket.io`);
  326. console.log(`环境: ${isProduction ? '生产环境' : '开发环境'}`);
  327. console.log('========================================');
  328. })
  329. // 统一的服务器关闭处理函数
  330. const shutdownServer = async () => {
  331. console.log('正在关闭服务器...');
  332. // 关闭 Vite 开发服务器(包括 HMR 服务)
  333. if (!isProduction && vite) {
  334. console.log('正在关闭 Vite 开发服务器(包括 HMR 服务)...');
  335. try {
  336. await vite.close();
  337. console.log('Vite 开发服务器已关闭');
  338. } catch (err) {
  339. console.error('关闭 Vite 服务器时出错:', err);
  340. }
  341. }
  342. // 关闭主服务器
  343. parentServer.close((err) => {
  344. if (err) {
  345. console.error('关闭主服务器时出错:', err);
  346. process.exit(1);
  347. }
  348. console.log('主服务器已关闭');
  349. process.exit(0);
  350. });
  351. };
  352. // 处理进程终止信号(包括 Ctrl+C)
  353. process.on('SIGINT', shutdownServer); // 处理 Ctrl+C
  354. process.on('SIGTERM', shutdownServer); // 处理 kill 命令