@collectui/cli 0.0.0-stage → 0.2.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,155 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { LIBS, ownedLibs, registryUrl, resolveLibKeys } from "../catalog.mjs";
4
+ import { registryUrl as registryBase, resolveToken, tokenSource } from "../config.mjs";
5
+ import { httpRequest } from "../http.mjs";
6
+ import { dashMcpTools, fetchMe } from "../dash.mjs";
7
+ import { detectProjectRoot, parseEnvText } from "../project.mjs";
8
+ import { formatTable } from "../report.mjs";
9
+
10
+ export async function doctorCmd(flags, rest, reporter) {
11
+ const checks = [];
12
+ const add = (name, status, detail) => {
13
+ checks.push({ check: name, status, detail: detail ?? "" });
14
+ if (status === "fail") reporter.error(`${name}: ${detail}`);
15
+ else if (status === "warn") reporter.warn(`${name}: ${detail}`);
16
+ else reporter.success(`${name}: ${detail}`);
17
+ };
18
+
19
+ const nodeMajor = Number(process.versions.node.split(".")[0]);
20
+ add("node", nodeMajor >= 18 ? "ok" : "fail", `v${process.versions.node} (>=18.17 required)`);
21
+
22
+ const token = resolveToken(flags);
23
+ const source = tokenSource(flags);
24
+ add("credentials", token ? "ok" : "fail", token ? `PAT from ${source}` : "no PAT (run collectui login)");
25
+
26
+ let me = null;
27
+ if (token) {
28
+ try {
29
+ me = await fetchMe(token, { reporter });
30
+ add("account", "ok", `${me.account?.username ?? me.account?.uid} · ${me.sites?.length ?? 0} libraries`);
31
+ } catch (error) {
32
+ add("account", "fail", error.message);
33
+ }
34
+ }
35
+
36
+ if (token) {
37
+ try {
38
+ const tools = await dashMcpTools(token, { reporter });
39
+ add("dash-mcp", "ok", `${tools.length} tools: ${tools.map((t) => t.name).join(", ")}`);
40
+ } catch (error) {
41
+ const status = /404|not enabled/i.test(error.message) ? "warn" : "fail";
42
+ add("dash-mcp", status, error.message);
43
+ }
44
+ }
45
+
46
+ // 项目检查
47
+ const detected = detectProjectRoot(flags.cwd ? resolve(String(flags.cwd)) : process.cwd());
48
+ const root = detected.root;
49
+ const componentsPath = join(root, "components.json");
50
+ if (!existsSync(componentsPath)) {
51
+ add("project", "warn", `no components.json under ${root}`);
52
+ } else {
53
+ try {
54
+ const components = JSON.parse(readFileSync(componentsPath, "utf8"));
55
+ const scopes = Object.keys(components.registries ?? {});
56
+ add("project", "ok", `${root} · ${scopes.length} registries${scopes.length ? `: ${scopes.join(", ")}` : ""}`);
57
+
58
+ const envPath = join(root, ".env.local");
59
+ const env = existsSync(envPath) ? parseEnvText(readFileSync(envPath, "utf8")) : {};
60
+ const missing = [];
61
+ for (const lib of LIBS) {
62
+ if (!scopes.some((scope) => (lib.registries ?? []).some((r) => r.scope === scope))) continue;
63
+ for (const spec of lib.env ?? []) {
64
+ if (spec.from === "cliKey" && !env[spec.name]) missing.push(`${lib.site}:${spec.name}`);
65
+ }
66
+ }
67
+ add("env", missing.length ? "warn" : "ok", missing.length ? `missing ${missing.join(", ")}` : "license variables present");
68
+ } catch (error) {
69
+ add("project", "fail", `cannot parse components.json: ${error.message}`);
70
+ }
71
+ }
72
+
73
+ const mcpFiles = [
74
+ join(root, ".mcp.json"),
75
+ join(root, ".cursor", "mcp.json"),
76
+ join(root, ".vscode", "mcp.json"),
77
+ ];
78
+ const present = mcpFiles.filter((file) => existsSync(file));
79
+ add("mcp-config", present.length ? "ok" : "warn", present.length ? present.join(", ") : "no project MCP config");
80
+
81
+ // registry 深探测:只探测有 verify + CLI key 的库;默认第一个,--deep 全部
82
+ if (token && me) {
83
+ const owned = ownedLibs(me);
84
+ const targets = flags.deep ? owned : owned.slice(0, 1);
85
+ for (const lib of targets) {
86
+ const { cli } = resolveLibKeys(lib, me);
87
+ const verify = lib.verify?.[0];
88
+ if (!cli || !verify) continue;
89
+ const probe = buildProbe(lib, verify, cli, registryBase());
90
+ if (!probe) continue;
91
+ try {
92
+ const out = await httpRequest(probe.url, {
93
+ headers: probe.headers,
94
+ reporter,
95
+ label: `registry probe ${lib.site}`,
96
+ timeout: 20_000,
97
+ retries: 1,
98
+ });
99
+ const ok = out.res.ok;
100
+ add(
101
+ `registry:${lib.site}`,
102
+ ok ? "ok" : out.res.status === 401 || out.res.status === 403 ? "warn" : "fail",
103
+ `HTTP ${out.res.status} · ${verify}`
104
+ );
105
+ } catch (error) {
106
+ add(`registry:${lib.site}`, "fail", error.message);
107
+ }
108
+ }
109
+ }
110
+
111
+ const failed = checks.filter((c) => c.status === "fail").length;
112
+ const warned = checks.filter((c) => c.status === "warn").length;
113
+ if (reporter.json) {
114
+ reporter.result({ root, checks, failed, warned });
115
+ } else {
116
+ reporter.note(
117
+ "Doctor",
118
+ formatTable(checks, [
119
+ { key: "check", header: "CHECK" },
120
+ { key: "status", header: "STATUS" },
121
+ { key: "detail", header: "DETAIL" },
122
+ ])
123
+ );
124
+ }
125
+ if (failed > 0) process.exitCode = 1;
126
+ reporter.outro(failed > 0 ? `${failed} failure(s), ${warned} warning(s).` : warned > 0 ? `${warned} warning(s).` : "All checks passed.");
127
+ }
128
+
129
+ function buildProbe(lib, verify, cliKey, base) {
130
+ const [scope, ...rest] = String(verify).split("/");
131
+ const component = rest.join("/");
132
+ const registry = (lib.registries ?? []).find((r) => r.scope === scope);
133
+ if (!registry || !lib.source) return null;
134
+ const path = (registry.path ?? "{name}.json").replace("{name}", component);
135
+ let url = registryUrl(lib.source, { ...registry, path }, base);
136
+ const headers = { ...(registry.headers ?? {}) };
137
+ for (const [name, value] of Object.entries(headers)) {
138
+ headers[name] = String(value).replace(/\$\{([A-Z0-9_]+)\}/g, (_, key) => envFor(lib, key, cliKey));
139
+ }
140
+ const params = { ...(registry.params ?? {}) };
141
+ if (Object.keys(params).length) {
142
+ const qs = new URLSearchParams();
143
+ for (const [name, value] of Object.entries(params)) {
144
+ qs.set(name, String(value).replace(/\$\{([A-Z0-9_]+)\}/g, (_, key) => envFor(lib, key, cliKey)));
145
+ }
146
+ url += `${url.includes("?") ? "&" : "?"}${qs.toString()}`;
147
+ }
148
+ return { url, headers };
149
+ }
150
+
151
+ function envFor(lib, name, cliKey) {
152
+ const spec = (lib.env ?? []).find((e) => e.name === name);
153
+ if (!spec) return "";
154
+ return spec.from === "cliKey" ? cliKey : spec.value ?? "";
155
+ }
@@ -0,0 +1,5 @@
1
+ import { runSetup } from "./setup.mjs";
2
+
3
+ export async function initCmd(flags, rest, reporter) {
4
+ return runSetup({ flags, rest, reporter, mode: "init" });
5
+ }
@@ -0,0 +1,49 @@
1
+ import { LIBS, ownedLibs, resolveLibKeys } from "../catalog.mjs";
2
+ import { formatTable } from "../report.mjs";
3
+ import { loadMe } from "./common.mjs";
4
+
5
+ export async function libsCmd(flags, rest, reporter) {
6
+ let me = null;
7
+ try {
8
+ me = await loadMe(flags, reporter, { required: false });
9
+ } catch (error) {
10
+ reporter.warn(`Could not load account (${error.message}); showing catalog only.`);
11
+ }
12
+
13
+ const owned = me ? new Set(ownedLibs(me).map((lib) => lib.site)) : null;
14
+ const rows = [];
15
+
16
+ for (const lib of LIBS) {
17
+ const keys = me ? resolveLibKeys(lib, me) : { cli: null, mcp: null };
18
+ rows.push({
19
+ site: lib.site,
20
+ name: lib.siteName,
21
+ owned: owned ? (owned.has(lib.site) ? "yes" : "no") : "?",
22
+ cli: keys.cli ? "bound" : "—",
23
+ mcp: keys.mcp ? "bound" : "—",
24
+ registries: (lib.registries ?? []).map((r) => r.scope).join(", ") || "—",
25
+ mcpServer: lib.mcp ?? (lib.shadcnUiMcp ? "shadcn (generic)" : "—"),
26
+ });
27
+ }
28
+
29
+ if (reporter.json) {
30
+ reporter.result({ account: me?.account ?? null, libraries: rows });
31
+ return;
32
+ }
33
+
34
+ reporter.note(
35
+ me ? `Account ${me.account?.username ?? me.account?.uid}` : "Catalog (not logged in)",
36
+ formatTable(rows, [
37
+ { key: "site", header: "SITE" },
38
+ { key: "name", header: "LIBRARY" },
39
+ { key: "owned", header: "OWNED" },
40
+ { key: "cli", header: "CLI KEY" },
41
+ { key: "mcp", header: "MCP KEY" },
42
+ { key: "registries", header: "REGISTRIES" },
43
+ { key: "mcpServer", header: "MCP SERVER" },
44
+ ])
45
+ );
46
+ if (!me) {
47
+ reporter.info("Run `collectui login` to see which libraries your account owns and to bind keys.");
48
+ }
49
+ }
@@ -0,0 +1,26 @@
1
+ import { login, logout } from "../login.mjs";
2
+
3
+ export async function loginCmd(flags, rest, reporter) {
4
+ const timeout = flags.timeout ? Number(flags.timeout) : 180_000;
5
+ if (!Number.isFinite(timeout) || timeout < 5_000) {
6
+ throw new Error("--timeout must be at least 5000 ms");
7
+ }
8
+ const { token: _token, me } = await login({
9
+ token: flags.token,
10
+ noOpen: Boolean(flags["no-open"]),
11
+ timeout,
12
+ reporter,
13
+ skipVerify: Boolean(flags["no-verify"]),
14
+ });
15
+ reporter.result({
16
+ account: me?.account ?? null,
17
+ libraries: (me?.sites ?? []).map((s) => s.slug),
18
+ keys: (me?.keys ?? []).length,
19
+ });
20
+ }
21
+
22
+ export function logoutCmd(flags, rest, reporter) {
23
+ logout({ reporter });
24
+ reporter.result({ loggedOut: true });
25
+ reporter.outro("Logged out.");
26
+ }
@@ -0,0 +1,190 @@
1
+ import { resolve } from "node:path";
2
+ import { ChangeSet } from "../changes.mjs";
3
+ import { dashUrl, registryUrl } from "../config.mjs";
4
+ import { usageError } from "../errors.mjs";
5
+ import { addMeSecrets, dashMcpTool, dashMcpTools, dashMe, fetchMe, formatMeHuman, formatTools } from "../dash.mjs";
6
+ import { buildMcpEntries, describeEntries, planMcpConfig, renderEntry } from "../mcp.mjs";
7
+ import { requireToken, selectLibs } from "./common.mjs";
8
+ import { resolveClients } from "./setup.mjs";
9
+
10
+ export async function mcpCmd(flags, rest, reporter) {
11
+ const sub = rest[0] ?? "show";
12
+ if (sub === "help" || flags.help) {
13
+ reporter.info(MCP_HELP);
14
+ return;
15
+ }
16
+
17
+ if (["tools", "call", "me", "repos", "download", "feedback"].includes(sub)) {
18
+ return dashMcpCommand(sub, flags, rest.slice(1), reporter);
19
+ }
20
+
21
+ if (sub === "show" || sub === "init" || sub === "configure") {
22
+ return mcpConfigCommand(sub, flags, rest.slice(1), reporter);
23
+ }
24
+
25
+ throw usageError(`Unknown mcp subcommand "${sub}".`, { hint: MCP_HELP });
26
+ }
27
+
28
+ async function mcpConfigCommand(sub, flags, rest, reporter) {
29
+ const token = requireToken(flags, reporter);
30
+ const me = await fetchMe(token, { reporter });
31
+ reporter.addSecrets((me.keys ?? []).map((k) => k.key).filter(Boolean));
32
+ const { units } = await selectLibs({ flags, me, reporter });
33
+ const clients = resolveClients(flags);
34
+ const target = resolve(flags.cwd || rest[0] || process.cwd());
35
+
36
+ const entries = buildMcpEntries({
37
+ units,
38
+ me,
39
+ dashToken: token,
40
+ registryBase: registryUrl(),
41
+ dashBase: dashUrl(),
42
+ includeDash: !flags["no-dash-mcp"],
43
+ reporter,
44
+ });
45
+
46
+ if (sub === "show") {
47
+ const configs = {};
48
+ for (const client of clients) {
49
+ configs[client] = Object.fromEntries(
50
+ entries.map((entry) => [entry.serverName, renderEntry(entry, client)])
51
+ );
52
+ }
53
+ if (reporter.json) {
54
+ reporter.result({ servers: entries.map((e) => e.serverName), configs });
55
+ return;
56
+ }
57
+ reporter.note("MCP servers", describeEntries(entries).join("\n") || "(none)");
58
+ for (const client of clients) {
59
+ reporter.preview(`${client} config`, JSON.stringify(configs[client], null, 2));
60
+ }
61
+ return;
62
+ }
63
+
64
+ const cs = new ChangeSet({
65
+ reporter,
66
+ dryRun: Boolean(flags["dry-run"]),
67
+ yes: Boolean(flags.yes) || reporter.headless,
68
+ root: target,
69
+ });
70
+ planMcpConfig(cs, {
71
+ projectDir: target,
72
+ units,
73
+ me,
74
+ dashToken: token,
75
+ registryBase: registryUrl(),
76
+ dashBase: dashUrl(),
77
+ clients,
78
+ force: Boolean(flags.force),
79
+ includeDash: !flags["no-dash-mcp"],
80
+ codexHome: flags["codex-home"] ? String(flags["codex-home"]) : undefined,
81
+ reporter,
82
+ });
83
+ const applied = await cs.apply();
84
+ reporter.result({
85
+ target,
86
+ clients,
87
+ servers: entries.map((e) => e.serverName),
88
+ files: applied.files?.length ?? 0,
89
+ dryRun: Boolean(flags["dry-run"]),
90
+ });
91
+ reporter.outro(flags["dry-run"] ? "Dry run complete." : "MCP configuration updated.");
92
+ }
93
+
94
+ async function dashMcpCommand(sub, flags, rest, reporter) {
95
+ const token = requireToken(flags, reporter);
96
+
97
+ if (sub === "tools") {
98
+ const tools = await dashMcpTools(token, { reporter });
99
+ if (reporter.json) reporter.result({ tools });
100
+ else reporter.note("Dash MCP tools", formatTools(tools));
101
+ return;
102
+ }
103
+
104
+ if (sub === "call") {
105
+ const name = rest[0];
106
+ if (!name) throw usageError("Usage: collectui mcp call <tool> [--args '<json>']");
107
+ let args = {};
108
+ if (flags.args) {
109
+ try {
110
+ args = JSON.parse(String(flags.args));
111
+ } catch (error) {
112
+ throw usageError(`--args is not valid JSON: ${error.message}`);
113
+ }
114
+ }
115
+ const result = await dashMcpTool(token, name, args, { reporter });
116
+ if (result?.keys) addMeSecrets(reporter, result);
117
+ if (reporter.json) reporter.result({ tool: name, result });
118
+ else reporter.note(`mcp:${name}`, typeof result === "string" ? result : JSON.stringify(result, null, 2));
119
+ return;
120
+ }
121
+
122
+ if (sub === "me") {
123
+ const me = await dashMe(token, { reporter });
124
+ addMeSecrets(reporter, me);
125
+ if (reporter.json) reporter.result(me);
126
+ else reporter.note("Dash account", formatMeHuman(me));
127
+ return;
128
+ }
129
+
130
+ if (sub === "repos") {
131
+ const result = await dashMcpTool(token, "list_repos", {}, { reporter });
132
+ if (reporter.json) reporter.result(result);
133
+ else {
134
+ const lines = (result?.releases ?? []).map(
135
+ (r) => `- ${r.repo} v${r.version} ${r.size ?? "?"} bytes ${r.releasedAt}${r.brief ? `\n ${r.brief}` : ""}`
136
+ );
137
+ reporter.note("Downloadable repos", lines.join("\n") || "(none)");
138
+ }
139
+ return;
140
+ }
141
+
142
+ if (sub === "download") {
143
+ const repo = rest[0];
144
+ if (!repo) throw usageError("Usage: collectui mcp download <owner/repo>");
145
+ const result = await dashMcpTool(token, "download_repo", { repo }, { reporter });
146
+ if (reporter.json) reporter.result(result);
147
+ else {
148
+ reporter.note(
149
+ "Download",
150
+ [
151
+ `- repo: ${result?.repo ?? repo}`,
152
+ `- version: ${result?.version ?? "?"}`,
153
+ `- url: ${result?.url ?? "(no url)"}`,
154
+ result?.gitUrl ? `- git: ${result.gitUrl}` : null,
155
+ result?.expiresAt ? `- expires: ${result.expiresAt}` : null,
156
+ ]
157
+ .filter(Boolean)
158
+ .join("\n")
159
+ );
160
+ }
161
+ return;
162
+ }
163
+
164
+ if (sub === "feedback") {
165
+ const message = rest.join(" ").trim();
166
+ if (!message) throw usageError("Usage: collectui mcp feedback <message> [--site reui,arc]");
167
+ const result = await dashMcpTool(
168
+ token,
169
+ "submit_feedback",
170
+ { message, ...(flags.site ? { site: String(flags.site) } : {}) },
171
+ { reporter }
172
+ );
173
+ if (reporter.json) reporter.result(result);
174
+ else reporter.note("Feedback", JSON.stringify(result, null, 2));
175
+ return;
176
+ }
177
+
178
+ throw usageError(`Unknown mcp subcommand "${sub}".`, { hint: MCP_HELP });
179
+ }
180
+
181
+ const MCP_HELP = `Usage: collectui mcp <show|init|tools|call|me|repos|download|feedback>
182
+
183
+ show Print MCP server config for the selected libraries and clients
184
+ init Write/merge MCP configs (same as configure's MCP step)
185
+ tools List tools on the CollectUI Dash MCP
186
+ call <tool> Call a Dash MCP tool (--args '<json>')
187
+ me Account aggregation via Dash MCP (falls back to REST)
188
+ repos Downloadable snapshot repos via Dash MCP
189
+ download <repo> Fresh download URL for a repo
190
+ feedback <message> Submit feedback through Dash MCP (--site reui,arc)`;
@@ -0,0 +1,221 @@
1
+ import { existsSync, readdirSync, statSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { basename, join, resolve } from "node:path";
4
+ import { ChangeSet } from "../changes.mjs";
5
+ import { CLI_VERSION } from "../version.mjs";
6
+ import { dashUrl, registryUrl, resolveToken } from "../config.mjs";
7
+ import { CliError } from "../errors.mjs";
8
+ import { login } from "../login.mjs";
9
+ import { fetchMe } from "../dash.mjs";
10
+ import { planMcpConfig, describeEntries } from "../mcp.mjs";
11
+ import { detectPackageManager, planProjectConfig } from "../project.mjs";
12
+ import { planManifest, planScaffold } from "../scaffold.mjs";
13
+ import { selectLibs } from "./common.mjs";
14
+
15
+ const DEFAULT_CLIENTS = ["claude", "cursor", "vscode"];
16
+ const ALL_CLIENTS = ["claude", "cursor", "codex", "vscode"];
17
+
18
+ export function resolveClients(flags) {
19
+ const raw = flags.clients;
20
+ if (!raw) return DEFAULT_CLIENTS;
21
+ const list = String(raw)
22
+ .split(/[,\s]+/)
23
+ .map((s) => s.trim().toLowerCase())
24
+ .filter(Boolean);
25
+ if (list.includes("all")) return ALL_CLIENTS;
26
+ const unknown = list.filter((c) => !ALL_CLIENTS.includes(c));
27
+ if (unknown.length) {
28
+ throw new CliError(`Unknown MCP client(s): ${unknown.join(", ")}`, {
29
+ code: 2,
30
+ hint: `Supported: ${ALL_CLIENTS.join(", ")}, all`,
31
+ });
32
+ }
33
+ return [...new Set(list)];
34
+ }
35
+
36
+ export function resolveTarget({ flags, rest, mode }) {
37
+ const explicit = flags.cwd || rest[0];
38
+ if (explicit) return resolve(String(explicit));
39
+ const safeName = String(flags.name ?? "collectui-app").replace(/[\\/]+/g, "-");
40
+ if (flags.tmp) {
41
+ return join(tmpdir(), safeName);
42
+ }
43
+ if (mode === "configure") return process.cwd();
44
+ return resolve(safeName);
45
+ }
46
+
47
+ function isNonEmptyDir(dir) {
48
+ try {
49
+ const st = statSync(dir);
50
+ if (!st.isDirectory()) return true;
51
+ return readdirSync(dir).length > 0;
52
+ } catch {
53
+ return false;
54
+ }
55
+ }
56
+
57
+ /**
58
+ * init / configure 共用主流程:
59
+ * 身份 → 选库 → 脚手架(仅 init)→ registries/env → MCP → manifest → 应用。
60
+ * 全程 ChangeSet:先展示计划、再确认、再落盘;--dry-run 只展示。
61
+ */
62
+ export async function runSetup({ flags, rest = [], reporter, mode }) {
63
+ reporter.intro(`CollectUI CLI · ${mode}`);
64
+
65
+ let token = resolveToken(flags);
66
+ if (!token) {
67
+ if (reporter.headless) {
68
+ throw new CliError("Not logged in (headless).", {
69
+ code: 3,
70
+ hint: "Pass --token dpat_... or set COLLECTUI_TOKEN. `collectui login` opens Dash for you in a terminal.",
71
+ });
72
+ }
73
+ reporter.info("No saved session — starting login first.");
74
+ const session = await login({ reporter });
75
+ token = session.token;
76
+ }
77
+ reporter.addSecrets([token]);
78
+
79
+ let me;
80
+ try {
81
+ me = await fetchMe(token, { reporter });
82
+ } catch (error) {
83
+ if (error?.exitCode === 3 && !reporter.headless) {
84
+ reporter.warn("Saved PAT was rejected — starting login again.");
85
+ const session = await login({ reporter });
86
+ token = session.token;
87
+ reporter.addSecrets([token]);
88
+ me = session.me ?? (await fetchMe(token, { reporter }));
89
+ } else {
90
+ throw error;
91
+ }
92
+ }
93
+ reporter.addSecrets((me.keys ?? []).map((k) => k.key).filter(Boolean));
94
+ const account = me.account ?? {};
95
+ reporter.info(
96
+ `Signed in as ${account.username ?? account.uid ?? "(unknown)"} · ${me.sites?.length ?? 0} librar${(me.sites?.length ?? 0) === 1 ? "y" : "ies"} with access.`
97
+ );
98
+
99
+ const { libs, units } = await selectLibs({ flags, me, reporter });
100
+
101
+ const target = resolveTarget({ flags, rest, mode });
102
+ const hasComponents = existsSync(join(target, "components.json"));
103
+ const nonEmpty = isNonEmptyDir(target);
104
+ const template = flags.template ? String(flags.template) : "vite";
105
+
106
+ if (mode === "configure" && !hasComponents) {
107
+ throw new CliError(`${target} has no components.json.`, {
108
+ hint: "Point at a shadcn project, or run `collectui init` to create one.",
109
+ });
110
+ }
111
+ if (mode === "init" && hasComponents) {
112
+ reporter.info(`${target} already has components.json — switching to configure mode (no scaffold).`);
113
+ mode = "configure";
114
+ }
115
+ if (mode === "init" && !hasComponents && nonEmpty && !flags.force) {
116
+ throw new CliError(`Target directory is not empty: ${target}`, {
117
+ hint: "Pick an empty/new directory, or pass --force to add missing files without overwriting existing ones.",
118
+ });
119
+ }
120
+ if (template === "none" && !hasComponents) {
121
+ throw new CliError("--template none needs an existing components.json.", {
122
+ hint: "Use --template vite or point at an existing shadcn project.",
123
+ });
124
+ }
125
+
126
+ const pm = flags.pm ? String(flags.pm) : detectPackageManager(hasComponents ? target : process.cwd());
127
+ const install =
128
+ mode === "init" &&
129
+ !hasComponents &&
130
+ flags.install !== false &&
131
+ !flags["no-install"];
132
+ const clients = resolveClients(flags);
133
+ const projectName = flags.name ? String(flags.name) : basename(target) || "collectui-app";
134
+
135
+ const cs = new ChangeSet({
136
+ reporter,
137
+ dryRun: Boolean(flags["dry-run"]),
138
+ yes: Boolean(flags.yes) || reporter.headless,
139
+ root: target,
140
+ });
141
+
142
+ if (mode === "init" && !hasComponents) {
143
+ reporter.step(1, 5, `Scaffold ${template} project in ${target}`);
144
+ planScaffold(cs, { target, name: projectName, template, pm, install });
145
+ } else {
146
+ reporter.step(1, 5, `Use existing project ${target}`);
147
+ }
148
+
149
+ reporter.step(2, 5, "Configure shadcn registries and license keys");
150
+ planProjectConfig(cs, {
151
+ projectDir: target,
152
+ units,
153
+ me,
154
+ registryBase: registryUrl(),
155
+ force: Boolean(flags.force),
156
+ reporter,
157
+ });
158
+
159
+ let mcpEntries = [];
160
+ if (!flags["no-mcp"]) {
161
+ reporter.step(3, 5, "Configure MCP servers (library + CollectUI Dash)");
162
+ const mcp = planMcpConfig(cs, {
163
+ projectDir: target,
164
+ units,
165
+ me,
166
+ dashToken: token,
167
+ registryBase: registryUrl(),
168
+ dashBase: dashUrl(),
169
+ clients,
170
+ force: Boolean(flags.force),
171
+ includeDash: !flags["no-dash-mcp"],
172
+ codexHome: flags["codex-home"] ? String(flags["codex-home"]) : undefined,
173
+ reporter,
174
+ });
175
+ mcpEntries = mcp.entries;
176
+ if (reporter.verbose) {
177
+ reporter.note("MCP servers", describeEntries(mcpEntries).join("\n") || "(none)");
178
+ }
179
+ } else {
180
+ reporter.step(3, 5, "MCP configuration skipped (--no-mcp)");
181
+ }
182
+
183
+ reporter.step(4, 5, "Write machine-readable setup record");
184
+ planManifest(cs, {
185
+ target,
186
+ units,
187
+ me,
188
+ registryBase: registryUrl(),
189
+ dashBase: dashUrl(),
190
+ clients,
191
+ mcpEntries,
192
+ cliVersion: CLI_VERSION,
193
+ });
194
+
195
+ reporter.step(5, 5, "Apply changes");
196
+ const applied = await cs.apply();
197
+
198
+ const summary = {
199
+ target,
200
+ mode,
201
+ libraries: libs.map((lib) => lib.site),
202
+ units: units.map((u) => u.site),
203
+ files: applied.files?.length ?? 0,
204
+ mcpClients: clients,
205
+ mcpServers: mcpEntries.map((e) => e.serverName),
206
+ dryRun: Boolean(flags["dry-run"]),
207
+ next: [
208
+ mode === "init" && !hasComponents ? `cd ${target}` : null,
209
+ install ? `dependencies installing via ${pm}` : "npm install (if dependencies are missing)",
210
+ `collectui add ${units[0]?.site ?? "<site>"} <component>`,
211
+ "collectui doctor",
212
+ ].filter(Boolean),
213
+ };
214
+ reporter.result(summary);
215
+ reporter.outro(
216
+ flags["dry-run"]
217
+ ? "Dry run complete. Re-run without --dry-run to apply."
218
+ : `Done — ${libs.length} librar${libs.length === 1 ? "y" : "ies"} configured in ${target}.`
219
+ );
220
+ return summary;
221
+ }
@@ -0,0 +1,26 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import { ChangeSet } from "../changes.mjs";
6
+
7
+ export async function skillCmd(flags, rest, reporter) {
8
+ const source = fileURLToPath(new URL("../skill/SKILL.md", import.meta.url));
9
+ const content = readFileSync(source, "utf8");
10
+ const global = Boolean(flags.global);
11
+ const root = global
12
+ ? join(homedir(), ".claude", "skills", "collectui")
13
+ : join(resolve(flags.cwd || rest[0] || process.cwd()), ".claude", "skills", "collectui");
14
+ const target = join(root, "SKILL.md");
15
+
16
+ const cs = new ChangeSet({
17
+ reporter,
18
+ dryRun: Boolean(flags["dry-run"]),
19
+ yes: Boolean(flags.yes) || reporter.headless,
20
+ root: process.cwd(),
21
+ });
22
+ cs.write(target, content, { summary: "install the CollectUI agent skill" });
23
+ await cs.apply();
24
+ reporter.result({ path: target, scope: global ? "global" : "project" });
25
+ reporter.outro("Skill installed. Claude Code picks it up automatically.");
26
+ }
@@ -0,0 +1,17 @@
1
+ import { formatMeHuman, maskKey } from "../dash.mjs";
2
+ import { loadMe } from "./common.mjs";
3
+
4
+ export async function whoamiCmd(flags, rest, reporter) {
5
+ const me = await loadMe(flags, reporter);
6
+ if (reporter.json) {
7
+ reporter.result({
8
+ account: me.account,
9
+ sites: me.sites,
10
+ keys: (me.keys ?? []).map((k) => ({ ...k, key: maskKey(k.key) })),
11
+ repos: me.repos,
12
+ orders: me.orders,
13
+ });
14
+ return;
15
+ }
16
+ reporter.note("Account", formatMeHuman(me));
17
+ }