Ver Fonte

♻️ refactor(server): 重构服务器代码结构与配置

- 重命名server2.js为server.js并更新package.json中的dev脚本
- 优化服务器初始化流程,合并重复的日志输出
- 重构请求处理中间件,统一API路由和SSR渲染逻辑
- 移除冗余空行和注释,优化代码格式
- 改进服务器关闭流程,增加明确的步骤注释

🔥 feat(server): 增强服务器功能与稳定性

- 实现模板处理函数分离,区分开发/生产环境逻辑
- 添加SSR渲染超时控制机制,防止长时间无响应
- 优化错误处理流程,提供更详细的错误日志
- 改进Vite开发服务器集成方式,提升HMR稳定性
- 实现统一的请求处理中间件,合并API和SSR逻辑

🗑️ chore(server): 清理冗余文件与代码

- 删除过时的server2.js文件
- 移除生产环境的API路由预加载代码
- 删除重复的动态API路由中间件
- 清理不必要的变量声明和调试日志
- 优化import语句排序,提高代码可读性
yourname há 6 meses atrás
pai
commit
073bac6b82
3 ficheiros alterados com 160 adições e 577 exclusões
  1. 1 1
      package.json
  2. 159 162
      server.js
  3. 0 414
      server2.js

+ 1 - 1
package.json

@@ -4,7 +4,7 @@
   "version": "0.0.0",
   "type": "module",
   "scripts": {
-    "dev": "PORT=8080 node server2",
+    "dev": "PORT=8080 node server",
     "dev:stock": "PORT=8080 cross-env DEBUG=backend:* node server",
     "build": "npm run build:client && npm run build:server && npm run build:api",
     "build:client": "vite build --outDir dist/client --manifest",

+ 159 - 162
server.js

@@ -13,9 +13,8 @@ import { createAdaptorServer } from '@hono/node-server'
 // 新增:导入 Socket.IO
 import { Server } from 'socket.io';
 
-
 // 创建 Hono 应用
-const app = new Hono();// API路由
+const app = new Hono();
 
 // 全局使用 Hono 日志中间件(记录所有请求)
 app.use('*', logger());
@@ -40,17 +39,17 @@ console.log(`端口: ${port}`);
 console.log(`基础路径: ${base}`);
 console.log('========================================');
 
-// 解析基础路径为 URL 对象,方便后续处理
+// 解析基础路径为 URL 对象
 const baseUrl = new URL(base, `http://localhost:${port}`);
 console.log(`基础URL解析完成: ${baseUrl.href}`);
 
-// 创建服务器实例  
+// 创建服务器实例
 console.log('正在创建服务器实例...');
-const parentServer = createAdaptorServer({  
-  fetch: app.fetch,  
-  createServer: createNodeServer,  
-  port: port,  
-})  
+const parentServer = createAdaptorServer({
+  fetch: app.fetch,
+  createServer: createNodeServer,
+  port: port,
+})
 console.log('服务器实例创建成功');
 
 // 新增:初始化 Socket.IO 服务器
@@ -86,14 +85,12 @@ let vite;
 if (!isProduction) {
   console.log('开发环境: 初始化 Vite 开发服务器...');
   const { createServer } = await import('vite');
-  
-  
   vite = await createServer({
-    server: {
+    server: { 
       middlewareMode: {
         server: parentServer
       },
-      hmr: {
+      hmr: {  
         port: 8081,
         clientPort: 443,
         path: 'vite-hmr'
@@ -111,18 +108,17 @@ if (!isProduction) {
   console.log('Vite 开发服务器初始化完成');
 }
 
-// 加载 API 路由
-if (!isProduction) {
-  console.log('开发环境: 从 Vite 加载 API 路由...');
-  const apiModule = await vite.ssrLoadModule('./src/server/api.ts');
-  app.route('/', apiModule.default);
-  console.log('API 路由加载完成');
-}else{
-  console.log('生产环境: 加载编译后的 API 路由...');
-  const api = (await import('./dist/api/api.js')).default
-  app.route('/', api);
-  console.log('API 路由加载完成');
-}
+
+// 开发环境模板处理函数 - 仅处理模板转换
+const processDevTemplate = async (template) => {
+  if (!isProduction && vite) {
+    console.log('开发环境: 处理模板...');
+    const processedTemplate = await vite.transformIndexHtml('/', template);
+    console.log('开发环境模板处理完成');
+    return processedTemplate;
+  }
+  return template;
+};
 
 // 新增:加载 Socket.IO 中间件和路由
 if (!isProduction) {
@@ -167,156 +163,65 @@ if (!isProduction) {
   }
 }
 
-// 请求处理中间件 - 通用逻辑
-app.use(async (c, next) => {
+// 生产环境模板处理函数 - 仅处理资源路径替换
+const processProdTemplate = async (template) => {
+  console.log('生产环境: 处理模板资源路径...');
   try {
-    // 使用 c.env 获取原生请求响应对象
-    const req = c.env.incoming;
-    const res = c.env.outgoing;
-    const url = new URL(req.url, `http://${req.headers.host}`);
-    const path = url.pathname;
-
-    // 检查是否匹配基础路径
-    if (!path.startsWith(baseUrl.pathname)) {
-      return c.text('未找到', 404);
+    // 读取 manifest
+    const manifestPath = new URL('./dist/client/.vite/manifest.json', import.meta.url);
+    const manifestContent = await fs.readFile(manifestPath, 'utf-8');
+    const manifest = JSON.parse(manifestContent);
+    console.log('生产环境: 成功读取 manifest.json');
+
+    // 获取 src/client/index.tsx 对应的资源信息
+    const indexManifest = manifest['src/client/index.tsx'];
+    if (!indexManifest) {
+      throw new Error('manifest 中未找到 src/client/index.tsx 入口配置');
     }
 
-    // 开发环境:使用 Vite 中间件
-    if (!isProduction && vite) {
-      // 使用 Vite 中间件处理请求
-      const handled = await new Promise((resolve) => {
-        vite.middlewares(req, res, () => resolve(false));
-      });
-      
-      // 如果 Vite 中间件已经处理了请求,直接返回
-      if (handled) {
-        return c.body;
-      }
-    } 
-    // 生产环境:使用 compression 和 sirv 中间件
-    else if (isProduction) {
-      // 先尝试 compression 中间件
-      const compressed = await new Promise((resolve) => {
-        compressionMiddleware(req, res, () => resolve(false));
-      });
-      
-      if (compressed) {
-        return c.body;
-      }
-      
-      // 再尝试 sirv 中间件处理静态文件
-      const served = await new Promise((resolve) => {
-        sirvMiddleware(req, res, () => resolve(false));
-      });
-      
-      if (served) {
-        return c.body;
-      }
+    // 获取 src/style.css 对应的资源信息
+    const styleManifest = manifest['src/style.css'];
+    if (!styleManifest) {
+      throw new Error('manifest 中未找到 src/style.css 入口配置');
     }
 
-    await next()
-  } catch (e) {
-    if (!isProduction && vite) {
-      vite.ssrFixStacktrace(e);
-    }
-    console.error('请求处理中间件错误:', e.stack);
-    return c.text('服务器内部错误', 500);
-  }
-});
+    const cssPath = new URL(styleManifest.file, baseUrl).pathname;
+    const cssLinks = `<link href="${cssPath}" rel="stylesheet" />`;
 
-// 请求处理中间件 - SSR 渲染逻辑
-app.use(async (c) => {
-  
-  try {
-    // 使用 c.env 获取原生请求响应对象
-    const req = c.env.incoming;
-    const res = c.env.outgoing;
-    const url = new URL(req.url, `http://${req.headers.host}`);
-    const path = url.pathname;
+    // 替换入口脚本
+    const jsEntryPath = new URL(indexManifest.file, baseUrl).pathname;
+    const entryScript = `<script type="module" src="${jsEntryPath}"></script>`;
 
-    // 检查是否匹配基础路径
-    if (!path.startsWith(baseUrl.pathname)) {
-      return c.text('未找到', 404);
-    }
+    // 执行替换
+    const processedTemplate = template
+      .replace(/<link href="\/src\/style.css" rel="stylesheet"\/>/, cssLinks)
+      .replace(/<script type="module" src="\/src\/client\/index.tsx"><\/script>/, entryScript);
 
-    // 处理基础路径
-    const normalizedUrl = path.replace(baseUrl.pathname, '/') || '/';
-    console.log(`处理请求: ${normalizedUrl}`);
+    console.log('生产环境模板处理完成');
+    return processedTemplate;
 
-    // 处理所有其他请求的 SSR 逻辑
-    /** @type {string} */
-    let template;
-    /** @type {import('./src/server/index.tsx').render} */
-    let render;
-    
-    if (!isProduction && vite) {
-      console.log('开发环境: 加载模板和渲染函数...');
-      // 开发环境:读取最新模板并转换
-      const module = (await vite.ssrLoadModule('/src/server/index.tsx'));
-      template = module.template;
-      template = await vite.transformIndexHtml(normalizedUrl, template);
-      render = module.render;
-      console.log('开发环境模板处理完成');
-    } else {
-      // 生产环境:使用缓存的模板
-      console.log('生产环境: 加载编译后的模板和渲染函数...');
-      const module = await import('./dist/server/index.js');
-      
-      // 读取 manifest.json 并处理模板
-      try {
-        // 读取 manifest
-        const manifestPath = new URL('./dist/client/.vite/manifest.json', import.meta.url);
-        const manifestContent = await fs.readFile(manifestPath, 'utf-8');
-        const manifest = JSON.parse(manifestContent);
-        console.log('生产环境: 成功读取 manifest.json');
-
-        // 获取 index.html 对应的资源信息
-        const indexManifest = manifest['index.html'];
-        if (!indexManifest) {
-          throw new Error('manifest 中未找到 index.html 入口配置');
-        }
-
-        template = module.template;
-
-        // 替换 CSS 链接
-        const cssLinks = indexManifest.css?.map(cssFile => {
-          // 结合基础路径生成完整 URL(处理 base 前缀)
-          const cssUrl = new URL(cssFile, baseUrl).pathname;
-          return `<link href="${cssUrl}" rel="stylesheet" />`;
-        }).join('\n') || ''; // 无 CSS 则清空
-
-        // 替换入口脚本
-        const jsEntryPath = new URL(indexManifest.file, baseUrl).pathname;
-        const entryScript = `<script type="module" src="${jsEntryPath}"></script>`;
-
-        // 执行替换
-        template = template
-          .replace(/<link href="\/src\/style.css" rel="stylesheet"\/>/, cssLinks)
-          .replace(/<script type="module" src="\/src\/client\/index.tsx"><\/script>/, entryScript);
-
-        console.log('生产环境模板处理完成');
-
-      } catch (err) {
-        console.error('生产环境模板处理失败:', err);
-        throw err; // 终止启动,避免使用错误模板
-      }
-
-      render = module.render;
-    }
+  } catch (err) {
+    console.error('生产环境模板处理失败:', err);
+    throw err;
+  }
+};
 
+// SSR 渲染中间件函数
+const createSsrHandler = (template, render, normalizedUrl) => {
+  return async (c) => {
     let didError = false;
     let abortController;
 
     // 创建一个可读流用于 SSR 渲染内容
     const [htmlStart, htmlEnd] = template.split(`<!--app-html-->`);
     const ssrStream = new Readable({ read: () => {} });
-    
+
     // 写入 HTML 头部
     ssrStream.push(htmlStart);
 
     // 设置响应头和状态码
     c.header('Content-Type', 'text/html');
-    
+
     // 处理渲染
     const { pipe, abort } = render(normalizedUrl, {
       onShellError() {
@@ -336,7 +241,7 @@ app.use(async (c) => {
         });
 
         pipe(transformStream);
-        
+
         // 当 transformStream 完成时,添加 HTML 尾部
         transformStream.on('finish', () => {
           ssrStream.push(htmlEnd);
@@ -364,15 +269,108 @@ app.use(async (c) => {
         clearTimeout(abortTimeout);
       }
     });
+  };
+};
+
+// 统一的请求处理中间件 - 合并 API 和 SSR 渲染逻辑
+app.use(async (c) => {
+  try {
+    // 使用 c.env 获取原生请求响应对象
+    const req = c.env.incoming;
+    const res = c.env.outgoing;
+    const url = new URL(req.url, `http://${req.headers.host}`);
+    const path = url.pathname;
+
+    // 检查是否匹配基础路径
+    if (!path.startsWith(baseUrl.pathname)) {
+      return c.text('未找到', 404);
+    }
+
+    // 处理基础路径
+    const normalizedUrl = path.replace(baseUrl.pathname, '/') || '/';
+    console.log(`处理请求: ${normalizedUrl}`);
+
+    // 开发环境:使用 Vite 中间件
+    if (!isProduction && vite) {
+      // 使用 Vite 中间件处理请求
+      const handled = await new Promise((resolve) => {
+        vite.middlewares(req, res, () => resolve(false));
+      });
+      
+      // 如果 Vite 中间件已经处理了请求,直接返回
+      if (handled) {
+        return c.body;
+      }
+
+
+      // 动态加载最新 API 模块
+      const apiModule = await vite.ssrLoadModule('./src/server/index.tsx');
+      
+      // 创建临时子应用并挂载路由
+      const apiApp = new Hono();
+      apiApp.route('/', apiModule.api);
+      
+      // 处理开发环境模板
+      const template = await processDevTemplate(apiModule.template);
+      apiApp.get('*', createSsrHandler(template, apiModule.render, normalizedUrl));
+
+      // 直接由子应用处理 API 请求
+      return apiApp.fetch(c.req.raw, {
+        ...c.env,
+        // 传递原始请求对象
+        incoming: c.env.incoming,
+        outgoing: c.env.outgoing
+      });
+    }
+    // 生产环境:使用 compression 和 sirv 中间件
+    else if (isProduction) {
+      // 先尝试 compression 中间件
+      const compressed = await new Promise((resolve) => {
+        compressionMiddleware(req, res, () => resolve(false));
+      });
+      
+      if (compressed) {
+        return c.body;
+      }
+      
+      // 再尝试 sirv 中间件处理静态文件
+      const served = await new Promise((resolve) => {
+        sirvMiddleware(req, res, () => resolve(false));
+      });
+      
+      if (served) {
+        return c.body;
+      }
+
+      // 生产环境:使用缓存的 API 路由
+      const { api, template: rawTemplate, render } = (await import('./dist/server/index.js'));
+      const apiApp = new Hono();
+      apiApp.route('/', api);
+
+      // 处理生产环境模板
+      const template = await processProdTemplate(rawTemplate);
+      apiApp.get('*', createSsrHandler(template, render, normalizedUrl));
+
+      return apiApp.fetch(c.req.raw, {
+        ...c.env,
+        incoming: c.env.incoming,
+        outgoing: c.env.outgoing
+      });
+    }
+
   } catch (e) {
     if (!isProduction && vite) {
       vite.ssrFixStacktrace(e);
+      console.error('请求处理错误:', e.stack);
+      return c.text(e.stack, 500);
     }
-    console.error('SSR 处理错误:', e.stack);
+    console.error('请求处理错误:', e.stack);
     return c.text('服务器内部错误', 500);
   }
 });
 
+// 移除生产环境的 API 路由预加载(已在统一中间件中处理)
+// 移除动态 API 路由中间件(已合并到统一中间件中)
 
 // 启动服务器
 console.log('准备启动服务器...');
@@ -389,8 +387,7 @@ parentServer.listen(port, () => {
 const shutdownServer = async () => {
   console.log('正在关闭服务器...');
   
-  
-  // 关闭 Vite 开发服务器(包括 HMR 服务)
+  // 1. 先关闭 Vite 开发服务器(包括 HMR 服务)
   if (!isProduction && vite) {
     console.log('正在关闭 Vite 开发服务器(包括 HMR 服务)...');
     try {
@@ -401,7 +398,7 @@ const shutdownServer = async () => {
     }
   }
   
-  // 关闭主服务器
+  // 2. 关闭主服务器
   parentServer.close((err) => {
     if (err) {
       console.error('关闭主服务器时出错:', err);
@@ -412,6 +409,6 @@ const shutdownServer = async () => {
   });
 };
 
-// 处理进程终止信号(包括 Ctrl+C)
-process.on('SIGINT', shutdownServer);  // 处理 Ctrl+C
-process.on('SIGTERM', shutdownServer); // 处理 kill 命令
+// 处理进程终止信号
+process.on('SIGINT', shutdownServer);
+process.on('SIGTERM', shutdownServer);

+ 0 - 414
server2.js

@@ -1,414 +0,0 @@
-import 'dotenv/config'
-import fs from 'node:fs/promises';
-import { URL } from 'node:url';
-import { Transform } from 'node:stream';
-import { Readable } from 'node:stream';
-import { pipeline } from 'node:stream/promises';
-import { Hono } from 'hono';
-import { cors } from 'hono/cors'
-import { logger } from 'hono/logger';
-import { createServer as createNodeServer } from 'node:http';
-import process from 'node:process';
-import { createAdaptorServer } from '@hono/node-server'
-// 新增:导入 Socket.IO
-import { Server } from 'socket.io';
-
-// 创建 Hono 应用
-const app = new Hono();
-
-// 全局使用 Hono 日志中间件(记录所有请求)
-app.use('*', logger());
-app.use('*', cors(
-  // {
-  //   origin: ['http://localhost:3000'],
-  //   allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
-  //   credentials: true
-  // }
-))
-
-// 常量定义
-const isProduction = process.env.NODE_ENV === 'production';
-const port = process.env.PORT || 8080;
-const base = process.env.BASE || '/';
-const ABORT_DELAY = 10000;
-
-console.log('========================================');
-console.log('开始初始化服务器...');
-console.log(`环境: ${isProduction ? '生产环境' : '开发环境'}`);
-console.log(`端口: ${port}`);
-console.log(`基础路径: ${base}`);
-console.log('========================================');
-
-// 解析基础路径为 URL 对象
-const baseUrl = new URL(base, `http://localhost:${port}`);
-console.log(`基础URL解析完成: ${baseUrl.href}`);
-
-// 创建服务器实例
-console.log('正在创建服务器实例...');
-const parentServer = createAdaptorServer({
-  fetch: app.fetch,
-  createServer: createNodeServer,
-  port: port,
-})
-console.log('服务器实例创建成功');
-
-// 新增:初始化 Socket.IO 服务器
-console.log('正在初始化 Socket.IO 服务器...');
-const io = new Server(parentServer, {
-  // // 配置 CORS,根据实际需求调整
-  // cors: {
-  //   origin: isProduction ? process.env.FRONTEND_URL || false : "http://localhost:8080",
-  //   methods: ["GET", "POST"],
-  //   credentials: true
-  // },
-  // // 路径配置,避免与其他路由冲突
-  // path: `${base}socket.io`
-});
-console.log('Socket.IO 服务器初始化完成');
-
-// 生产环境中间件
-let compressionMiddleware;
-let sirvMiddleware;
-if (isProduction) {
-  console.log('生产环境: 加载压缩和静态文件中间件...');
-  compressionMiddleware = (await import('compression')).default();
-  sirvMiddleware = (await import('sirv')).default('./dist/client', { 
-    extensions: [],
-    baseUrl: base 
-  });
-  console.log('生产环境中间件加载完成');
-}
-
-// Vite 开发服务器
-/** @type {import('vite').ViteDevServer | undefined} */
-let vite;
-if (!isProduction) {
-  console.log('开发环境: 初始化 Vite 开发服务器...');
-  const { createServer } = await import('vite');
-  vite = await createServer({
-    server: { 
-      middlewareMode: {
-        server: parentServer
-      },
-      hmr: {  
-        port: 8081,
-        clientPort: 443,
-        path: 'vite-hmr'
-      },
-      proxy: {
-        '/vite-hmr': {
-          target: 'ws://localhost:8081',
-          ws: true,
-        },
-      },
-    },
-    appType: 'custom',
-    base,
-  });
-  console.log('Vite 开发服务器初始化完成');
-}
-
-
-// 开发环境模板处理函数 - 仅处理模板转换
-const processDevTemplate = async (template) => {
-  if (!isProduction && vite) {
-    console.log('开发环境: 处理模板...');
-    const processedTemplate = await vite.transformIndexHtml('/', template);
-    console.log('开发环境模板处理完成');
-    return processedTemplate;
-  }
-  return template;
-};
-
-// 新增:加载 Socket.IO 中间件和路由
-if (!isProduction) {
-  console.log('开发环境: 从 Vite 加载 Socket.IO 路由和中间件...');
-  try {
-    const socketModule = await vite.ssrLoadModule('./src/server/socket.ts');
-    
-    // 应用认证中间件
-    if (socketModule.authMiddleware) {
-      console.log('应用 Socket.IO 认证中间件');
-      io.use(socketModule.authMiddleware);
-    }
-    
-    // 应用路由
-    if (socketModule.default) {
-      console.log('注册 Socket.IO 路由处理');
-      socketModule.default(io);
-    }
-    console.log('Socket.IO 路由和中间件加载完成');
-  } catch (err) {
-    console.error('开发环境加载 Socket.IO 模块失败:', err);
-  }
-} else {
-  console.log('生产环境: 加载编译后的 Socket.IO 路由和中间件...');
-  try {
-    const socket = (await import('./dist/socket/socket.js')).default;
-    
-    // 应用认证中间件
-    if (socket.authMiddleware) {
-      console.log('应用 Socket.IO 认证中间件');
-      io.use(socket.authMiddleware);
-    }
-    
-    // 应用路由
-    if (socket.default) {
-      console.log('注册 Socket.IO 路由处理');
-      socket.default(io);
-    }
-    console.log('Socket.IO 路由和中间件加载完成');
-  } catch (err) {
-    console.error('加载 Socket.IO 模块失败:', err);
-  }
-}
-
-// 生产环境模板处理函数 - 仅处理资源路径替换
-const processProdTemplate = async (template) => {
-  console.log('生产环境: 处理模板资源路径...');
-  try {
-    // 读取 manifest
-    const manifestPath = new URL('./dist/client/.vite/manifest.json', import.meta.url);
-    const manifestContent = await fs.readFile(manifestPath, 'utf-8');
-    const manifest = JSON.parse(manifestContent);
-    console.log('生产环境: 成功读取 manifest.json');
-
-    // 获取 src/client/index.tsx 对应的资源信息
-    const indexManifest = manifest['src/client/index.tsx'];
-    if (!indexManifest) {
-      throw new Error('manifest 中未找到 src/client/index.tsx 入口配置');
-    }
-
-    // 获取 src/style.css 对应的资源信息
-    const styleManifest = manifest['src/style.css'];
-    if (!styleManifest) {
-      throw new Error('manifest 中未找到 src/style.css 入口配置');
-    }
-
-    const cssPath = new URL(styleManifest.file, baseUrl).pathname;
-    const cssLinks = `<link href="${cssPath}" rel="stylesheet" />`;
-
-    // 替换入口脚本
-    const jsEntryPath = new URL(indexManifest.file, baseUrl).pathname;
-    const entryScript = `<script type="module" src="${jsEntryPath}"></script>`;
-
-    // 执行替换
-    const processedTemplate = template
-      .replace(/<link href="\/src\/style.css" rel="stylesheet"\/>/, cssLinks)
-      .replace(/<script type="module" src="\/src\/client\/index.tsx"><\/script>/, entryScript);
-
-    console.log('生产环境模板处理完成');
-    return processedTemplate;
-
-  } catch (err) {
-    console.error('生产环境模板处理失败:', err);
-    throw err;
-  }
-};
-
-// SSR 渲染中间件函数
-const createSsrHandler = (template, render, normalizedUrl) => {
-  return async (c) => {
-    let didError = false;
-    let abortController;
-
-    // 创建一个可读流用于 SSR 渲染内容
-    const [htmlStart, htmlEnd] = template.split(`<!--app-html-->`);
-    const ssrStream = new Readable({ read: () => {} });
-
-    // 写入 HTML 头部
-    ssrStream.push(htmlStart);
-
-    // 设置响应头和状态码
-    c.header('Content-Type', 'text/html');
-
-    // 处理渲染
-    const { pipe, abort } = render(normalizedUrl, {
-      onShellError() {
-        didError = true;
-        c.status(500);
-        ssrStream.push('<h1>服务器渲染出错</h1>');
-        ssrStream.push(null); // 结束流
-      },
-      onShellReady() {
-        console.log(`开始渲染页面: ${normalizedUrl}`);
-        // 将渲染结果通过管道传入 ssrStream
-        const transformStream = new Transform({
-          transform(chunk, encoding, callback) {
-            ssrStream.push(chunk, encoding);
-            callback();
-          }
-        });
-
-        pipe(transformStream);
-
-        // 当 transformStream 完成时,添加 HTML 尾部
-        transformStream.on('finish', () => {
-          ssrStream.push(htmlEnd);
-          ssrStream.push(null); // 结束流
-          console.log(`页面渲染完成: ${normalizedUrl}`);
-        });
-      },
-      onError(error) {
-        didError = true;
-        console.error('渲染过程出错:', error);
-      },
-    });
-
-    // 设置超时中止
-    abortController = new AbortController();
-    const abortTimeout = setTimeout(() => {
-      console.log(`渲染超时,终止请求: ${normalizedUrl}`);
-      abort();
-      abortController.abort();
-    }, ABORT_DELAY);
-
-    // 将流通过 Hono 响应返回
-    return c.body(ssrStream, {
-      onEnd: () => {
-        clearTimeout(abortTimeout);
-      }
-    });
-  };
-};
-
-// 统一的请求处理中间件 - 合并 API 和 SSR 渲染逻辑
-app.use(async (c) => {
-  try {
-    // 使用 c.env 获取原生请求响应对象
-    const req = c.env.incoming;
-    const res = c.env.outgoing;
-    const url = new URL(req.url, `http://${req.headers.host}`);
-    const path = url.pathname;
-
-    // 检查是否匹配基础路径
-    if (!path.startsWith(baseUrl.pathname)) {
-      return c.text('未找到', 404);
-    }
-
-    // 处理基础路径
-    const normalizedUrl = path.replace(baseUrl.pathname, '/') || '/';
-    console.log(`处理请求: ${normalizedUrl}`);
-
-    // 开发环境:使用 Vite 中间件
-    if (!isProduction && vite) {
-      // 使用 Vite 中间件处理请求
-      const handled = await new Promise((resolve) => {
-        vite.middlewares(req, res, () => resolve(false));
-      });
-      
-      // 如果 Vite 中间件已经处理了请求,直接返回
-      if (handled) {
-        return c.body;
-      }
-
-
-      // 动态加载最新 API 模块
-      const apiModule = await vite.ssrLoadModule('./src/server/index.tsx');
-      
-      // 创建临时子应用并挂载路由
-      const apiApp = new Hono();
-      apiApp.route('/', apiModule.api);
-      
-      // 处理开发环境模板
-      const template = await processDevTemplate(apiModule.template);
-      apiApp.get('*', createSsrHandler(template, apiModule.render, normalizedUrl));
-
-      // 直接由子应用处理 API 请求
-      return apiApp.fetch(c.req.raw, {
-        ...c.env,
-        // 传递原始请求对象
-        incoming: c.env.incoming,
-        outgoing: c.env.outgoing
-      });
-    }
-    // 生产环境:使用 compression 和 sirv 中间件
-    else if (isProduction) {
-      // 先尝试 compression 中间件
-      const compressed = await new Promise((resolve) => {
-        compressionMiddleware(req, res, () => resolve(false));
-      });
-      
-      if (compressed) {
-        return c.body;
-      }
-      
-      // 再尝试 sirv 中间件处理静态文件
-      const served = await new Promise((resolve) => {
-        sirvMiddleware(req, res, () => resolve(false));
-      });
-      
-      if (served) {
-        return c.body;
-      }
-
-      // 生产环境:使用缓存的 API 路由
-      const { api, template: rawTemplate, render } = (await import('./dist/server/index.js'));
-      const apiApp = new Hono();
-      apiApp.route('/', api);
-
-      // 处理生产环境模板
-      const template = await processProdTemplate(rawTemplate);
-      apiApp.get('*', createSsrHandler(template, render, normalizedUrl));
-
-      return apiApp.fetch(c.req.raw, {
-        ...c.env,
-        incoming: c.env.incoming,
-        outgoing: c.env.outgoing
-      });
-    }
-
-  } catch (e) {
-    if (!isProduction && vite) {
-      vite.ssrFixStacktrace(e);
-      console.error('请求处理错误:', e.stack);
-      return c.text(e.stack, 500);
-    }
-    console.error('请求处理错误:', e.stack);
-    return c.text('服务器内部错误', 500);
-  }
-});
-
-// 移除生产环境的 API 路由预加载(已在统一中间件中处理)
-// 移除动态 API 路由中间件(已合并到统一中间件中)
-
-// 启动服务器
-console.log('准备启动服务器...');
-parentServer.listen(port, () => {  
-  console.log('========================================');
-  console.log(`服务器已成功启动!`);
-  console.log(`访问地址: http://localhost:${port}`);
-  console.log(`Socket.IO 路径: ${base}socket.io`);
-  console.log(`环境: ${isProduction ? '生产环境' : '开发环境'}`);
-  console.log('========================================');
-})
-
-// 统一的服务器关闭处理函数
-const shutdownServer = async () => {
-  console.log('正在关闭服务器...');
-  
-  // 1. 先关闭 Vite 开发服务器(包括 HMR 服务)
-  if (!isProduction && vite) {
-    console.log('正在关闭 Vite 开发服务器(包括 HMR 服务)...');
-    try {
-      await vite.close();
-      console.log('Vite 开发服务器已关闭');
-    } catch (err) {
-      console.error('关闭 Vite 服务器时出错:', err);
-    }
-  }
-  
-  // 2. 关闭主服务器
-  parentServer.close((err) => {
-    if (err) {
-      console.error('关闭主服务器时出错:', err);
-      process.exit(1);
-    }
-    console.log('主服务器已关闭');
-    process.exit(0);
-  });
-};
-
-// 处理进程终止信号
-process.on('SIGINT', shutdownServer);
-process.on('SIGTERM', shutdownServer);