2
0

server.js 11 KB

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