static.ts 3.57 KB
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;
        },
    },
];