ai-direct-preview-project.mjs
7.54 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
#!/usr/bin/env node
import child_process from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { requireWorkspaceRoot } from "./workspace-root.mjs";
const repoRoot = requireWorkspaceRoot();
function parseCliArgs() {
const args = process.argv.slice(2);
const parsed = {
bundleFile: "",
name: "",
dir: "apps/web/ai-previews",
existingProjectRoot: "",
force: false,
install: false,
};
for (let index = 0; index < args.length; index++) {
const arg = args[index];
const next = args[index + 1];
if (arg === "--bundle-file" && next) {
parsed.bundleFile = next;
index++;
} else if (arg === "--name" && next) {
parsed.name = next;
index++;
} else if (arg === "--dir" && next) {
parsed.dir = next;
index++;
} else if (arg === "--existing-project-root" && next) {
parsed.existingProjectRoot = next;
index++;
} else if (arg === "--force") {
parsed.force = true;
} else if (arg === "--install") {
parsed.install = true;
}
}
return parsed;
}
function readJson(filePath) {
return JSON.parse(fs.readFileSync(filePath, "utf8"));
}
function slugify(value) {
const normalized = String(value || "")
.trim()
.toLowerCase()
.replaceAll(/[^a-z0-9]+/g, "-")
.replaceAll(/^-+|-+$/g, "");
return normalized || "figma-page";
}
function toAbsolutePath(targetPath) {
return path.isAbsolute(targetPath) ? targetPath : path.resolve(targetPath);
}
function quote(value) {
return `"${String(value).replaceAll('"', String.raw`\"`)}"`;
}
function ensureCliBuilt() {
const cliEntry = path.join(repoRoot, "packages", "cli", "dist", "index.cjs.js");
if (fs.existsSync(cliEntry)) {
return;
}
throw new Error("Venus CLI 未构建,请先执行 pnpm run venus:build");
}
function normalizePath(targetPath) {
return targetPath.replaceAll("\\", "/");
}
function buildPreviewArgs({ previewName, bundle, targetDir, install, force }) {
const policy = bundle.rules.previewProjectPolicy || {};
if (!policy.mustUseVenusCli) {
throw new Error("当前 bundle 未声明 mustUseVenusCli,拒绝创建预览项目");
}
if (!policy.cliTemplate) {
throw new Error("当前框架没有可用的 Venus CLI 模板,无法创建预览项目");
}
ensureCliBuilt();
const args = [
"venus",
"create",
previewName,
"--template",
policy.cliTemplate,
"--dir",
targetDir,
"--root",
repoRoot,
"--router",
"--store",
"--eslint",
];
if (policy.cliUiOption) {
args.push("--ui", policy.cliUiOption);
}
if (!install) {
args.push("--no-install");
}
if (force) {
args.push("--force");
}
return args;
}
function run() {
const args = parseCliArgs();
if (!args.bundleFile) {
throw new Error(
"用法: node scripts/ai-direct-preview-project.mjs --bundle-file <bundle.json> [--name preview-name]",
);
}
const bundlePath = toAbsolutePath(args.bundleFile);
const bundle = readJson(bundlePath);
const summaryPath = path.join(
path.dirname(bundlePath),
`${path.basename(bundlePath, ".ai-direct-context-bundle.json")}.preview-project.json`,
);
const previewName = args.name || `${slugify(bundle.figma.pageSlug || bundle.figma.pageName)}-preview`;
let projectPath = "";
let command = "";
let mode = "create";
if (args.existingProjectRoot) {
projectPath = toAbsolutePath(args.existingProjectRoot);
command = "[reuse existing preview project]";
mode = "reuse-existing";
if (!fs.existsSync(projectPath)) {
throw new Error(`指定的现有预览项目不存在: ${projectPath}`);
}
} else {
const createArgs = buildPreviewArgs({
previewName,
bundle,
targetDir: args.dir,
install: args.install,
force: args.force,
});
command = `pnpm ${createArgs.join(" ")}`;
projectPath = path.join(repoRoot, args.dir, previewName);
}
console.log("[ai-direct-preview-project] 准备预览项目...");
console.log(` → bundle: ${bundlePath}`);
console.log(` → mode: ${mode}`);
if (mode === "create") {
console.log(` → name: ${previewName}`);
console.log(` → dir: ${args.dir}`);
console.log(` → force: ${args.force}`);
console.log(` → command: ${command}`);
// 如果目标目录已存在,清理除 .ai-direct 外的内容
let aiDirectBackup = null;
if (fs.existsSync(projectPath)) {
console.log(` → 目标目录已存在,正在清理: ${projectPath}`);
const entries = fs.readdirSync(projectPath, { withFileTypes: true });
for (const entry of entries) {
if (entry.name === ".ai-direct") {
// 备份 .ai-direct 到临时位置,创建完再移回
aiDirectBackup = path.join(projectPath, "..", `.${previewName}-ai-direct-tmp`);
const srcPath = path.join(projectPath, entry.name);
// Windows 文件锁问题:重试 rename,失败则降级为 cpSync+rmSync
let backedUp = false;
for (let attempt = 0; attempt < 3; attempt++) {
try {
fs.renameSync(srcPath, aiDirectBackup);
backedUp = true;
break;
} catch (err) {
if (err.code === "EPERM" && attempt < 2) {
console.warn(` ⚠ .ai-direct 目录被占用,等待重试 (${attempt + 1}/3)...`);
child_process.execSync("ping -n 2 127.0.0.1 > nul", { stdio: "ignore" });
} else {
break;
}
}
}
// 降级:cpSync + rmSync
if (!backedUp) {
try {
console.warn(` ⚠ 无法重命名 .ai-direct,尝试复制备份...`);
fs.cpSync(srcPath, aiDirectBackup, { recursive: true, force: true });
fs.rmSync(srcPath, { recursive: true, force: true });
backedUp = true;
console.log(` → 备份完成(复制模式)`);
} catch (copyErr) {
console.warn(` ⚠ 备份失败,删除旧 .ai-direct 继续: ${copyErr.message}`);
fs.rmSync(srcPath, { recursive: true, force: true });
aiDirectBackup = null;
}
}
continue;
}
const fullPath = path.join(projectPath, entry.name);
fs.rmSync(fullPath, { recursive: true, force: true });
}
// 如果目录空了则删除,让 venus create 重新创建
const remaining = fs.readdirSync(projectPath);
if (remaining.length === 0) {
fs.rmSync(projectPath, { recursive: true, force: true });
}
console.log(` → 清理完成`);
}
const createArgs = buildPreviewArgs({
previewName,
bundle,
targetDir: args.dir,
install: args.install,
force: args.force,
});
child_process.execFileSync("pnpm", createArgs, {
cwd: repoRoot,
stdio: "inherit",
shell: process.platform === "win32",
});
// 恢复 .ai-direct 备份
if (aiDirectBackup && fs.existsSync(aiDirectBackup)) {
const target = path.join(projectPath, ".ai-direct");
if (fs.existsSync(target)) {
fs.rmSync(target, { recursive: true, force: true });
}
fs.renameSync(aiDirectBackup, target);
console.log(` → 已恢复 .ai-direct 目录`);
}
} else {
console.log(` → project: ${projectPath}`);
}
const summary = {
meta: {
generator: "scripts/ai-direct-preview-project.mjs",
generatedAt: new Date().toISOString(),
mode,
bundleFile: normalizePath(bundlePath),
},
previewProject: {
name: path.basename(projectPath),
projectRoot: normalizePath(projectPath),
template: bundle.rules.previewProjectPolicy.cliTemplate,
ui: bundle.rules.previewProjectPolicy.cliUiOption,
install: mode === "create" ? args.install : false,
command,
},
};
fs.writeFileSync(summaryPath, `${JSON.stringify(summary, null, 2)}\n`, "utf8");
console.log("[ai-direct-preview-project] ✓ 完成");
console.log(` → project: ${projectPath}`);
console.log(` → summary: ${summaryPath}`);
}
run();
process.exit(0);