utils.ts
12.3 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
import fs from 'fs';
import { GraphState } from '../../state';
import { logger } from '../../utils/logger';
import { callModel } from '../../utils/call-model';
import { promisePool } from '../../utils/promise-pool';
import { getActiveStrategy } from './strategies';
import { Protocol } from '../../types';
import { createFiles, writeFile } from '../../utils/file';
import { DEFAULT_STYLING } from './constants';
import path from 'path';
import { extractCode, extractFiles } from '../../utils/parser';
import { workspaceManager } from '../../utils/workspace';
import { CodeCache, isComponentGenerated, saveComponentGenerated, isAppInjected, saveAppInjected } from '../../utils/code-cache';
/**
* Ensure src/components/index.ts re-exports the root component actually present
* on disk. This makes `import X from '@/components'` resolve reliably for Vue,
* regardless of whether the CODE node wrote src/components/index.vue or a named
* file (e.g. src/components/DashboardLayout.vue).
*
* `.ts` is in Vite's default resolve.extensions, so the directory index resolves
* to this barrel file (more robust than relying on `.vue` directory-index).
*/
function ensureVueComponentsBarrel(state: GraphState, rootName: string): void {
const componentsDir = workspaceManager.resolveAppSrc(state.workspace, 'components');
try {
if (!fs.existsSync(componentsDir)) return;
const entries = fs.readdirSync(componentsDir);
// Preferred: src/components/index.vue (the convention we instruct the LLM to use)
const pick = (ext: string) =>
entries.find((e) => e.toLowerCase() === `index.${ext}`) ||
entries.find((e) => e.toLowerCase() === `${rootName.toLowerCase()}.${ext}`) ||
entries.find((e) => e.toLowerCase().endsWith(`.${ext}`) && fs.statSync(path.join(componentsDir, e)).isFile());
const file =
pick('vue') ||
pick('tsx') ||
pick('ts') ||
pick('jsx') ||
pick('js');
if (!file) return;
const rel = `./${file}`;
const barrel = `export { default } from '${rel}';\n`;
writeFile(componentsDir, 'index.ts', barrel);
logger.printInfoLog(`🔗 已生成组件聚合入口(barrel)-> ${rel}`);
} catch (err) {
logger.printWarnLog(`生成组件聚合入口失败: ${(err as Error).message}`);
}
}
/**
* Process a node tree and generate code for all nodes
* Uses post-order traversal (children first, then parent)
*/
export async function processNode(state: GraphState, cache: CodeCache): Promise<number> {
// Read asset files list once for the entire generation run
const assetFilesList = getAssetFilesList(state);
// Flatten tree using post-order traversal (children first, then parent)
const flatNodes = flattenPostOrder(state.protocol!);
const total = flatNodes.length;
if (total === 0) {
logger.printWarnLog('结构树中未识别到可生成的组件。');
return 0;
}
logger.printInfoLog(`正在处理 ${total} 个节点…`);
let processedCount = 0;
let skippedCount = 0;
const processSingleNode = async (currentNode: Protocol) => {
// Defense-in-depth: a node whose `data` is missing cannot be generated.
if (!currentNode || !currentNode.data) {
logger.printWarnLog(`跳过缺少 data 字段的节点(id=${currentNode?.id ?? 'unknown'})`);
return;
}
const componentName = currentNode.data.name || currentNode.data.componentName || 'UnknownComponent';
const nodeId = currentNode.id;
// Check if component is already generated
if (isComponentGenerated(cache, nodeId)) {
skippedCount++;
logger.printInfoLog(`[${processedCount + skippedCount}/${total}] ⏭️ 复用缓存,跳过:${componentName}`);
return;
}
const progressInfo = `[${++processedCount + skippedCount}/${total}]`;
const isLeaf = !currentNode.children?.length;
if (isLeaf) {
await generateComponent(currentNode, state, assetFilesList, progressInfo);
} else {
await generateFrame(currentNode, state, assetFilesList, progressInfo);
}
// Mark component as generated and save immediately to prevent cache loss on interruption
saveComponentGenerated(cache, nodeId, state.workspace);
};
// Process nodes with concurrency control
await promisePool(flatNodes, processSingleNode);
if (skippedCount > 0) {
logger.printInfoLog(`跳过了 ${skippedCount} 个已缓存的组件`);
}
logger.printSuccessLog(`已生成 ${processedCount} 个组件`);
return processedCount;
}
/**
* Flatten tree into array using post-order traversal
*/
export function flattenPostOrder(node: Protocol): Protocol[] {
const result: Protocol[] = [];
function traverse(n: Protocol) {
// Skip malformed nodes that lack a `data` field (e.g. emitted by a weak
// model on a truncated structure response). Without this, downstream code
// reads `node.data.name` on `undefined` and the whole run crashes.
if (!n || !n.data) return;
n.children?.forEach(child => traverse(child));
result.push(n);
}
traverse(node);
return result;
}
/**
* Detect which rendering modes are used in this frame
*/
export function detectRenderingModes(node: Protocol): {
hasStates: boolean;
hasIndependentChildren: boolean;
} {
const hasStates = !!node.data.states?.length;
let hasIndependentChildren = false;
(node.children || [])
.filter(child => child && child.data)
.forEach(child => {
if (!child.data!.componentName) {
hasIndependentChildren = true;
}
});
return { hasStates, hasIndependentChildren };
}
/**
* Generate a frame/container component
* Frames compose multiple child components based on layout
*/
export async function generateFrame(node: Protocol, state: GraphState, assetFilesList: string, progressInfo: string): Promise<void> {
const frameName = node.data.name;
logger.printInfoLog(`${progressInfo} 🖼️ 正在生成容器(Frame):${frameName}`);
// Build children imports information
const childrenImports = (node.children || [])
.filter(child => child && child.data)
.map(child => ({
name: child.data!.name || '',
path: child.data!.path,
}));
// Detect rendering modes
const renderingModes = detectRenderingModes(node);
// Generate prompt (framework dispatched via the active strategy)
const prompt = getActiveStrategy().buildFramePrompt({
frameDetails: JSON.stringify(node.data),
childrenImports: JSON.stringify(childrenImports),
styling: JSON.stringify(DEFAULT_STYLING),
assetFiles: assetFilesList,
renderingModes,
fillContainer: state.fillContainer ?? true,
});
// Call AI model
const code = await callModel({
question: prompt,
imageUrls: state.figmaInfo.thumbnail,
});
// Save generated files
const componentPath = node.data.path || '';
const filePath = workspaceManager.resolveAppSrc(state.workspace, workspaceManager.resolveComponentPath(componentPath));
saveGeneratedCode(code, filePath);
logger.printSuccessLog(`容器已生成:${frameName}`);
}
/**
* Generate a component (leaf or reusable)
* Components are self-contained UI elements driven by props
*/
export async function generateComponent(node: Protocol, state: GraphState, assetFilesList: string, progressInfo: string): Promise<void> {
const componentName = node.data.componentName || node.data.name || 'UnknownComponent';
const componentPath = node.data.componentPath || node.data.path || '';
logger.printInfoLog(`${progressInfo} 📦 正在生成组件:${componentName}`);
// Generate prompt (framework dispatched via the active strategy)
const prompt = getActiveStrategy().buildComponentPrompt({
componentName,
componentDetails: JSON.stringify(node.data),
styling: JSON.stringify(DEFAULT_STYLING),
assetFiles: assetFilesList,
fillContainer: state.fillContainer ?? true,
});
// Call AI model
const code = await callModel({
question: prompt,
imageUrls: state.figmaInfo.thumbnail,
});
// Save generated files
const filePath = workspaceManager.resolveAppSrc(state.workspace, workspaceManager.resolveComponentPath(componentPath));
saveGeneratedCode(code, filePath);
logger.printSuccessLog(`组件已生成:${componentName}`);
}
/**
* Helper function to save generated code (handles both single and multi-file output)
*/
export function saveGeneratedCode(code: string, filePath: string): void {
const files = extractFiles(code);
if (files.length > 0) {
// Multi-file output (e.g., index.tsx + index.module.less)
createFiles({ files, filePath });
} else {
const extractedCode = extractCode(code);
const folderPath = path.dirname(filePath);
const fileName = path.basename(filePath);
writeFile(folderPath, fileName, extractedCode);
}
}
/**
* Get list of available asset files for AI to match against
*/
function getAssetFilesList(state: GraphState) {
try {
const assetsDir = workspaceManager.resolveAppSrc(state.workspace, 'assets');
if (!fs.existsSync(assetsDir)) {
return '';
}
const files = fs.readdirSync(assetsDir);
return files.join(', ');
} catch {
return '';
}
}
/**
* Inject root component into App.tsx
* Reads existing App.tsx, adds import and renders the root component
*/
export async function injectRootComponentToApp(state: GraphState, cache: CodeCache): Promise<void> {
try {
logger.reportPhase('注入根组件', 85);
// Check if already injected
if (isAppInjected(cache)) {
logger.printInfoLog('⏭️ 根组件已注入,跳过 App.tsx 注入步骤');
return;
}
logger.printInfoLog(`💉 正在将根组件注入 ${getActiveStrategy().rootFileName}…`);
// Construct the framework-specific app entry path (App.tsx for React, App.vue for Vue, …)
const strategy = getActiveStrategy();
const appEntryPath = workspaceManager.resolveAppSrc(state.workspace, strategy.rootFileName);
// Read existing app entry or use the strategy's default template
let appContent: string;
try {
appContent = fs.readFileSync(appEntryPath, 'utf8');
} catch {
// Use default template if the app entry doesn't exist yet
logger.printWarnLog(`未找到 ${strategy.rootFileName},使用默认模板`);
appContent = strategy.defaultAppContent;
}
// Get root component information
const rootNode = state.protocol!;
const componentName = rootNode.data?.name || 'RootComponent';
const componentPath = rootNode.data?.path || '';
// Generate prompt (framework dispatched via the active strategy)
const prompt = strategy.buildRootInjectionPrompt({
appContent,
componentName,
componentPath,
});
// Call AI model
const updatedCode = await callModel({
question: prompt,
});
// Extract code (no markdown blocks expected based on prompt requirements)
const finalCode = updatedCode.includes('```') ? extractCode(updatedCode) : updatedCode.trim();
// Write updated app entry
const appFolderPath = path.dirname(appEntryPath);
writeFile(appFolderPath, strategy.rootFileName, finalCode);
// Mark as injected and save immediately
saveAppInjected(cache, state.workspace);
// For Vue, ensure the "@/components" barrel re-exports whatever file the
// CODE node actually generated for the root component (LLMs sometimes
// write src/components/<Name>.vue instead of src/components/index.vue).
if (strategy.rootFileName === 'App.vue') {
ensureVueComponentsBarrel(state, componentName);
}
logger.printSuccessLog(`已成功将根组件 ${componentName} 注入 App 入口`);
} catch (error) {
logger.printErrorLog(`注入根组件失败:${(error as Error).message}`);
// Don't throw - allow the process to continue even if injection fails
}
}