server.ts 10.6 KB
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { readFileSync, existsSync, statSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { subscribeLogs, parseFigmaUrl, type LogEntry } from 'coderio';
import type { JobStore } from './jobStore';
import type { JobQueue } from './queue';
import { PreviewManager } from './preview';
import { configView, loadServerModelConfig, resolveServerOptions } from './config';
import type { GenerateRequest, Job, ServerConfigView } from './types';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PUBLIC_INDEX = path.join(__dirname, '..', 'public', 'index.html');
// Phase 2 前端工程构建产物:apps/web/dist。存在时优先托管它(支持 SPA 路由)。
const WEB_DIST = path.join(__dirname, '..', '..', 'web', 'dist');

const MIME: Record<string, string> = {
    '.html': 'text/html; charset=utf-8',
    '.js': 'text/javascript; charset=utf-8',
    '.mjs': 'text/javascript; charset=utf-8',
    '.css': 'text/css; charset=utf-8',
    '.json': 'application/json; charset=utf-8',
    '.svg': 'image/svg+xml',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.gif': 'image/gif',
    '.ico': 'image/x-icon',
    '.woff': 'font/woff',
    '.woff2': 'font/woff2',
    '.ttf': 'font/ttf',
    '.map': 'application/json',
};

function serveStaticFile(res: ServerResponse, filePath: string): void {
    try {
        const data = readFileSync(filePath);
        const ext = path.extname(filePath).toLowerCase();
        res.writeHead(200, {
            'Content-Type': MIME[ext] ?? 'application/octet-stream',
            'Cache-Control': 'no-cache',
        });
        res.end(data);
    } catch {
        res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
        res.end('Not Found');
    }
}

function resolveIndexHtml(): string {
    if (WEB_DIST && existsSync(path.join(WEB_DIST, 'index.html'))) {
        return path.join(WEB_DIST, 'index.html');
    }
    return PUBLIC_INDEX;
}

export interface ServerDeps {
    store: JobStore;
    queue: JobQueue;
    preview: PreviewManager;
}

export interface AppHandle {
    server: ReturnType<typeof createServer>;
    /** Broadcast an SSE event to all connected clients. */
    broadcast: (event: string, data: unknown) => void;
}

export function createApp(deps: ServerDeps): AppHandle {
    const { store, queue, preview } = deps;
    const sseClients = new Set<ServerResponse>();
    const opts = resolveServerOptions();
    const model = loadServerModelConfig();

    const broadcast = (event: string, data: unknown): void => {
        const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
        for (const res of sseClients) {
            try {
                res.write(payload);
            } catch {
                sseClients.delete(res);
            }
        }
    };

    // Forward engine logs to every connected SSE client.
    subscribeLogs((entry: LogEntry) => broadcast('log', entry));

    const sendJson = (res: ServerResponse, code: number, obj: unknown): void => {
        res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' });
        res.end(JSON.stringify(obj));
    };

    const readBody = (req: IncomingMessage): Promise<string> =>
        new Promise((resolve, reject) => {
            let data = '';
            req.on('data', (chunk) => {
                data += chunk;
                if (data.length > 5 * 1024 * 1024) req.destroy();
            });
            req.on('end', () => resolve(data));
            req.on('error', reject);
        });

    const server = createServer(async (req, res) => {
        try {
            const url = new URL(req.url ?? '/', `http://localhost:${opts.port}`);

            // ---- Built web static assets (apps/web/dist) ----
            if (req.method === 'GET' && WEB_DIST && url.pathname.startsWith('/assets/')) {
                const fp = path.join(WEB_DIST, decodeURIComponent(url.pathname));
                if (existsSync(fp) && statSync(fp).isFile()) {
                    serveStaticFile(res, fp);
                    return;
                }
            }

            // ---- SPA root / index ----
            if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) {
                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.');
                }
                return;
            }

            // ---- SPA fallback (client-side routing, non-asset GET) ----
            if (
                req.method === 'GET' &&
                !url.pathname.startsWith('/api') &&
                !path.extname(url.pathname)
            ) {
                const idx = resolveIndexHtml();
                if (existsSync(idx)) {
                    serveStaticFile(res, idx);
                    return;
                }
            }

            // ---- SSE stream ----
            if (req.method === 'GET' && url.pathname === '/api/stream') {
                res.writeHead(200, {
                    'Content-Type': 'text/event-stream; charset=utf-8',
                    'Cache-Control': 'no-cache',
                    Connection: 'keep-alive',
                });
                res.write('retry: 3000\n\n');
                sseClients.add(res);
                broadcast('jobs', store.list()); // replay current jobs snapshot
                res.write(`event: preview\ndata: ${JSON.stringify(preview.state)}\n\n`);
                const ping = setInterval(() => {
                    try {
                        res.write(': ping\n\n');
                    } catch {
                        /* ignore */
                    }
                }, 15000);
                req.on('close', () => {
                    clearInterval(ping);
                    sseClients.delete(res);
                });
                return;
            }

            // ---- GET /api/config ----
            if (req.method === 'GET' && url.pathname === '/api/config') {
                const view: ServerConfigView = configView(model, opts.maxConcurrent);
                sendJson(res, 200, view);
                return;
            }

            // ---- POST /api/generate ----
            if (req.method === 'POST' && url.pathname === '/api/generate') {
                const raw = await readBody(req);
                let body: GenerateRequest;
                try {
                    body = JSON.parse(raw || '{}');
                } catch {
                    sendJson(res, 400, { error: 'Invalid JSON body' });
                    return;
                }
                const figmaUrl = (body.figmaUrl || '').trim();
                if (!figmaUrl) {
                    sendJson(res, 400, { error: 'figmaUrl 为必填项' });
                    return;
                }
                try {
                    parseFigmaUrl(figmaUrl);
                } catch {
                    sendJson(res, 400, {
                        error: 'Invalid Figma URL(需包含 design/file 链接与 ?node-id=)',
                    });
                    return;
                }

                const mode =
                    body.mode && ['full', 'code', 'with-report'].includes(body.mode)
                        ? body.mode
                        : 'full';
                const job: Job = {
                    id: `job-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
                    status: 'queued',
                    figmaUrl,
                    mode,
                    outputDir: body.outputDir
                        ? path.resolve(body.outputDir)
                        : opts.outputDir,
                    appName: body.appName || 'my-app',
                    resultDir: null,
                    reportPath: null,
                    error: null,
                    pid: null,
                    createdAt: new Date().toISOString(),
                    startedAt: null,
                    finishedAt: null,
                };
                queue.submit(job);
                const position = queue.position(job.id);
                sendJson(res, 200, {
                    jobId: job.id,
                    position,
                    message:
                        position > 0
                            ? `已加入队列,前方还有 ${position} 个任务`
                            : '开始生成',
                });
                return;
            }

            // ---- GET /api/jobs ----
            if (req.method === 'GET' && url.pathname === '/api/jobs') {
                sendJson(res, 200, { jobs: store.list() });
                return;
            }

            // ---- GET /api/job/:id ----
            if (req.method === 'GET' && url.pathname.startsWith('/api/job/')) {
                const id = url.pathname.slice('/api/job/'.length);
                const job = store.get(id);
                sendJson(res, job ? 200 : 404, job ?? { error: 'not found' });
                return;
            }

            // ---- GET /api/preview ----
            if (req.method === 'GET' && url.pathname === '/api/preview') {
                sendJson(res, 200, preview.state);
                return;
            }

            // ---- POST /api/preview (start) ----
            if (req.method === 'POST' && url.pathname === '/api/preview') {
                const raw = await readBody(req);
                let body: { appPath?: string } = {};
                try {
                    body = JSON.parse(raw || '{}');
                } catch {
                    /* ignore */
                }
                const latestDone = store
                    .list()
                    .find((j) => j.status === 'done' && j.resultDir);
                const appPath =
                    body.appPath ||
                    PreviewManager.defaultAppPath(latestDone?.resultDir ?? null);
                const r = preview.start(appPath);
                sendJson(res, r.ok ? 200 : 409, { ok: r.ok, error: r.error });
                return;
            }

            // ---- POST /api/preview/stop ----
            if (req.method === 'POST' && url.pathname === '/api/preview/stop') {
                preview.stop();
                sendJson(res, 200, { ok: true });
                return;
            }

            res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
            res.end('Not Found');
        } catch (err) {
            sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) });
        }
    });

    return { server, broadcast };
}