context.ts 2.46 KB
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { JobStore } from '../jobStore';
import type { JobQueue } from '../queue';
import type { PreviewManager } from '../preview';
import type { ProjectRunner } from '../project-runner';
import type { resolveServerOptions, loadServerModelConfig } from '../config';
import type { SystemStatus, LogEntry } from '../types';

/**
 * 注入到所有路由 handler 的共享上下文。
 * 等价于原 server.ts 闭包内共享的依赖与辅助函数,集中到一个对象里传递,
 * 避免每个 handler 各自携带一长串参数。
 */
export interface ServerCtx {
    store: JobStore;
    queue: JobQueue;
    preview: PreviewManager;
    projectRunner: ProjectRunner;
    opts: ReturnType<typeof resolveServerOptions>;
    startTime: number;
    serverVersion: string;
    coderioVersion: string;
    admin: { restart: () => void; shutdown: () => void };
    model: ReturnType<typeof loadServerModelConfig>;
    sseClients: Set<ServerResponse>;
    recentLogs: LogEntry[];
    broadcast: (event: string, data: unknown) => void;
    sendJson: (res: ServerResponse, code: number, obj: unknown) => void;
    readJsonBody: <T = Record<string, unknown>>(req: IncomingMessage) => Promise<T>;
    /** 读取请求体并按 zod schema 校验;失败抛 `ValidationError`(全局映射为 400)。 */
    parseJsonBody: <S extends import('zod').ZodTypeAny>(
        req: IncomingMessage,
        schema: S,
    ) => Promise<import('zod').z.infer<S>>;
    computeStatus: () => SystemStatus;
    /** 是否由后端托管 UI(COD_SERVE_WEB !== '0')。 */
    SERVE_WEB: boolean;
    /** Phase 2 前端构建产物目录;仅 SERVE_WEB 时有效。 */
    WEB_DIST: string | undefined;
}

/** 一次请求 + 匹配出的路径参数,统一传给 handler。 */
export interface RouteContext {
    ctx: ServerCtx;
    req: IncomingMessage;
    res: ServerResponse;
    url: URL;
    params: Record<string, string>;
}

/**
 * 单条路由定义。
 * handle 返回值语义:返回 `false` 表示“未处理,继续尝试下一条路由”;
 * 返回 `true` / `undefined` / `void` 表示已处理(无论响应内容是什么)。
 * 这用于实现 SPA fallback 等“条件命中”的路由。
 */
export interface Route {
    method: string;
    /** 精确路径,或含 `:param`(单段)与 `*`(`/assets/*` 等通配)的模式。 */
    path: string;
    handle: (rc: RouteContext) => Promise<boolean | void> | boolean | void;
}