server.ts
26.4 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { readFileSync, existsSync, statSync, readdirSync } from 'node:fs';
import path from 'node:path';
import os from 'node:os';
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 { ProjectRunner } from './project-runner';
import { configView, loadServerModelConfig, resolveServerOptions, loadProjectProfile, saveProjectProfile, projectProfileTemplate } from './config';
import { scanProject } from './project-scanner';
import type {
GenerateRequest,
Job,
ServerConfigView,
SystemStatus,
OrchestratorStatus,
EngineStatus,
EnvInfo,
JobStats,
} 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',
};
/** Directories hidden from the picker to keep navigation readable. */
const FS_NOISE = new Set([
'node_modules',
'.git',
'.next',
'.nuxt',
'.turbo',
'.cache',
'dist',
'build',
'out',
'coverage',
'.svelte-kit',
'.output',
'.workbuddy',
'.trash',
'.trash-win',
]);
/** Top-level filesystem roots for the picker's initial view. */
function listRoots(): string[] {
if (process.platform === 'win32') {
const drives: string[] = [];
for (const c of 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
try {
if (existsSync(`${c}:\\`)) drives.push(`${c}:\\`);
} catch {
/* inaccessible drive, skip */
}
}
return drives.length ? drives : ['C:\\'];
}
return ['/'];
}
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;
projectRunner: ProjectRunner;
opts: ReturnType<typeof resolveServerOptions>;
startTime: number;
serverVersion: string;
coderioVersion: string;
admin: { restart: () => void; shutdown: () => void };
}
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, projectRunner, opts, startTime, serverVersion, coderioVersion, admin } = deps;
const sseClients = new Set<ServerResponse>();
const model = loadServerModelConfig();
const computeStatus = (): SystemStatus => {
const jobsList = store.list();
const jobs: JobStats = {
total: jobsList.length,
queued: jobsList.filter((j) => j.status === 'queued').length,
running: jobsList.filter((j) => j.status === 'running').length,
done: jobsList.filter((j) => j.status === 'done').length,
error: jobsList.filter((j) => j.status === 'error').length,
cancelled: jobsList.filter((j) => j.status === 'cancelled').length,
};
const orchestrator: OrchestratorStatus = {
running: true,
version: serverVersion,
pid: process.pid,
port: opts.port,
host: opts.host,
uptimeSec: Math.floor((Date.now() - startTime) / 1000),
startedAt: new Date(startTime).toISOString(),
dataDir: opts.dataDir,
outputDir: opts.outputDir,
maxConcurrent: opts.maxConcurrent,
};
const engine: EngineStatus = {
name: 'coderio',
version: coderioVersion,
status: 'ready',
};
const env: EnvInfo = {
node: process.version,
platform: process.platform,
arch: process.arch,
cpus: os.cpus().length,
totalMemoryGB: (os.totalmem() / 1e9).toFixed(1),
cwd: process.cwd(),
};
return { orchestrator, preview: preview.state, engine, env, jobs };
};
// In-memory ring buffer of recent engine logs so that (re)connecting
// clients receive history instead of a blank terminal.
const MAX_LOG_HISTORY = 1000;
const recentLogs: LogEntry[] = [];
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 (and buffer history).
subscribeLogs((entry: LogEntry) => {
recentLogs.push(entry);
if (recentLogs.length > MAX_LOG_HISTORY) recentLogs.shift();
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);
});
/** Read the request body and parse it as JSON (returns `{}` for empty bodies). */
const readJsonBody = async <T = Record<string, unknown>>(req: IncomingMessage): Promise<T> =>
JSON.parse((await readBody(req)) || '{}') as T;
const server = createServer(async (req, res) => {
try {
const url = new URL(req.url ?? '/', `http://localhost:${opts.port}`);
// 开发模式(COD_SERVE_WEB=0)下后端不托管 UI,根路径跳转前端 dev server。
const SERVE_WEB = process.env.COD_SERVE_WEB !== '0';
if (!SERVE_WEB && req.method === 'GET' && url.pathname === '/') {
const webPort = process.env.COD_WEB_PORT || '5173';
res.writeHead(302, { Location: `http://localhost:${webPort}/` });
res.end();
return;
}
// ---- 就绪探针(轻量、首屏即开)----
// 端口仅在引擎加载 + sqlite 初始化全部完成后才 listen(),因此本端点
// 一旦返回 200,即可认定后端已完全就绪、可接收 /api/generate。前端用它
// 在「重启后端」的 boot 窗口期内门控「开始生成」按钮,避免点进未就绪的端口。
if (req.method === 'GET' && url.pathname === '/api/health') {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ ok: true, uptime: Math.round(process.uptime()) }));
return;
}
// ---- Built web static assets (apps/web/dist) ----
if (SERVE_WEB && 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 (SERVE_WEB && 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 (
SERVE_WEB &&
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);
// Replay recent log history so the terminal isn't blank on (re)connect.
for (const entry of recentLogs) {
res.write(`event: log\ndata: ${JSON.stringify(entry)}\n\n`);
}
broadcast('jobs', store.list()); // replay current jobs snapshot
res.write(`event: preview\ndata: ${JSON.stringify(preview.state)}\n\n`);
res.write(`event: projectRun\ndata: ${JSON.stringify(projectRunner.getStatus())}\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;
}
// ---- GET /api/project-profile ----
// Returns the target-project profile (画像) for the "项目接入"
// settings panel, or a fresh seed template when none is set.
if (req.method === 'GET' && url.pathname === '/api/project-profile') {
const profile = loadProjectProfile() ?? projectProfileTemplate();
const exists = loadProjectProfile() !== null;
sendJson(res, 200, { exists, profile });
return;
}
// ---- PUT /api/project-profile ----
// Persist the project profile edited in the UI. PUT replaces the
// whole profile; the engine picks it up on the next job (it reads
// the file per run, so no restart is required).
if (req.method === 'PUT' && url.pathname === '/api/project-profile') {
let incoming: unknown;
try {
incoming = await readJsonBody(req);
} catch {
sendJson(res, 400, { error: 'Invalid JSON body' });
return;
}
if (!incoming || typeof incoming !== 'object') {
sendJson(res, 400, { error: 'profile must be an object' });
return;
}
const profile = { ...projectProfileTemplate(), ...(incoming as Record<string, unknown>) } as never;
try {
saveProjectProfile(profile);
sendJson(res, 200, { ok: true, profile });
} catch (e) {
sendJson(res, 500, { error: e instanceof Error ? e.message : '保存失败' });
}
return;
}
// ---- POST /api/project-profile/scan ----
// Scan a target project root and draft a ProjectProfile (画像). This
// is the Phase 1 scanner: it never writes to the target project or
// the canonical profile file — it just returns a draft for the UI
// to review and (optionally) persist via PUT.
if (req.method === 'POST' && url.pathname === '/api/project-profile/scan') {
let body: { rootDir?: string } = {};
try {
body = await readJsonBody<{ rootDir?: string }>(req);
} catch {
sendJson(res, 400, { error: 'Invalid JSON body' });
return;
}
const rootDir = (body.rootDir || '').trim();
if (!rootDir) {
sendJson(res, 400, { error: 'rootDir 为必填项(目标项目根目录)' });
return;
}
try {
const result = scanProject(rootDir);
sendJson(res, 200, result);
} catch (e) {
sendJson(res, 500, { error: e instanceof Error ? e.message : '扫描失败' });
}
return;
}
// ---- GET /api/fs/list (server-side directory browser) ----
// Powers the frontend directory picker. Returns immediate child
// directories (plus the parent path) so the UI can navigate the
// SERVER's filesystem and pick a real absolute path. Noise dirs
// (node_modules / .git / build caches) are hidden to keep the tree
// readable. When `dir` is empty, returns the top-level roots.
if (req.method === 'GET' && url.pathname === '/api/fs/list') {
const dirParam = (url.searchParams.get('dir') || '').trim();
try {
if (!dirParam) {
sendJson(res, 200, { path: null, parent: null, dirs: listRoots(), isRoot: true });
return;
}
const abs = path.resolve(dirParam);
if (!existsSync(abs) || !statSync(abs).isDirectory()) {
sendJson(res, 400, { error: `目录不存在:${abs}` });
return;
}
const entries = readdirSync(abs, { withFileTypes: true });
const dirs = entries
.filter((e) => e.isDirectory() && !FS_NOISE.has(e.name))
.map((e) => e.name)
.sort((a, b) => a.localeCompare(b));
const parent = path.dirname(abs);
sendJson(res, 200, {
path: abs,
parent: parent !== abs ? parent : null,
dirs,
isRoot: false,
});
} catch (e) {
sendJson(res, 500, { error: e instanceof Error ? e.message : '读取目录失败' });
}
return;
}
// ---- GET /api/admin/status (system snapshot) ----
if (req.method === 'GET' && url.pathname === '/api/admin/status') {
sendJson(res, 200, computeStatus());
return;
}
// ---- POST /api/generate ----
if (req.method === 'POST' && url.pathname === '/api/generate') {
let body: GenerateRequest;
try {
body = await readJsonBody<GenerateRequest>(req);
} 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',
target: body.target ?? null,
stack: body.stack ?? null,
fillContainer: body.fillContainer ?? true,
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/logs (recent log history) ----
if (req.method === 'GET' && url.pathname === '/api/logs') {
sendJson(res, 200, { logs: recentLogs });
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;
}
// ---- POST /api/jobs/:id/cancel ----
if (
req.method === 'POST' &&
url.pathname.startsWith('/api/jobs/') &&
url.pathname.endsWith('/cancel')
) {
const id = url.pathname
.slice('/api/jobs/'.length)
.replace(/\/cancel$/, '');
const ok = queue.cancel(id);
sendJson(res, ok ? 200 : 404, { ok });
return;
}
// ---- DELETE /api/jobs/:id (remove a single job) ----
if (
req.method === 'DELETE' &&
url.pathname.startsWith('/api/jobs/')
) {
const id = url.pathname.slice('/api/jobs/'.length);
const job = store.get(id);
if (!job) {
sendJson(res, 404, { ok: false, error: '任务不存在' });
return;
}
// Abort a still-live run so we don't leak a detached child.
if (job.status === 'running' || job.status === 'queued') {
queue.cancel(id);
}
store.delete(id);
broadcast('jobs', store.list());
sendJson(res, 200, { ok: true });
return;
}
// ---- DELETE /api/jobs (clear all jobs) ----
if (req.method === 'DELETE' && url.pathname === '/api/jobs') {
const all = store.list();
for (const j of all) {
if (j.status === 'running' || j.status === 'queued') {
queue.cancel(j.id);
}
}
const count = store.clear();
broadcast('jobs', store.list());
sendJson(res, 200, { ok: true, count });
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') {
let body: { appPath?: string } = {};
try {
body = await readJsonBody<{ appPath?: string }>(req);
} catch {
/* ignore */
}
// Resolve the generated app directory. We derive it from the
// latest finished job's Figma URL using the *current* parser
// rather than trusting the persisted `resultDir`: that string is
// computed by the server process at spawn time, so if the
// `coderio` dist was rebuilt after the server started (common
// during development), the stored value can disagree with the
// directory the engine actually created — leaving preview unable
// to locate `my-app`. Fall back to the stored value only if the
// URL-based resolution fails.
const latestDone = store.list().find((j) => j.status === 'done' && j.figmaUrl);
let resolvedDir: string | null = null;
if (latestDone?.figmaUrl) {
try {
const projectName = parseFigmaUrl(latestDone.figmaUrl).projectName;
if (projectName) {
resolvedDir = path.resolve(opts.outputDir, 'coderio', projectName);
}
} catch {
resolvedDir = null;
}
}
if (!resolvedDir && latestDone?.resultDir) {
resolvedDir = latestDone.resultDir;
}
const appPath = body.appPath || PreviewManager.defaultAppPath(resolvedDir);
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;
}
// ---- POST /api/preview/restart ----
if (req.method === 'POST' && url.pathname === '/api/preview/restart') {
const r = preview.restart();
sendJson(res, r.ok ? 200 : 409, { ok: r.ok, error: r.error });
return;
}
// ---- GET /api/project/run (target-project dev-server status) ----
if (req.method === 'GET' && url.pathname === '/api/project/run') {
sendJson(res, 200, projectRunner.getStatus());
return;
}
// ---- POST /api/project/run (launch target project dev server) ----
if (req.method === 'POST' && url.pathname === '/api/project/run') {
let body: { dir?: string } = {};
try {
body = await readJsonBody<{ dir?: string }>(req);
} catch {
/* ignore */
}
const dir = (body.dir || loadProjectProfile()?.rootDir || '').trim();
if (!dir) {
sendJson(res, 400, { ok: false, error: '未配置工作目录(请先在「项目接入」中选择目标项目根)' });
return;
}
const r = projectRunner.start(dir);
sendJson(res, r.ok ? 200 : 409, { ok: r.ok, error: r.error });
return;
}
// ---- POST /api/project/run/stop ----
if (req.method === 'POST' && url.pathname === '/api/project/run/stop') {
projectRunner.stop();
sendJson(res, 200, { ok: true });
return;
}
// ---- POST /api/admin/restart (self-restart) ----
if (req.method === 'POST' && url.pathname === '/api/admin/restart') {
sendJson(res, 200, { ok: true, message: '服务正在重启…' });
// 直接触发重启,不依赖 res.on('finish'):否则连接被提前关闭时
// 回调可能不触发,导致「点了重启却没反应」。
admin.restart();
return;
}
// ---- POST /api/admin/shutdown ----
if (req.method === 'POST' && url.pathname === '/api/admin/shutdown') {
sendJson(res, 200, { ok: true, message: '服务正在停止…' });
res.on('finish', () => admin.shutdown());
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 };
}