preview.ts 5.57 KB
import { spawn, execSync, type ChildProcess } from 'node:child_process';
import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
import { existsSync } from 'node:fs';
import type { PreviewState } from './types';

/**
 * Manages a persistent dev server for a generated `my-app` so the user can open
 * and inspect the result in the browser. Distinct from the transient dev server
 * the VALIDATION node spins up internally for screenshots (torn down after each
 * iteration). This is a placeholder for the Phase 3 static-build hosting: for
 * now we `npm run dev` the generated app and probe the port.
 */
export class PreviewManager {
    private proc: ChildProcess | null = null;
    state: PreviewState = {
        running: false,
        appPath: null,
        url: null,
        localUrl: null,
        port: null,
        pid: null,
        error: null,
    };

    constructor(private readonly onChange: (s: PreviewState) => void) {}

    private getLanIp(): string {
        const nets = os.networkInterfaces();
        for (const name of Object.keys(nets)) {
            for (const ni of nets[name] ?? []) {
                if (ni.family === 'IPv4' && !ni.internal) return ni.address;
            }
        }
        return 'localhost';
    }

    start(explicitAppPath?: string | null): { ok: boolean; error?: string } {
        if (this.proc) return { ok: false, error: '预览服务已在运行,请先停止' };
        const appPath =
            explicitAppPath && existsSync(explicitAppPath) ? explicitAppPath : null;
        if (!appPath) return { ok: false, error: '未找到生成的 my-app,请先完成一次生成' };

        this.state = {
            running: true,
            appPath,
            url: null,
            localUrl: null,
            port: null,
            pid: null,
            error: null,
        };
        try {
            const child = spawn('npm run dev -- --host --port 5180', {
                cwd: appPath,
                env: { ...process.env },
                windowsHide: true,
                detached: true,
                shell: true,
            });
            child.unref();
            this.proc = child;
            this.state.pid = child.pid ?? null;

            child.on('error', (e) => {
                this.state = { ...this.state, running: false, error: e.message };
                this.proc = null;
                this.onChange(this.state);
            });
            child.on('exit', (code) => {
                if (this.proc === child) {
                    this.state = {
                        ...this.state,
                        running: false,
                        error: code ? `预览进程退出 (code ${code})` : null,
                    };
                    this.proc = null;
                    this.onChange(this.state);
                }
            });

            // Reliable URL detection: probe the dev-server port(s) until reachable.
            const startPort = 5180;
            const endPort = 5195;
            const deadline = Date.now() + 90_000;
            const probe = setInterval(() => {
                if (this.state.url || !this.proc) {
                    clearInterval(probe);
                    return;
                }
                if (Date.now() > deadline) {
                    clearInterval(probe);
                    return;
                }
                for (let p = startPort; p <= endPort; p++) {
                    const sock = net.createConnection({ port: p, host: '127.0.0.1' });
                    let connected = false;
                    sock.once('connect', () => {
                        connected = true;
                        sock.destroy();
                        clearInterval(probe);
                        const ip = this.getLanIp();
                        this.state.localUrl = `http://localhost:${p}/`;
                        this.state.url = `http://${ip}:${p}/`;
                        this.state.port = p;
                        this.onChange(this.state);
                    });
                    sock.once('error', () => {
                        if (!connected) sock.destroy();
                    });
                }
            }, 1000);

            this.onChange(this.state);
            return { ok: true };
        } catch (e) {
            const message = e instanceof Error ? e.message : String(e);
            this.state = {
                running: false,
                appPath: null,
                url: null,
                localUrl: null,
                port: null,
                pid: null,
                error: message,
            };
            this.proc = null;
            return { ok: false, error: message };
        }
    }

    stop(): void {
        if (this.proc?.pid) {
            try {
                if (os.platform() === 'win32') {
                    execSync(`taskkill /pid ${this.proc.pid} /f /t`, { stdio: 'ignore' });
                } else {
                    process.kill(-this.proc.pid, 'SIGKILL');
                }
            } catch {
                /* ignore */
            }
        }
        this.proc = null;
        this.state = {
            running: false,
            appPath: null,
            url: null,
            localUrl: null,
            port: null,
            pid: null,
            error: null,
        };
        this.onChange(this.state);
    }

    /** Default app path = latest done job's resultDir/my-app. */
    static defaultAppPath(resultDir: string | null): string | null {
        if (!resultDir) return null;
        const p = path.join(resultDir, 'my-app');
        return existsSync(p) ? p : null;
    }
}