server.js 13 KB

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