@collectui/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,386 @@
1
+ /**
2
+ * CollectUI Dash 的 shadcn 库目录(内置快照)。
3
+ *
4
+ * 数据源与 Dash 站点卡「AI Tools / Copy to Agent」同源(lib/ai-tools/libs.ts +
5
+ * packages/config/mcp-products.ts)。CLI 内置一份是为了在无网时也能「预览计划」,
6
+ * 实际密钥与授权仍以 /api/me 为准。新增库 = 在 LIBS 加一项;改 registry 路径/
7
+ * env 名时须同步 Dash,否则两者配置不一致。
8
+ */
9
+
10
+ /** MCP 产品(由 MCP_PRODUCTS 抄录,server 名/端点/stdio 包名逐一核对)。 */
11
+ export const MCP_PRODUCTS = {
12
+ affectui: {
13
+ id: "affectui",
14
+ label: "affectUI",
15
+ kind: "http",
16
+ endpointPath: "/api/affectui-mcp",
17
+ serverName: "affectui",
18
+ keyPrefix: "affectui_mcp",
19
+ },
20
+ arc: {
21
+ id: "arc",
22
+ label: "Arc",
23
+ kind: "http",
24
+ endpointPath: "/api/arc-mcp",
25
+ serverName: "arc",
26
+ keyPrefix: "arc_mcp",
27
+ },
28
+ beui: {
29
+ id: "beui",
30
+ label: "beUI Pro",
31
+ kind: "http",
32
+ endpointPath: "/api/beui-mcp",
33
+ serverName: "beui",
34
+ keyPrefix: "beui_mcp",
35
+ },
36
+ reactbits: {
37
+ id: "reactbits",
38
+ label: "React Bits",
39
+ kind: "http",
40
+ endpointPath: "/api/reactbits-mcp",
41
+ serverName: "reactbits",
42
+ keyPrefix: "reactbits_mcp",
43
+ },
44
+ reui: {
45
+ id: "reui",
46
+ label: "ReUI",
47
+ kind: "http",
48
+ endpointPath: "/api/reui-mcp",
49
+ serverName: "reui",
50
+ keyPrefix: "reui_mcp",
51
+ },
52
+ space: {
53
+ id: "space",
54
+ label: "ShadcnSpace",
55
+ kind: "http",
56
+ endpointPath: "/api/space-mcp",
57
+ serverName: "shadcnspace",
58
+ keyPrefix: "space_mcp",
59
+ },
60
+ shadcnstudio: {
61
+ id: "shadcnstudio",
62
+ label: "Shadcn Studio",
63
+ kind: "stdio",
64
+ packageName: "ss-studio-mcp",
65
+ serverName: "shadcn-studio-mcp",
66
+ keyPrefix: "ss_mcp",
67
+ extraEnv: { EMAIL: "studio@collectui.pro" },
68
+ },
69
+ uikit: {
70
+ id: "uikit",
71
+ label: "Shadcn UI Kit",
72
+ kind: "http",
73
+ endpointPath: "/api/uikit-mcp",
74
+ serverName: "shadcnuikit",
75
+ keyPrefix: "uikit_mcp",
76
+ },
77
+ "motion-plus": {
78
+ id: "motion-plus",
79
+ label: "Motion+",
80
+ kind: "http",
81
+ endpointPath: "/api/motion-plus-mcp",
82
+ serverName: "motion-plus",
83
+ keyPrefix: "mp_mcp",
84
+ },
85
+ "21st": {
86
+ id: "21st",
87
+ label: "21st.dev",
88
+ kind: "http",
89
+ endpointPath: "/api/21st-mcp",
90
+ serverName: "21st",
91
+ keyPrefix: "21st_mcp",
92
+ },
93
+ };
94
+
95
+ /** 官方 shadcn 通用 MCP(读 components.json 里全部 registries)。 */
96
+ export const SHADCN_MCP = {
97
+ serverName: "shadcn",
98
+ command: "npx",
99
+ args: ["shadcn@latest", "mcp"],
100
+ };
101
+
102
+ export const LIBS = [
103
+ {
104
+ site: "affectui",
105
+ siteName: "affectUI",
106
+ source: "affectui",
107
+ registries: [{ scope: "@affectui", headers: { Authorization: "Bearer ${AFFECTUI_TOKEN}" } }],
108
+ env: [{ name: "AFFECTUI_TOKEN", from: "cliKey" }],
109
+ mcp: "affectui",
110
+ verify: ["@affectui/thinking-loader"],
111
+ },
112
+ {
113
+ site: "arc",
114
+ siteName: "Arc",
115
+ source: "uiarc",
116
+ registries: [
117
+ // @uiarc 也带 key:registry 2026-11-02 起免费层退役,一律凭 key(uiarc_/arc_pro_ 前缀均可过)
118
+ { scope: "@uiarc", headers: { Authorization: "Bearer ${ARC_PRO_TOKEN}" } },
119
+ { scope: "@uiarc-pro", path: "pro/{name}.json", headers: { Authorization: "Bearer ${ARC_PRO_TOKEN}" } },
120
+ ],
121
+ env: [{ name: "ARC_PRO_TOKEN", from: "cliKey" }],
122
+ mcp: "arc",
123
+ verify: ["@uiarc/arc-foundation", "@uiarc/button", "@uiarc-pro/dock"],
124
+ freeVerify: ["@uiarc/button"],
125
+ foundation: {
126
+ install: "@uiarc/arc-foundation",
127
+ importPath: "@/components/arc/vendored/foundation.css",
128
+ },
129
+ },
130
+ {
131
+ site: "beui",
132
+ siteName: "BeUI",
133
+ source: "beui",
134
+ registries: [
135
+ // @beui 同上:registry 免费层退役,免费 scope 也须带 key
136
+ { scope: "@beui", headers: { Authorization: "Bearer ${BEUI_PRO_TOKEN}" } },
137
+ { scope: "@beui-pro", path: "pro/{name}.json", headers: { Authorization: "Bearer ${BEUI_PRO_TOKEN}" } },
138
+ ],
139
+ env: [{ name: "BEUI_PRO_TOKEN", from: "cliKey" }],
140
+ mcp: "beui",
141
+ verify: ["@beui/tilt-card"],
142
+ freeVerify: ["@beui/tilt-card"],
143
+ },
144
+ {
145
+ site: "efferd",
146
+ siteName: "Efferd",
147
+ source: "efferd",
148
+ registries: [
149
+ {
150
+ scope: "@efferd",
151
+ path: "base-luma/{name}.json",
152
+ headers: { Authorization: "Bearer ${EFFERD_REGISTRY_TOKEN}" },
153
+ },
154
+ ],
155
+ env: [{ name: "EFFERD_REGISTRY_TOKEN", from: "cliKey" }],
156
+ shadcnUiMcp: true,
157
+ verify: ["@efferd/logo-cloud-6"],
158
+ },
159
+ {
160
+ site: "magic",
161
+ siteName: "MagicUI",
162
+ source: "magicui",
163
+ registries: [
164
+ {
165
+ scope: "@magicui-pro",
166
+ headers: { Authorization: "Bearer ${MAGICUI_PRO_REGISTRY_TOKEN}" },
167
+ },
168
+ ],
169
+ env: [{ name: "MAGICUI_PRO_REGISTRY_TOKEN", from: "cliKey" }],
170
+ shadcnUiMcp: true,
171
+ verify: ["@magicui-pro/pricing-1"],
172
+ },
173
+ {
174
+ site: "bits",
175
+ siteName: "React Bits",
176
+ source: "reactbits",
177
+ registries: [
178
+ {
179
+ scope: "@reactbits-starter",
180
+ path: "starter/{name}.json",
181
+ headers: { Authorization: "Bearer ${REACTBITS_LICENSE_KEY}" },
182
+ },
183
+ {
184
+ scope: "@reactbits-pro",
185
+ path: "pro/{name}.json",
186
+ headers: { Authorization: "Bearer ${REACTBITS_LICENSE_KEY}" },
187
+ },
188
+ ],
189
+ env: [{ name: "REACTBITS_LICENSE_KEY", from: "cliKey" }],
190
+ mcp: "reactbits",
191
+ shadcnUiMcp: true,
192
+ verify: ["@reactbits-pro/profile-3"],
193
+ },
194
+ {
195
+ site: "reui",
196
+ siteName: "ReUI",
197
+ source: "reui",
198
+ registries: [
199
+ {
200
+ scope: "@reui",
201
+ path: "default/{name}.json",
202
+ headers: { Authorization: "Bearer ${REUI_LICENSE_KEY}" },
203
+ },
204
+ ],
205
+ env: [{ name: "REUI_LICENSE_KEY", from: "cliKey" }],
206
+ mcp: "reui",
207
+ verify: ["@reui/data-grid"],
208
+ },
209
+ {
210
+ site: "blocks",
211
+ siteName: "Shadcnblocks",
212
+ source: "shadcnblocks",
213
+ registries: [
214
+ {
215
+ scope: "@shadcnblocks",
216
+ headers: { Authorization: "Bearer ${SHADCNBLOCKS_API_KEY}" },
217
+ },
218
+ ],
219
+ env: [{ name: "SHADCNBLOCKS_API_KEY", from: "cliKey" }],
220
+ shadcnUiMcp: true,
221
+ verify: ["@shadcnblocks/hero18"],
222
+ },
223
+ {
224
+ site: "space",
225
+ siteName: "ShadcnSpace",
226
+ source: "shadcn-space",
227
+ registries: [
228
+ {
229
+ scope: "@shadcn-space",
230
+ params: {
231
+ email: "${SHADCN_SPACE_EMAIL}",
232
+ license_key: "${SHADCN_SPACE_LICENSE_KEY}",
233
+ },
234
+ },
235
+ ],
236
+ env: [
237
+ { name: "SHADCN_SPACE_LICENSE_KEY", from: "cliKey" },
238
+ { name: "SHADCN_SPACE_EMAIL", value: "anything@example.com" },
239
+ ],
240
+ mcp: "space",
241
+ verify: ["@shadcn-space/hero-01"],
242
+ },
243
+ {
244
+ site: "studio",
245
+ siteName: "Shadcnstudio",
246
+ source: "shadcnstudio",
247
+ registries: [
248
+ // registry 要求凭 key(免费层 2026-11-02 退役)+ {style} 前缀(上游 API 改版)。
249
+ // style 钉 new-york-v4(不依赖 components.json 的 style 字段);有效值见
250
+ // 上游 Invalid style 报错列表(radix-vega / base-nova 等 17 种)。
251
+ {
252
+ scope: "@shadcn-studio",
253
+ path: "new-york-v4/{name}.json",
254
+ params: { email: "${EMAIL}", license_key: "${LICENSE_KEY}" },
255
+ },
256
+ {
257
+ scope: "@ss-components",
258
+ path: "components/new-york-v4/{name}.json",
259
+ params: { email: "${EMAIL}", license_key: "${LICENSE_KEY}" },
260
+ },
261
+ {
262
+ scope: "@ss-blocks",
263
+ path: "blocks/new-york-v4/{name}.json",
264
+ params: { email: "${EMAIL}", license_key: "${LICENSE_KEY}" },
265
+ },
266
+ {
267
+ scope: "@ss-themes",
268
+ path: "themes/{name}.json",
269
+ params: { email: "${EMAIL}", license_key: "${LICENSE_KEY}" },
270
+ },
271
+ ],
272
+ env: [
273
+ { name: "LICENSE_KEY", from: "cliKey" },
274
+ { name: "EMAIL", value: "studio@collectui.pro" },
275
+ ],
276
+ mcp: "shadcnstudio",
277
+ verify: ["@shadcn-studio/button-01"],
278
+ freeVerify: ["@shadcn-studio/button-01"],
279
+ },
280
+ {
281
+ site: "uikit",
282
+ siteName: "Shadcn UI Kit",
283
+ source: "shadcnuikit",
284
+ registries: [
285
+ {
286
+ scope: "@shadcnuikit",
287
+ headers: { Authorization: "Bearer ${SHADCNUKIT_REGISTRY_TOKEN}" },
288
+ },
289
+ ],
290
+ env: [{ name: "SHADCNUKIT_REGISTRY_TOKEN", from: "cliKey" }],
291
+ mcp: "uikit",
292
+ verify: ["@shadcnuikit/hero2"],
293
+ },
294
+ {
295
+ site: "motion",
296
+ siteName: "Motion",
297
+ source: "motion",
298
+ registries: [
299
+ { scope: "@motion", headers: { Authorization: "Bearer ${MOTION_TOKEN}" } },
300
+ ],
301
+ env: [{ name: "MOTION_TOKEN", from: "cliKey" }],
302
+ mcp: "motion-plus",
303
+ verify: ["@motion/hero-parallax-layers"],
304
+ },
305
+ {
306
+ site: "21st",
307
+ siteName: "21st",
308
+ source: "21st",
309
+ registries: [
310
+ { scope: "@21st", headers: { Authorization: "Bearer ${API_KEY_21ST}" } },
311
+ ],
312
+ env: [{ name: "API_KEY_21ST", from: "cliKey" }],
313
+ mcp: "21st",
314
+ cliTool: { package: "@collectui/21st", forkOf: "@21st-dev/cli" },
315
+ verify: ["@21st/shugar/button-1"],
316
+ },
317
+ ];
318
+
319
+ /**
320
+ * 按 slug/别名找库。
321
+ * @param {string} slug
322
+ * @returns {any}
323
+ */
324
+ export function libBySlug(slug) {
325
+ const needle = String(slug || "").toLowerCase();
326
+ for (const lib of LIBS) {
327
+ if (lib.site.toLowerCase() === needle) return lib;
328
+ if (lib.source && lib.source.toLowerCase() === needle) return lib;
329
+ }
330
+ return null;
331
+ }
332
+
333
+ export function allSlugs() {
334
+ return LIBS.map((lib) => lib.site);
335
+ }
336
+
337
+ /** 用户拥有的库(site 授权或已绑定任意 key)。 */
338
+ export function ownedLibs(me) {
339
+ const sites = new Set((me?.sites ?? []).map((s) => s.slug));
340
+ const keySites = new Set((me?.keys ?? []).map((k) => k.site).filter(Boolean));
341
+ return LIBS.filter((lib) => sites.has(lib.site) || keySites.has(lib.site));
342
+ }
343
+
344
+ export function keyEntriesFor(me, site) {
345
+ return (me?.keys ?? []).filter((k) => k.site === site);
346
+ }
347
+
348
+ export function resolveLibKeys(lib, me) {
349
+ const entries = keyEntriesFor(me, lib.site);
350
+ const cli = entries.find((k) => k.kind === "cli")?.key ?? entries.find((k) => k.kind !== "mcp")?.key ?? null;
351
+ const mcp = entries.find((k) => k.kind === "mcp")?.key ?? null;
352
+ return { cli, mcp, entries };
353
+ }
354
+
355
+ export function registryUrl(source, registry, base) {
356
+ const path = registry.path ?? "{name}.json";
357
+ return `${base.replace(/\/+$/, "")}/api/r/${source}/${path}`;
358
+ }
359
+
360
+ /** components.json 的 registries 值:无认证字段时用字符串简写(与 Dash 同款)。 */
361
+ export function registryEntry(registry, source, base) {
362
+ const url = registryUrl(source, registry, base);
363
+ if (!(registry.headers || registry.params)) return url;
364
+ const entry = { url };
365
+ if (registry.headers) entry.headers = { ...registry.headers };
366
+ if (registry.params) entry.params = { ...registry.params };
367
+ return entry;
368
+ }
369
+
370
+ export function envValue(env, cliKey) {
371
+ return env.from === "cliKey" ? (cliKey ?? "") : (env.value ?? "");
372
+ }
373
+
374
+ /** MCP 产品定义;未知 id 返回 null(配置时跳过并报告)。 */
375
+ export function mcpProduct(id) {
376
+ return id ? MCP_PRODUCTS[id] ?? null : null;
377
+ }
378
+
379
+ /** 配置单元:目录里每个库就是一个单元(保留导出供调用方按库遍历)。 */
380
+ /**
381
+ * @param {any[]} libs
382
+ * @returns {any[]}
383
+ */
384
+ export function configUnits(libs) {
385
+ return [...libs];
386
+ }
@@ -0,0 +1,311 @@
1
+ import { spawn } from "node:child_process";
2
+ import {
3
+ chmodSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ statSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import { dirname, relative } from "node:path";
11
+ import { CliError } from "./errors.mjs";
12
+
13
+ /**
14
+ * ChangeSet:所有写操作先落到内存,最后统一展示 + 应用。
15
+ * 这是「每一步动作都透明」的载体——dry-run 能打印完整计划,正常执行也逐条
16
+ * 输出 created/updated/unchanged、命令与结果;任何密钥都经 reporter 脱敏。
17
+ */
18
+ export class ChangeSet {
19
+ constructor({ reporter, dryRun = false, yes = false, root = process.cwd() }) {
20
+ this.reporter = reporter;
21
+ this.dryRun = dryRun;
22
+ this.yes = yes;
23
+ this.root = root;
24
+ this.files = new Map(); // abs -> {original, content, summary, mode, changes}
25
+ this.dirs = new Set();
26
+ this.runs = [];
27
+ this.gitRepos = new Set();
28
+ }
29
+
30
+ rel(path) {
31
+ const r = relative(process.cwd(), path);
32
+ return r && !r.startsWith("..") ? r : path;
33
+ }
34
+
35
+ read(path) {
36
+ if (this.files.has(path)) return this.files.get(path).content;
37
+ try {
38
+ return readFileSync(path, "utf8");
39
+ } catch {
40
+ return null;
41
+ }
42
+ }
43
+
44
+ exists(path) {
45
+ if (this.files.has(path)) return this.files.get(path).content !== null;
46
+ return existsSync(path);
47
+ }
48
+
49
+ readJson(path, fallback) {
50
+ const text = this.read(path);
51
+ if (text === null) return fallback;
52
+ try {
53
+ return JSON.parse(text);
54
+ } catch (error) {
55
+ throw new CliError(`Cannot parse ${path}: ${error.message}`, {
56
+ hint: "Fix the file (or remove it) and retry; CollectUI never overwrites an unparseable config.",
57
+ });
58
+ }
59
+ }
60
+
61
+ /** 写文件;content 为 null 表示删除(暂未用)。 */
62
+ write(path, content, { summary, mode, changes = [] } = {}) {
63
+ const existing = this.files.get(path);
64
+ const original = existing ? existing.original : this.read(path);
65
+ this.files.set(path, {
66
+ original,
67
+ content,
68
+ summary: summary ?? (original === null ? "create file" : "update file"),
69
+ mode,
70
+ changes,
71
+ });
72
+ return this;
73
+ }
74
+
75
+ mkdir(path) {
76
+ this.dirs.add(path);
77
+ return this;
78
+ }
79
+
80
+ run(command, args, { cwd = this.root, env = {}, summary, quiet = false } = {}) {
81
+ this.runs.push({ command, args, cwd, env, summary: summary ?? `${command} ${args.join(" ")}`, quiet });
82
+ return this;
83
+ }
84
+
85
+ gitInit(cwd = this.root) {
86
+ this.gitRepos.add(cwd);
87
+ return this;
88
+ }
89
+
90
+ /** 只返回真正有变化的文件。 */
91
+ pendingFiles() {
92
+ const out = [];
93
+ for (const [path, item] of this.files) {
94
+ if (item.original === item.content) continue;
95
+ out.push({
96
+ path,
97
+ ...item,
98
+ status: item.original === null ? "created" : "updated",
99
+ });
100
+ }
101
+ return out;
102
+ }
103
+
104
+ async plan() {
105
+ const files = this.pendingFiles();
106
+ const dirs = [...this.dirs].filter((d) => !existsSync(d));
107
+ const plans = [];
108
+
109
+ for (const dir of dirs) {
110
+ plans.push({
111
+ kind: "mkdir",
112
+ path: dir,
113
+ summary: "create directory",
114
+ status: "planned",
115
+ });
116
+ }
117
+ for (const file of files) {
118
+ plans.push({
119
+ kind: "write",
120
+ path: file.path,
121
+ summary: file.summary,
122
+ status: file.original === null ? "created" : "updated",
123
+ changes: file.changes,
124
+ });
125
+ }
126
+ for (const repo of this.gitRepos) {
127
+ plans.push({ kind: "git-init", path: repo, summary: "git init (project baseline)" });
128
+ }
129
+ for (const run of this.runs) {
130
+ plans.push({
131
+ kind: "run",
132
+ command: [run.command, ...run.args].join(" "),
133
+ path: run.cwd,
134
+ summary: run.summary,
135
+ });
136
+ }
137
+ return plans;
138
+ }
139
+
140
+ async preview() {
141
+ const plans = await this.plan();
142
+ if (plans.length === 0) {
143
+ this.reporter.info("No changes — everything is already configured.");
144
+ return false;
145
+ }
146
+ for (const item of plans) {
147
+ this.reporter.action(item);
148
+ }
149
+ if (this.reporter.verbose || this.dryRun) {
150
+ for (const file of this.pendingFiles()) {
151
+ if (file.original === null) {
152
+ this.reporter.preview(`new file · ${this.rel(file.path)}`, truncate(file.content));
153
+ } else {
154
+ this.reporter.preview(`updated · ${this.rel(file.path)}`, previewUpdate(file.original, file.content));
155
+ }
156
+ }
157
+ }
158
+ return true;
159
+ }
160
+
161
+ async apply() {
162
+ const plans = await this.plan();
163
+ if (plans.length === 0) {
164
+ this.reporter.info("No changes — everything is already configured.");
165
+ return { files: [], runs: [], skipped: true };
166
+ }
167
+
168
+ if (this.dryRun) {
169
+ for (const item of plans) this.reporter.action({ ...item, status: "planned" });
170
+ for (const file of this.pendingFiles()) {
171
+ if (this.reporter.verbose || this.dryRun) {
172
+ this.reporter.preview(
173
+ `${file.original === null ? "new" : "updated"} · ${this.rel(file.path)}`,
174
+ file.original === null ? truncate(file.content) : previewUpdate(file.original, file.content)
175
+ );
176
+ }
177
+ }
178
+ this.reporter.info(`Dry run: ${plans.length} action(s) would be applied. Nothing was written.`);
179
+ return { files: this.pendingFiles(), runs: [], dryRun: true };
180
+ }
181
+
182
+ if (!this.reporter.json) {
183
+ this.reporter.note(
184
+ "Plan",
185
+ plans
186
+ .map((p) => `- ${p.kind}${p.path ? ` ${this.rel(p.path)}` : ""}${p.summary ? ` — ${p.summary}` : ""}`)
187
+ .join("\n")
188
+ );
189
+ }
190
+
191
+ const ok = await this.reporter.confirm(
192
+ `Apply ${plans.length} action(s) to ${this.root}?`,
193
+ { defaultValue: true }
194
+ );
195
+ if (!ok) {
196
+ this.reporter.info("Aborted.");
197
+ return { files: [], runs: [], aborted: true };
198
+ }
199
+
200
+ for (const dir of [...this.dirs]) {
201
+ if (!existsSync(dir)) {
202
+ mkdirSync(dir, { recursive: true, mode: 0o755 });
203
+ this.reporter.action({ kind: "mkdir", path: this.rel(dir), summary: "create directory", status: "created" });
204
+ }
205
+ }
206
+
207
+ const written = [];
208
+ for (const file of this.pendingFiles()) {
209
+ mkdirSync(dirname(file.path), { recursive: true });
210
+ writeFileSync(file.path, file.content, { mode: file.mode ?? 0o644 });
211
+ if (file.mode) {
212
+ try {
213
+ chmodSync(file.path, file.mode);
214
+ } catch {
215
+ // Windows 权限位不可用
216
+ }
217
+ }
218
+ written.push(file);
219
+ this.reporter.action({
220
+ kind: "write",
221
+ path: this.rel(file.path),
222
+ summary: file.summary,
223
+ status: file.status,
224
+ changes: file.changes,
225
+ });
226
+ }
227
+
228
+ for (const repo of this.gitRepos) {
229
+ if (isGitRepo(repo)) {
230
+ this.reporter.action({ kind: "git-init", path: this.rel(repo), summary: "already a git repo (skipped)", status: "unchanged" });
231
+ continue;
232
+ }
233
+ await exec("git", ["init", "-q"], { cwd: repo });
234
+ this.reporter.action({ kind: "git-init", path: this.rel(repo), summary: "git initialized", status: "created" });
235
+ }
236
+
237
+ for (const run of this.runs) {
238
+ this.reporter.action({
239
+ kind: "run",
240
+ command: [run.command, ...run.args].join(" "),
241
+ path: this.rel(run.cwd),
242
+ summary: run.summary,
243
+ status: "running",
244
+ });
245
+ const code = await exec(run.command, run.args, {
246
+ cwd: run.cwd,
247
+ env: { ...process.env, ...run.env },
248
+ quiet: run.quiet,
249
+ });
250
+ if (code !== 0) {
251
+ throw new CliError(
252
+ `Command failed (exit ${code}): ${[run.command, ...run.args].join(" ")}`,
253
+ { hint: "The files already written stay in place; fix the issue and re-run the same command (idempotent)." }
254
+ );
255
+ }
256
+ this.reporter.action({
257
+ kind: "run",
258
+ command: [run.command, ...run.args].join(" "),
259
+ path: this.rel(run.cwd),
260
+ summary: "command completed",
261
+ status: "created",
262
+ });
263
+ }
264
+
265
+ return { files: written, runs: this.runs, dryRun: false };
266
+ }
267
+ }
268
+
269
+ function exec(command, args, { cwd, env, quiet = false }) {
270
+ return new Promise((resolve, reject) => {
271
+ const isJson = process.env.COLLECTUI_JSON === "1";
272
+ const child = spawn(command, args, {
273
+ cwd,
274
+ env,
275
+ stdio: isJson || quiet ? ["ignore", 2, 2] : "inherit",
276
+ });
277
+ child.on("error", (error) => {
278
+ reject(new CliError(`Cannot run ${command}: ${error.message}`, {
279
+ hint: "Make sure the command exists and is on PATH.",
280
+ }));
281
+ });
282
+ child.on("exit", (code) => resolve(code ?? 1));
283
+ });
284
+ }
285
+
286
+ function isGitRepo(cwd) {
287
+ try {
288
+ statSync(`${cwd}/.git`);
289
+ return true;
290
+ } catch {
291
+ return false;
292
+ }
293
+ }
294
+
295
+ function truncate(content, max = 80) {
296
+ const lines = String(content).split("\n");
297
+ if (lines.length <= max) return String(content);
298
+ return `${lines.slice(0, max).join("\n")}\n… (${lines.length - max} more line(s))`;
299
+ }
300
+
301
+ function previewUpdate(before, after) {
302
+ const a = new Set(String(before).split("\n"));
303
+ const b = new Set(String(after).split("\n"));
304
+ const removed = [...a].filter((line) => line && !b.has(line)).slice(0, 12);
305
+ const added = [...b].filter((line) => line && !a.has(line)).slice(0, 20);
306
+ const parts = [];
307
+ if (removed.length) parts.push(...removed.map((line) => `- ${line}`));
308
+ if (added.length) parts.push(...added.map((line) => `+ ${line}`));
309
+ if (parts.length === 0) return "(content unchanged)";
310
+ return parts.join("\n");
311
+ }