preview.ts
5.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
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;
}
}