graph.ts
7.72 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
import { StateGraph, START, END } from '@langchain/langgraph';
import { GraphNode, ValidationMode } from './types/graph-types';
import { GraphStateAnnotation } from './state';
import { initialProject } from './nodes/initial';
import { generateProtocol } from './nodes/process';
import { runValidation } from './nodes/validation';
import { parseFigmaUrl } from './utils/url-parser';
import { workspaceManager } from './utils/workspace';
import { generateCode } from './nodes/code';
import { initializeSqliteSaver, promptCheckpointChoice, resetCheckpointDb } from './utils/checkpoint';
import { logger } from './utils/logger';
import { setRuntimeConfig } from './utils/config';
import { setProjectProfile } from './utils/project-profile';
import type { ProjectProfile } from './types/project-profile';
/**
* Optional parameters for the design-to-code run, used by the service mode
* (`coderio serve`) to drive generation non-interactively.
*/
export interface Design2CodeOptions {
/**
* Custom root directory for the generated project. Maps to the `rootPath`
* argument of `workspaceManager.initWorkspace`. Defaults to the current
* working directory when omitted (CLI behavior).
*/
outputDir?: string;
/**
* Custom generated app folder name (defaults to `my-app`).
*/
appName?: string;
/**
* Explicit resume decision. When provided (true/false) the interactive
* checkpoint prompt is skipped — required for non-interactive service mode.
* When omitted, the CLI falls back to `promptCheckpointChoice`.
*/
resume?: boolean;
/**
* Runtime model + Figma configuration injected by the orchestration backend
* (apps/server). When provided, it overrides `~/.coderio/config.yaml` for
* this run, so the backend owns credentials instead of a global file.
* `figmaToken` maps to the Figma personal access token.
*/
modelConfig?: {
provider?: string;
model?: string;
baseUrl?: string;
apiKey?: string;
figmaToken?: string;
};
/**
* Project profile (the "画像" of the target project A) injected by the
* orchestration backend. When present, the CODE node constrains generation
* to the target project's components / tokens / utils / conventions so the
* output matches the team's existing code rather than a generic scaffold.
*/
projectProfile?: ProjectProfile | null;
/**
* Generation target chosen by the user on the workbench: where the code
* should land (standalone / new-page / modify-slot). Recorded for a future
* phase that rewrites into the real project; currently generation still
* writes to the default workspace and this value is informational.
*/
target?: {
mode?: string;
page?: string;
slot?: string;
} | null;
/**
* Whether the generated root component should fill its host container.
* Defaults to `true` (embed-into-app-shell scenario). When `false`, the
* root renders at the Figma frame's intrinsic width, centered, without
* stretching to a wide viewport (useful for fixed-width standalone previews).
*/
fillContainer?: boolean;
}
export async function design2code(url: string, mode?: ValidationMode, options?: Design2CodeOptions): Promise<void> {
const opts = options ?? {};
// Apply backend-injected runtime config (overrides ~/.coderio/config.yaml).
if (opts.modelConfig) {
const mc = opts.modelConfig;
const modelOverride: Record<string, string> = {};
if (mc.provider !== undefined) modelOverride.provider = mc.provider;
if (mc.model !== undefined) modelOverride.model = mc.model;
if (mc.baseUrl !== undefined) modelOverride.baseUrl = mc.baseUrl;
if (mc.apiKey !== undefined) modelOverride.apiKey = mc.apiKey;
setRuntimeConfig({
model: modelOverride,
figma: mc.figmaToken !== undefined ? { token: mc.figmaToken } : undefined,
});
}
// Apply the target-project profile (画像) so the CODE node generates code
// that matches the team's existing components / tokens / conventions.
if (opts.projectProfile !== undefined) {
setProjectProfile(opts.projectProfile);
}
// Reset cached workspace so a fresh run (especially in service mode, where
// multiple jobs may run in the same process) does not reuse a stale path.
workspaceManager.reset();
const urlInfo = parseFigmaUrl(url);
const threadId = urlInfo.projectName!;
const workspace = workspaceManager.initWorkspace(threadId, opts.outputDir, opts.appName);
const dbPath = workspace.db;
logger.printInfoLog(`已开始设计稿转代码流程:${urlInfo.projectName}`);
// Resolve resume decision. Service mode always passes an explicit boolean
// (resume:false), so no interactive prompt is needed there.
let checkpointer: ReturnType<typeof initializeSqliteSaver>;
let resume: boolean | undefined;
if (typeof opts.resume === 'boolean') {
resume = opts.resume;
} else {
// CLI: open a probe saver just to check for an existing checkpoint,
// then close it (we reopen below once the decision is made).
const probe = initializeSqliteSaver(dbPath);
resume = await promptCheckpointChoice(probe, threadId);
try {
(probe as unknown as { db?: { close(): void } }).db?.close();
} catch {
/* ignore */
}
}
if (resume !== true) {
// Fresh start: open the checkpoint db, then reset its state in place
// (flush + truncate the WAL and clear the checkpoint tables) so a
// previous crashed / force-killed run can never leave a read-only WAL
// behind. We reset via SQL rather than deleting the files because file
// deletion is intercepted by the environment's `safe-delete` hook.
checkpointer = initializeSqliteSaver(dbPath);
resetCheckpointDb(checkpointer, dbPath);
// Clean the rest of the workspace but keep the checkpoint database
// files (they are reset in place above, no need to delete them).
workspaceManager.deleteWorkspace(workspace, [
'checkpoint/coderio-cli.db',
'checkpoint/coderio-cli.db-shm',
'checkpoint/coderio-cli.db-wal',
]);
logger.printInfoLog('开始全新生成…');
} else {
checkpointer = initializeSqliteSaver(dbPath);
logger.printInfoLog('从缓存恢复…');
}
// Compile graph with checkpointer (after potential reinitialization)
const graph = new StateGraph(GraphStateAnnotation)
.addNode(GraphNode.INITIAL, initialProject)
.addNode(GraphNode.PROCESS, generateProtocol)
.addNode(GraphNode.CODE, generateCode)
.addNode(GraphNode.VALIDATION, runValidation)
.addEdge(START, GraphNode.INITIAL)
.addEdge(GraphNode.INITIAL, GraphNode.PROCESS)
.addEdge(GraphNode.PROCESS, GraphNode.CODE)
.addEdge(GraphNode.CODE, GraphNode.VALIDATION)
.addEdge(GraphNode.VALIDATION, END)
.compile({ checkpointer });
const config = { configurable: { thread_id: threadId } };
// If resuming from checkpoint, pass null to let LangGraph resume from saved state
// Otherwise, pass initial state to start fresh
const validationMode: ValidationMode = mode ?? ValidationMode.Full;
const state =
resume === true
? null
: {
messages: [],
urlInfo,
workspace,
config: {
validationMode,
},
fillContainer: opts.fillContainer ?? true,
};
await graph.invoke(state, config);
logger.printSuccessLog('设计稿转代码流程已完成!');
}