@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.
package/src/mcp.mjs ADDED
@@ -0,0 +1,389 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ import { CliError } from "./errors.mjs";
4
+ import { MCP_PRODUCTS, SHADCN_MCP, mcpProduct, resolveLibKeys } from "./catalog.mjs";
5
+
6
+ /**
7
+ * MCP 配置生成与合并。
8
+ *
9
+ * 合并规则(需求「没配置、或配置的是官方才动」):
10
+ * - 缺失 → 添加
11
+ * - 完全一致 → 跳过
12
+ * - 同一端点但 token 不同 → 刷新 token(视为自己的条目)
13
+ * - 官方 shadcn 通用 MCP 占位 → 换成该库的专属 MCP
14
+ * - 其它自定义配置 → 保留(除非 --force),并明确报告
15
+ *
16
+ * 密钥只写入用户自己的配置文件;日志里全部脱敏。
17
+ */
18
+
19
+ export const CLIENT_FILES = {
20
+ claude: { root: "mcpServers", file: ".mcp.json", type: true },
21
+ cursor: { root: "mcpServers", file: ".cursor/mcp.json", type: false },
22
+ vscode: { root: "servers", file: ".vscode/mcp.json", type: true },
23
+ codex: { root: null, file: null, type: false },
24
+ };
25
+
26
+ export function mcpConfigPath(client, { projectDir, codexHome } = {}) {
27
+ if (client === "codex") {
28
+ const home = codexHome || process.env.CODEX_HOME || join(homedir(), ".codex");
29
+ return join(home, "config.toml");
30
+ }
31
+ const spec = CLIENT_FILES[client];
32
+ if (!spec) throw new CliError(`Unknown MCP client: ${client}`);
33
+ return join(projectDir, spec.file);
34
+ }
35
+
36
+ /** 组装要写入的 MCP server 条目(canonical 形态,渲染时按 client 变形)。 */
37
+ export function buildMcpEntries({ units, me, dashToken, registryBase, dashBase, includeDash = true, reporter }) {
38
+ const entries = [];
39
+ let needsShadcn = false;
40
+
41
+ for (const unit of units) {
42
+ if (!unit.mcp) {
43
+ if (unit.shadcnUiMcp) needsShadcn = true;
44
+ continue;
45
+ }
46
+ const product = mcpProduct(unit.mcp);
47
+ if (!product) {
48
+ reporter?.warn(`MCP product "${unit.mcp}" is not in the catalog; skipped.`);
49
+ continue;
50
+ }
51
+ const key = resolveLibKeys(unit, me).mcp;
52
+ if (!key) {
53
+ reporter?.warn(
54
+ `No MCP key bound for ${unit.siteName}; its MCP server was skipped (CLI/registry config is unaffected).`
55
+ );
56
+ continue;
57
+ }
58
+ if (product.kind === "http") {
59
+ entries.push({
60
+ kind: "http",
61
+ serverName: product.serverName ?? product.id,
62
+ url: `${registryBase.replace(/\/+$/, "")}${product.endpointPath}`,
63
+ headers: { Authorization: `Bearer ${key}` },
64
+ site: unit.site,
65
+ product: product.id,
66
+ key,
67
+ });
68
+ } else if (product.kind === "stdio") {
69
+ entries.push({
70
+ kind: "stdio",
71
+ serverName: product.serverName ?? product.id,
72
+ packageName: product.packageName,
73
+ env: { API_KEY: key, ...(product.extraEnv ?? {}) },
74
+ site: unit.site,
75
+ product: product.id,
76
+ key,
77
+ });
78
+ }
79
+ if (unit.shadcnUiMcp) needsShadcn = true;
80
+ }
81
+
82
+ if (needsShadcn) {
83
+ entries.push({
84
+ kind: "stdio",
85
+ serverName: SHADCN_MCP.serverName,
86
+ packageName: null,
87
+ command: SHADCN_MCP.command,
88
+ args: SHADCN_MCP.args,
89
+ env: {},
90
+ site: null,
91
+ product: "shadcn",
92
+ key: null,
93
+ });
94
+ }
95
+
96
+ if (includeDash) {
97
+ if (dashToken) {
98
+ entries.push({
99
+ kind: "http",
100
+ serverName: "collectui-dash",
101
+ url: `${dashBase.replace(/\/+$/, "")}/api/mcp`,
102
+ headers: { Authorization: `Bearer ${dashToken}` },
103
+ site: null,
104
+ product: "dash",
105
+ key: dashToken,
106
+ });
107
+ } else {
108
+ reporter?.warn("No Dash PAT; collectui-dash MCP was skipped. Run `collectui login` to add it.");
109
+ }
110
+ }
111
+
112
+ return dedupe(entries);
113
+ }
114
+
115
+ function dedupe(entries) {
116
+ const map = new Map();
117
+ for (const entry of entries) map.set(entry.serverName, entry);
118
+ return [...map.values()];
119
+ }
120
+
121
+ export function renderEntry(entry, client) {
122
+ const spec = CLIENT_FILES[client];
123
+ if (entry.kind === "http") {
124
+ const base = { url: entry.url, headers: { ...entry.headers } };
125
+ if (spec?.type) return { type: "http", ...base };
126
+ return base;
127
+ }
128
+ // stdio
129
+ const args = entry.args ?? ["-y", `${entry.packageName}@latest`];
130
+ if (entry.command && !entry.packageName) {
131
+ const value = { command: entry.command, args: [...args] };
132
+ if (spec?.type) return { type: "stdio", ...value };
133
+ return value;
134
+ }
135
+ const envPairs = Object.entries(entry.env ?? {}).map(([k, v]) => `${k}=${v}`);
136
+ if (client === "vscode") {
137
+ return {
138
+ type: "stdio",
139
+ command: "npx",
140
+ args,
141
+ env: { ...entry.env },
142
+ };
143
+ }
144
+ const value = { command: "npx", args: [...args, ...envPairs] };
145
+ if (spec?.type) return { type: "stdio", ...value };
146
+ return value;
147
+ }
148
+
149
+ export function isOfficialShadcnServer(name, value) {
150
+ if (!value || typeof value !== "object") return name === "shadcn" && value == null;
151
+ const cmd = String(value.command ?? "");
152
+ const args = Array.isArray(value.args) ? value.args.map(String) : [];
153
+ const url = String(value.url ?? "");
154
+ const looksOfficial =
155
+ cmd.includes("shadcn@") ||
156
+ args.some((a) => a.startsWith("shadcn@") || a === "shadcn") ||
157
+ /(^https?:\/\/)?(ui\.)?shadcn\.com\//i.test(url);
158
+ // 只有「名字是 shadcn 且内容确实官方」才视为可替换;同名的自定义条目保留
159
+ return looksOfficial || (name === "shadcn" && !cmd && !args.length && !url);
160
+ }
161
+
162
+ function sameServer(a, b) {
163
+ return JSON.stringify(sort(a)) === JSON.stringify(sort(b));
164
+ }
165
+
166
+ function sort(value) {
167
+ if (Array.isArray(value)) return value.map(sort);
168
+ if (value && typeof value === "object") {
169
+ return Object.fromEntries(Object.keys(value).sort().map((k) => [k, sort(value[k])]));
170
+ }
171
+ return value;
172
+ }
173
+
174
+ function isOurs(existing, entry) {
175
+ if (entry.kind === "http") {
176
+ return existing && existing.url === entry.url;
177
+ }
178
+ if (entry.packageName) {
179
+ const args = Array.isArray(existing?.args) ? existing.args.join(" ") : "";
180
+ return args.includes(entry.packageName);
181
+ }
182
+ if (entry.command && entry.args) {
183
+ const args = Array.isArray(existing?.args) ? existing.args.join(" ") : "";
184
+ return existing?.command === entry.command && args.includes(entry.args.join(" "));
185
+ }
186
+ return false;
187
+ }
188
+
189
+ const ROOT_KEY = { claude: "mcpServers", cursor: "mcpServers", vscode: "servers" };
190
+
191
+ /** JSON 型 MCP 配置合并(.mcp.json / .cursor/mcp.json / .vscode/mcp.json)。 */
192
+ export function mergeJsonConfig(text, client, entries, { force = false } = {}) {
193
+ const rootKey = ROOT_KEY[client];
194
+ if (!rootKey) throw new CliError(`Unknown MCP client: ${client}`);
195
+ let config = {};
196
+ if (text && text.trim()) {
197
+ try {
198
+ config = JSON.parse(text);
199
+ } catch (error) {
200
+ throw new CliError(`Cannot parse ${client} MCP config: ${error.message}`, {
201
+ hint: "Fix the JSON (or pass --force only after backing it up) and retry.",
202
+ });
203
+ }
204
+ }
205
+ const root = { ...(config[rootKey] ?? {}) };
206
+ const decisions = [];
207
+
208
+ for (const entry of entries) {
209
+ const desired = renderEntry(entry, client);
210
+ const existing = root[entry.serverName];
211
+ if (existing === undefined) {
212
+ root[entry.serverName] = desired;
213
+ decisions.push({ server: entry.serverName, action: "added" });
214
+ continue;
215
+ }
216
+ if (sameServer(existing, desired)) {
217
+ decisions.push({ server: entry.serverName, action: "unchanged" });
218
+ continue;
219
+ }
220
+ if (isOurs(existing, entry) || isOfficialShadcnServer(entry.serverName, existing)) {
221
+ root[entry.serverName] = desired;
222
+ decisions.push({ server: entry.serverName, action: "updated" });
223
+ continue;
224
+ }
225
+ if (force) {
226
+ root[entry.serverName] = desired;
227
+ decisions.push({ server: entry.serverName, action: "replaced" });
228
+ continue;
229
+ }
230
+ decisions.push({ server: entry.serverName, action: "kept-custom" });
231
+ }
232
+
233
+ const next = { ...config, [rootKey]: root };
234
+ return { text: `${JSON.stringify(next, null, 2)}\n`, decisions };
235
+ }
236
+
237
+ function tomlSectionName(name) {
238
+ return /^[A-Za-z0-9_-]+$/.test(name) ? name : JSON.stringify(name);
239
+ }
240
+
241
+ function tomlValue(value) {
242
+ return JSON.stringify(value);
243
+ }
244
+
245
+ function renderToml(entry) {
246
+ if (entry.kind === "http") {
247
+ return [
248
+ `[mcp_servers.${tomlSectionName(entry.serverName)}]`,
249
+ `url = ${tomlValue(entry.url)}`,
250
+ `http_headers = { Authorization = ${tomlValue(entry.headers.Authorization)} }`,
251
+ ].join("\n");
252
+ }
253
+ const args = entry.args ?? ["-y", `${entry.packageName}@latest`];
254
+ const envPairs = Object.entries(entry.env ?? {}).map(([k, v]) => `${k}=${v}`);
255
+ const allArgs = [...args, ...envPairs];
256
+ if (entry.command && !entry.packageName) {
257
+ return [
258
+ `[mcp_servers.${tomlSectionName(entry.serverName)}]`,
259
+ `command = ${tomlValue(entry.command)}`,
260
+ `args = ${tomlValue(allArgs)}`,
261
+ ].join("\n");
262
+ }
263
+ return [
264
+ `[mcp_servers.${tomlSectionName(entry.serverName)}]`,
265
+ `command = "npx"`,
266
+ `args = ${tomlValue(allArgs)}`,
267
+ ].join("\n");
268
+ }
269
+
270
+ /** Codex config.toml 合并:按 [mcp_servers.<name>] 段落追加/更新,其它段落原样保留。 */
271
+ export function mergeCodexToml(text, entries, { force = false } = {}) {
272
+ let content = text ?? "";
273
+ const decisions = [];
274
+ for (const entry of entries) {
275
+ const section = renderToml(entry);
276
+ const header = `[mcp_servers.${tomlSectionName(entry.serverName)}]`;
277
+ const start = content.indexOf(header);
278
+ if (start === -1) {
279
+ content = `${content.replace(/\s*$/, "")}${content.trim() ? "\n\n" : ""}${section}\n`;
280
+ decisions.push({ server: entry.serverName, action: "added" });
281
+ continue;
282
+ }
283
+ const afterHeader = content.indexOf("\n[", start + header.length);
284
+ const end = afterHeader === -1 ? content.length : afterHeader + 1;
285
+ const existing = content.slice(start, end).trim();
286
+ if (existing === section.trim()) {
287
+ decisions.push({ server: entry.serverName, action: "unchanged" });
288
+ continue;
289
+ }
290
+ const ours = entry.kind === "http" ? existing.includes(entry.url) : existing.includes(entry.packageName ?? entry.command ?? "");
291
+ if (ours || force) {
292
+ content = `${content.slice(0, start)}${section}\n${content.slice(end).replace(/^\n/, "")}`;
293
+ decisions.push({ server: entry.serverName, action: "updated" });
294
+ continue;
295
+ }
296
+ decisions.push({ server: entry.serverName, action: "kept-custom" });
297
+ }
298
+ return { text: content.endsWith("\n") ? content : `${content}\n`, decisions };
299
+ }
300
+
301
+ export function planMcpConfig(cs, {
302
+ projectDir,
303
+ units,
304
+ me,
305
+ dashToken,
306
+ registryBase,
307
+ dashBase,
308
+ clients,
309
+ force,
310
+ includeDash,
311
+ codexHome,
312
+ reporter,
313
+ }) {
314
+ const entries = buildMcpEntries({
315
+ units,
316
+ me,
317
+ dashToken,
318
+ registryBase,
319
+ dashBase,
320
+ includeDash,
321
+ reporter,
322
+ });
323
+ if (entries.length === 0) {
324
+ reporter?.warn("No MCP servers to configure (no bound MCP keys and no Dash PAT).");
325
+ return { entries, decisions: [] };
326
+ }
327
+ if (entries.some((entry) => entry.key)) {
328
+ reporter?.warn(
329
+ "MCP configs contain access tokens — keep .mcp.json, .cursor/mcp.json and .vscode/mcp.json out of git."
330
+ );
331
+ }
332
+
333
+ const allDecisions = [];
334
+ for (const client of clients) {
335
+ const path = mcpConfigPath(client, { projectDir, codexHome });
336
+ if (client === "codex") {
337
+ const before = cs.read(path) ?? "";
338
+ const { text, decisions } = mergeCodexToml(before, entries, { force });
339
+ if (text !== before) {
340
+ cs.mkdir(join(path, ".."));
341
+ cs.write(path, text, {
342
+ summary: "configure Codex MCP servers",
343
+ changes: decisions.map((d) => `${d.action}: ${d.server}`),
344
+ });
345
+ }
346
+ allDecisions.push({ client, path, decisions });
347
+ reporter?.info(`MCP (codex): ${summarize(decisions)}`);
348
+ continue;
349
+ }
350
+
351
+ const before = cs.read(path) ?? "";
352
+ const { text, decisions } = mergeJsonConfig(before, client, entries, { force });
353
+ if (text !== before) {
354
+ cs.write(path, text, {
355
+ summary: `configure ${client} MCP servers`,
356
+ mode: 0o600,
357
+ changes: decisions.map((d) => `${d.action}: ${d.server}`),
358
+ });
359
+ }
360
+ allDecisions.push({ client, path, decisions });
361
+ reporter?.info(`MCP (${client}): ${summarize(decisions)}`);
362
+ }
363
+
364
+ return { entries, decisions: allDecisions };
365
+ }
366
+
367
+ function summarize(decisions) {
368
+ if (!decisions.length) return "nothing to change.";
369
+ const counts = {};
370
+ for (const d of decisions) counts[d.action] = (counts[d.action] ?? 0) + 1;
371
+ return Object.entries(counts)
372
+ .map(([action, n]) => `${n} ${action}`)
373
+ .join(", ");
374
+ }
375
+
376
+ /** 给人类看的 MCP server 清单(不含密钥)。 */
377
+ export function describeEntries(entries) {
378
+ return entries.map((entry) => {
379
+ if (entry.kind === "http") {
380
+ return `- ${entry.serverName}: HTTP ${entry.url}${entry.key ? " (key bound)" : ""}`;
381
+ }
382
+ if (entry.packageName) {
383
+ return `- ${entry.serverName}: stdio npx -y ${entry.packageName}${entry.key ? " (key bound)" : ""}`;
384
+ }
385
+ return `- ${entry.serverName}: stdio ${entry.command} ${(entry.args ?? []).join(" ")}`;
386
+ });
387
+ }
388
+
389
+ export { MCP_PRODUCTS };
@@ -0,0 +1,258 @@
1
+ import { existsSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { CliError } from "./errors.mjs";
4
+ import { envValue, registryEntry, resolveLibKeys } from "./catalog.mjs";
5
+
6
+ /** 判断项目根:优先 components.json,其次 package.json(向上最多 4 层)。 */
7
+ export function detectProjectRoot(start = process.cwd()) {
8
+ let dir = resolve(start);
9
+ for (let i = 0; i < 5; i += 1) {
10
+ if (existsSync(join(dir, "components.json"))) return { root: dir, hasComponents: true };
11
+ if (existsSync(join(dir, "package.json"))) return { root: dir, hasComponents: false };
12
+ const parent = dirname(dir);
13
+ if (parent === dir) break;
14
+ dir = parent;
15
+ }
16
+ return { root: resolve(start), hasComponents: false };
17
+ }
18
+
19
+ export function detectPackageManager(root) {
20
+ if (existsSync(join(root, "pnpm-lock.yaml"))) return "pnpm";
21
+ if (existsSync(join(root, "yarn.lock"))) return "yarn";
22
+ if (existsSync(join(root, "bun.lockb")) || existsSync(join(root, "bun.lock"))) return "bun";
23
+ return "npm";
24
+ }
25
+
26
+ export function registryEntryEqual(a, b) {
27
+ const na = normalizeEntry(a);
28
+ const nb = normalizeEntry(b);
29
+ return JSON.stringify(sortObject(na)) === JSON.stringify(sortObject(nb));
30
+ }
31
+
32
+ export function isOfficialShadcn(value) {
33
+ if (typeof value === "string") return /(^https?:\/\/)?(ui\.)?shadcn\.com\//i.test(value);
34
+ if (value && typeof value === "object" && typeof value.url === "string") {
35
+ return isOfficialShadcn(value.url);
36
+ }
37
+ return false;
38
+ }
39
+
40
+ function normalizeEntry(value) {
41
+ if (typeof value === "string") return { url: value };
42
+ if (!value || typeof value !== "object") return { url: String(value) };
43
+ const out = { url: value.url };
44
+ if (value.headers) out.headers = { ...value.headers };
45
+ if (value.params) out.params = { ...value.params };
46
+ return out;
47
+ }
48
+
49
+ function sortObject(value) {
50
+ if (Array.isArray(value)) return value.map(sortObject);
51
+ if (value && typeof value === "object") {
52
+ return Object.fromEntries(
53
+ Object.keys(value)
54
+ .sort()
55
+ .map((key) => [key, sortObject(value[key])])
56
+ );
57
+ }
58
+ return value;
59
+ }
60
+
61
+ /**
62
+ * 合并 components.json 的 registries。
63
+ * 规则(对应需求「没配置或配置的是官方才配」):
64
+ * - 缺失 → 加
65
+ * - 已是同一配置 → 跳过
66
+ * - URL 相同但 token 不同 → 更新 token(视为自己的条目)
67
+ * - 官方 shadcn URL 或 --force → 替换
68
+ * - 其他自定义配置 → 保留并报告
69
+ */
70
+ export function mergeRegistries(components, units, { me, registryBase, force = false, onDecision }) {
71
+ const next = { ...components };
72
+ const current = components.registries && typeof components.registries === "object"
73
+ ? { ...components.registries }
74
+ : {};
75
+ const decisions = [];
76
+
77
+ for (const unit of units) {
78
+ if (!unit.registries?.length || !unit.source) continue;
79
+ const { cli: cliKey } = resolveLibKeys(unit, me);
80
+ for (const registry of unit.registries) {
81
+ const desired = registryEntry(registry, unit.source, registryBase);
82
+ const existing = current[registry.scope];
83
+ if (existing === undefined) {
84
+ current[registry.scope] = desired;
85
+ decisions.push({ scope: registry.scope, action: "added", site: unit.site });
86
+ continue;
87
+ }
88
+ if (registryEntryEqual(existing, desired)) {
89
+ decisions.push({ scope: registry.scope, action: "unchanged", site: unit.site });
90
+ continue;
91
+ }
92
+ const sameUrl =
93
+ normalizeEntry(existing).url === normalizeEntry(desired).url;
94
+ if (sameUrl) {
95
+ current[registry.scope] = desired;
96
+ decisions.push({ scope: registry.scope, action: "token-updated", site: unit.site });
97
+ continue;
98
+ }
99
+ if (force || isOfficialShadcn(existing)) {
100
+ current[registry.scope] = desired;
101
+ decisions.push({ scope: registry.scope, action: "replaced", site: unit.site });
102
+ continue;
103
+ }
104
+ decisions.push({ scope: registry.scope, action: "kept-custom", site: unit.site });
105
+ }
106
+ if (!cliKey) {
107
+ decisions.push({ scope: unit.source, action: "missing-cli-key", site: unit.site });
108
+ }
109
+ onDecision?.({ unit, cliKey });
110
+ }
111
+
112
+ if (Object.keys(current).length > 0) next.registries = current;
113
+ return { components: next, decisions };
114
+ }
115
+
116
+ /** 文本级 .env 合并:保留注释/顺序,不覆盖用户已有的不同值(除非 --force)。 */
117
+ export function mergeEnvText(text, envSpecs, { cliKey, force = false }) {
118
+ const lines = (text ?? "").split(/\r?\n/);
119
+ const existing = new Map();
120
+ for (const [index, line] of lines.entries()) {
121
+ const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(line);
122
+ if (m) existing.set(m[1], { index, value: m[2] });
123
+ }
124
+
125
+ const decisions = [];
126
+ for (const spec of envSpecs ?? []) {
127
+ const desired = envValue(spec, cliKey);
128
+ if (!desired) {
129
+ decisions.push({ name: spec.name, action: "missing-cli-key" });
130
+ continue;
131
+ }
132
+ const found = existing.get(spec.name);
133
+ if (!found) {
134
+ lines.push(`${spec.name}=${desired}`);
135
+ existing.set(spec.name, { index: lines.length - 1, value: desired });
136
+ decisions.push({ name: spec.name, action: "added" });
137
+ continue;
138
+ }
139
+ const currentValue = unquote(found.value);
140
+ if (currentValue === desired) {
141
+ decisions.push({ name: spec.name, action: "unchanged" });
142
+ continue;
143
+ }
144
+ if (force) {
145
+ lines[found.index] = `${spec.name}=${desired}`;
146
+ decisions.push({ name: spec.name, action: "updated" });
147
+ continue;
148
+ }
149
+ decisions.push({ name: spec.name, action: "kept-custom" });
150
+ }
151
+
152
+ let out = lines.join("\n");
153
+ if (!out.endsWith("\n")) out += "\n";
154
+ return { text: out, decisions };
155
+ }
156
+
157
+ export function readEnvValue(text, name) {
158
+ for (const line of String(text ?? "").split(/\r?\n/)) {
159
+ const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(line);
160
+ if (m && m[1] === name) return unquote(m[2]);
161
+ }
162
+ return null;
163
+ }
164
+
165
+ export function parseEnvText(text) {
166
+ const out = {};
167
+ for (const line of String(text ?? "").split(/\r?\n/)) {
168
+ const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(line);
169
+ if (m) out[m[1]] = unquote(m[2]);
170
+ }
171
+ return out;
172
+ }
173
+
174
+ function unquote(value) {
175
+ const v = String(value ?? "").trim();
176
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
177
+ return v.slice(1, -1);
178
+ }
179
+ return v;
180
+ }
181
+
182
+ /** 把 registry/env 配置写入 ChangeSet(components.json + .env.local)。 */
183
+ export function planProjectConfig(cs, { projectDir, units, me, registryBase, force, reporter }) {
184
+ const componentsPath = join(projectDir, "components.json");
185
+ if (!cs.exists(componentsPath)) {
186
+ throw new CliError(`No components.json in ${projectDir}.`, {
187
+ hint: "Run `collectui init` to scaffold a project, or point --cwd at an existing shadcn project.",
188
+ });
189
+ }
190
+ const before = cs.readJson(componentsPath, {});
191
+ const { components, decisions } = mergeRegistries(before, units, {
192
+ me,
193
+ registryBase,
194
+ force,
195
+ });
196
+
197
+ const changes = decisions.map((d) => `${d.action}: ${d.scope} (${d.site})`);
198
+ if (JSON.stringify(before) !== JSON.stringify(components)) {
199
+ cs.write(componentsPath, `${JSON.stringify(components, null, 2)}\n`, {
200
+ summary: "configure components.json registries",
201
+ changes,
202
+ });
203
+ }
204
+ reporter?.info(
205
+ summarizeDecisions("registries", decisions)
206
+ );
207
+
208
+ // .env.local:所有选中单元的 env(同一变量只写一次,先到先得)
209
+ const seen = new Set();
210
+ const envSpecs = [];
211
+ const envCliKey = new Map();
212
+ for (const unit of units) {
213
+ const { cli: cliKey } = resolveLibKeys(unit, me);
214
+ for (const spec of unit.env ?? []) {
215
+ if (seen.has(spec.name)) continue;
216
+ seen.add(spec.name);
217
+ envSpecs.push(spec);
218
+ if (spec.from === "cliKey") envCliKey.set(spec.name, cliKey);
219
+ }
220
+ }
221
+ if (envSpecs.length > 0) {
222
+ const envPath = join(projectDir, ".env.local");
223
+ const beforeEnv = cs.read(envPath) ?? "";
224
+ let text = beforeEnv;
225
+ const allDecisions = [];
226
+ for (const spec of envSpecs) {
227
+ const cliKey = envCliKey.get(spec.name) ?? null;
228
+ const merged = mergeEnvText(text, [spec], { cliKey, force });
229
+ text = merged.text;
230
+ allDecisions.push(...merged.decisions);
231
+ }
232
+ if (text !== beforeEnv) {
233
+ cs.write(envPath, text, {
234
+ summary: "write license keys to .env.local",
235
+ mode: 0o600,
236
+ changes: allDecisions.map((d) => `${d.action}: ${d.name}`),
237
+ });
238
+ }
239
+ reporter?.info(summarizeDecisions(".env.local", allDecisions));
240
+ }
241
+
242
+ // 缺失 CLI key 的库单独警告(registry 已写但安装会 401)
243
+ const missing = units.filter((u) => u.registries?.length && !resolveLibKeys(u, me).cli);
244
+ if (missing.length > 0) {
245
+ reporter?.warn(
246
+ `No CLI key bound for: ${missing.map((u) => u.siteName).join(", ")}. Registries are configured, but installs will 401 until a key is bound in Dash.`
247
+ );
248
+ }
249
+ }
250
+
251
+ function summarizeDecisions(label, decisions) {
252
+ if (!decisions.length) return `${label}: nothing to change.`;
253
+ const counts = {};
254
+ for (const d of decisions) counts[d.action] = (counts[d.action] ?? 0) + 1;
255
+ return `${label}: ${Object.entries(counts)
256
+ .map(([action, n]) => `${n} ${action}`)
257
+ .join(", ")}`;
258
+ }