static.ts
3.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import path from 'node:path';
import { existsSync, statSync } from 'node:fs';
import type { Route } from './context';
import { serveStaticFile, resolveIndexHtml } from '../http-utils';
/**
* 静态资源 & UI 托管 & 就绪探针。
* 注意顺序:spa catch-all (`/*`) 必须放在最后,且仅对非 /api、无后缀的 GET 生效,
* 对 /api 路径返回 false 以放行给后续业务路由。
*/
export const staticRoutes: Route[] = [
// ---- 就绪探针(轻量、首屏即开)----
// 端口仅在引擎加载 + sqlite 初始化全部完成后才 listen(),因此本端点
// 一旦返回 200,即可认定后端已完全就绪、可接收 /api/generate。前端用它
// 在「重启后端」的 boot 窗口期内门控「开始生成」按钮,避免点进未就绪的端口。
{
method: 'GET',
path: '/api/health',
handle: ({ res }) => {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ ok: true, uptime: Math.round(process.uptime()) }));
},
},
// ---- 根路径 ----
// 开发模式(COD_SERVE_WEB=0)下后端不托管 UI,跳转到前端 dev server;
// 否则返回 index.html(优先 Phase 2 构建产物)。
{
method: 'GET',
path: '/',
handle: ({ ctx, res }) => {
if (!ctx.SERVE_WEB) {
const webPort = process.env.COD_WEB_PORT || '5173';
res.writeHead(302, { Location: `http://localhost:${webPort}/` });
res.end();
return;
}
const idx = resolveIndexHtml();
if (existsSync(idx)) {
serveStaticFile(res, idx);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('UI not found.');
}
},
},
// ---- 托管已构建的前端静态资源(apps/web/dist)----
{
method: 'GET',
path: '/assets/*',
handle: ({ ctx, res, params }) => {
if (!ctx.SERVE_WEB || !ctx.WEB_DIST) return false;
// 还原原始子路径:url.pathname 为 "/assets/...",拼接时需保留 assets 段
const fp = path.join(ctx.WEB_DIST, 'assets', params.splat ?? '');
if (existsSync(fp) && statSync(fp).isFile()) {
serveStaticFile(res, fp);
return;
}
return false; // 文件不存在 → 继续,最终 404
},
},
// ---- SPA 根 /index.html ----
{
method: 'GET',
path: '/index.html',
handle: ({ ctx, res }) => {
if (!ctx.SERVE_WEB) return false;
const idx = resolveIndexHtml();
if (existsSync(idx)) {
serveStaticFile(res, idx);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('UI not found.');
}
},
},
// ---- SPA fallback(客户端路由)----
// 非 /api、无文件后缀的 GET 一律回 index.html;其余返回 false 放行。
{
method: 'GET',
path: '/*',
handle: ({ ctx, res, url }) => {
if (!ctx.SERVE_WEB) return false;
if (url.pathname.startsWith('/api')) return false;
if (path.extname(url.pathname)) return false;
const idx = resolveIndexHtml();
if (existsSync(idx)) {
serveStaticFile(res, idx);
return;
}
return false;
},
},
];