preview.ts
2.76 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
import path from 'node:path';
import { parseFigmaUrl } from 'coderio';
import type { Route } from './context';
import { PreviewManager } from '../preview';
/** 生成结果预览服务:状态、启动、停止、重启。 */
export const previewRoutes: Route[] = [
// ---- GET /api/preview:查询预览服务状态 ----
{
method: 'GET',
path: '/api/preview',
handle: ({ ctx, res }) => {
ctx.sendJson(res, 200, ctx.preview.state);
},
},
// ---- POST /api/preview(启动预览)----
{
method: 'POST',
path: '/api/preview',
handle: async ({ ctx, req, res }) => {
let body: { appPath?: string } = {};
try {
body = await ctx.readJsonBody<{ appPath?: string }>(req);
} catch {
/* 忽略解析失败,使用默认解析 */
}
// 解析生成的 app 目录:优先用最新完成任务的 Figma URL 重新解析(见下方说明),
// 而非信任持久化的 resultDir——后者由 server 进程在 spawn 时计算,若 coderio
// 包在 server 启动后被重建(开发期常见),存储值可能与引擎实际创建目录不一致,
// 导致 preview 找不到 my-app。仅在 URL 解析失败时才回退到存储值。
const latestDone = ctx.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(ctx.opts.outputDir, 'coderio', projectName);
}
} catch {
resolvedDir = null;
}
}
if (!resolvedDir && latestDone?.resultDir) {
resolvedDir = latestDone.resultDir;
}
const appPath = body.appPath || PreviewManager.defaultAppPath(resolvedDir);
const r = ctx.preview.start(appPath);
ctx.sendJson(res, r.ok ? 200 : 409, { ok: r.ok, error: r.error });
},
},
// ---- POST /api/preview/stop:停止预览 ----
{
method: 'POST',
path: '/api/preview/stop',
handle: ({ ctx, res }) => {
ctx.preview.stop();
ctx.sendJson(res, 200, { ok: true });
},
},
// ---- POST /api/preview/restart:重启预览 ----
{
method: 'POST',
path: '/api/preview/restart',
handle: ({ ctx, res }) => {
const r = ctx.preview.restart();
ctx.sendJson(res, r.ok ? 200 : 409, { ok: r.ok, error: r.error });
},
},
];