designsource 0.4.0 → 0.5.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.
Files changed (3) hide show
  1. package/README.md +104 -17
  2. package/dist/index.js +2666 -256
  3. package/package.json +7 -6
package/dist/index.js CHANGED
@@ -1,5 +1,876 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ // src/connect/apps.ts
4
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
5
+ import { posix as posix3, win32 } from "node:path";
6
+
7
+ // src/add/setup.ts
8
+ import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync } from "node:fs";
9
+ import { join as join2, posix as posix2 } from "node:path";
10
+
11
+ // src/errors.ts
12
+ var CliError = class extends Error {
13
+ constructor(message, exitCode = 1) {
14
+ super(message);
15
+ this.exitCode = exitCode;
16
+ }
17
+ exitCode;
18
+ };
19
+ var CANCELLED = "Cancelled.";
20
+ var TOKEN_MESSAGE = "Project token not recognised. In the workbench open Project settings and copy the project token.";
21
+ var MCP_TOKEN_REQUIRED = "A project token is required: pass --token or set DS_SYNC_TOKEN (workbench \u2192 Project settings).";
22
+ var UNREACHABLE = (api) => `Could not reach ${api}.`;
23
+ var UPDATE_MESSAGE = "This design system needs a newer designsource CLI. Update it (for example `npx designsource@latest`) and run again.";
24
+ var PLAN_MESSAGE = "This project's account is on the free plan. Exports need Pro: https://designsource.app/pricing";
25
+ function messageForResponse(status, body, api) {
26
+ if (status === 401) return TOKEN_MESSAGE;
27
+ if (status === 402) return PLAN_MESSAGE;
28
+ const serverMessage = typeof body === "object" && body !== null && typeof body.error === "string" ? body.error : null;
29
+ if (status === 400) return serverMessage ?? `${api} rejected the request (400).`;
30
+ return `${api} answered ${status}.`;
31
+ }
32
+
33
+ // src/paths.ts
34
+ import { isAbsolute, resolve, sep } from "node:path";
35
+ function resolveInside(root, relPath) {
36
+ const escapes = (why) => new CliError(`Manifest path "${relPath}" is outside the target folder (${why}).`);
37
+ if (!relPath) throw escapes("empty");
38
+ if (isAbsolute(relPath) || /^[a-zA-Z]:[\\/]/.test(relPath) || relPath.startsWith("\\")) throw escapes("absolute");
39
+ if (relPath.split(/[\\/]/).includes("..")) throw escapes("..");
40
+ const abs = resolve(root, relPath);
41
+ if (abs === root || !abs.startsWith(root.endsWith(sep) ? root : root + sep)) throw escapes("resolves above it");
42
+ return abs;
43
+ }
44
+
45
+ // src/add/targets.ts
46
+ import { existsSync, readFileSync } from "node:fs";
47
+ import { join, posix } from "node:path";
48
+ var BAD_COMPONENTS_JSON = "components.json is missing its aliases or tailwind.css path.";
49
+ var noAlias = (alias) => new CliError(`Could not resolve the import alias "${alias}" from tsconfig.json.`);
50
+ var outside = (alias) => new CliError(`The import alias "${alias}" points outside the app folder.`);
51
+ function stripJsonc(text) {
52
+ let out = "";
53
+ let i = 0;
54
+ while (i < text.length) {
55
+ const c = text[i];
56
+ if (c === '"') {
57
+ let j = i + 1;
58
+ while (j < text.length && text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
59
+ out += text.slice(i, j + 1);
60
+ i = j + 1;
61
+ } else if (c === "/" && text[i + 1] === "/") {
62
+ while (i < text.length && text[i] !== "\n") i++;
63
+ } else if (c === "/" && text[i + 1] === "*") {
64
+ const end = text.indexOf("*/", i + 2);
65
+ i = end === -1 ? text.length : end + 2;
66
+ } else {
67
+ out += c;
68
+ i++;
69
+ }
70
+ }
71
+ return out.replace(/,(\s*[}\]])/g, "$1");
72
+ }
73
+ function readTsconfig(path) {
74
+ if (!existsSync(path)) return null;
75
+ try {
76
+ const json = JSON.parse(stripJsonc(readFileSync(path, "utf8")));
77
+ return typeof json === "object" && json !== null ? json : null;
78
+ } catch {
79
+ throw new CliError(`${path.slice(path.lastIndexOf("/") + 1)} is not valid JSON.`);
80
+ }
81
+ }
82
+ function pathsOf(config) {
83
+ const options = config?.compilerOptions;
84
+ if (typeof options !== "object" || options === null) return null;
85
+ const { paths, baseUrl } = options;
86
+ if (typeof paths !== "object" || paths === null) return null;
87
+ const clean = Object.fromEntries(Object.entries(paths).filter((e) => Array.isArray(e[1]) && typeof e[1][0] === "string"));
88
+ return { paths: clean, baseUrl: typeof baseUrl === "string" ? baseUrl : "." };
89
+ }
90
+ function readPaths(root) {
91
+ const base = readTsconfig(join(root, "tsconfig.json"));
92
+ return pathsOf(base) ?? (base?.references ? pathsOf(readTsconfig(join(root, "tsconfig.app.json"))) : null);
93
+ }
94
+ function resolveAlias(alias, tsconfig) {
95
+ if (!tsconfig) throw noAlias(alias);
96
+ let best = null;
97
+ for (const [key, targets] of Object.entries(tsconfig.paths)) {
98
+ const star = key.indexOf("*");
99
+ const prefix = star === -1 ? key : key.slice(0, star);
100
+ const suffix = star === -1 ? "" : key.slice(star + 1);
101
+ const matches = star === -1 ? alias === key : alias.startsWith(prefix) && alias.endsWith(suffix) && alias.length >= prefix.length + suffix.length;
102
+ if (!matches || best && best.prefixLength >= prefix.length) continue;
103
+ const rest = star === -1 ? "" : alias.slice(prefix.length, alias.length - suffix.length);
104
+ const target = targets[0];
105
+ best = { prefixLength: prefix.length, resolved: star === -1 ? target : target.replace("*", () => rest) };
106
+ }
107
+ if (!best) throw noAlias(alias);
108
+ const relative5 = posix.normalize(posix.join(tsconfig.baseUrl, best.resolved));
109
+ if (relative5 === ".." || relative5.startsWith("../") || posix.isAbsolute(relative5)) throw outside(alias);
110
+ return relative5 === "." ? "" : relative5;
111
+ }
112
+ function resolveTargets(root, shadcn) {
113
+ const { aliases, tailwind } = shadcn ?? {};
114
+ if (typeof aliases?.components !== "string" || typeof aliases.utils !== "string" || typeof tailwind?.css !== "string") throw new CliError(BAD_COMPONENTS_JSON);
115
+ const tsconfig = readPaths(root);
116
+ const uiAlias = typeof aliases.ui === "string" ? aliases.ui : `${aliases.components}/ui`;
117
+ return {
118
+ uiDir: resolveAlias(uiAlias, tsconfig),
119
+ utilsFile: `${resolveAlias(aliases.utils, tsconfig)}.ts`,
120
+ cssFile: tailwind.css,
121
+ uiAlias,
122
+ utilsAlias: aliases.utils
123
+ };
124
+ }
125
+ function rewriteForApp(contents, t) {
126
+ return contents.replace(/(['"])@\/components\/ui\//g, (_, q) => `${q}${t.uiAlias}/`).replace(/(['"])@\/lib\/utils\1/g, (_, q) => `${q}${t.utilsAlias}${q}`);
127
+ }
128
+
129
+ // src/add/setup.ts
130
+ var StepError = class extends CliError {
131
+ constructor(message, outputTail2) {
132
+ super(message);
133
+ this.outputTail = outputTail2;
134
+ }
135
+ outputTail;
136
+ };
137
+ var OUTPUT_TAIL_LINES = 20;
138
+ var VITE_CONFIGS = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"];
139
+ var POSTCSS_CONFIGS = ["postcss.config.mjs", "postcss.config.js", "postcss.config.cjs", "postcss.config.ts", ".postcssrc", ".postcssrc.json"];
140
+ var NO_POSTCSS_TAILWIND = 'This app has a PostCSS config without Tailwind. Add "@tailwindcss/postcss" to its plugins, then run this again.';
141
+ var NO_STYLESHEET = "Could not find the app's global stylesheet (app/globals.css or src/index.css). Create it, import it in your root layout or entry file, then run this again.";
142
+ var NO_VITE_TAILWIND = "Could not add Tailwind to vite.config.ts automatically. Add the @tailwindcss/vite plugin, then run this again.";
143
+ var NO_VITE_ALIAS = 'Could not add the @/ import alias to vite.config.ts automatically. Add resolve.alias for "@", then run this again.';
144
+ var noTsconfigAlias = (file) => new CliError(`Could not add the @/ import alias to ${file} automatically. Add "paths": { "@/*": ["./src/*"] }, then run this again.`);
145
+ function installArgs(pm, pkgs, dev) {
146
+ const specs = Object.entries(pkgs).map(([name, range]) => `${name}@${range}`);
147
+ const verb = pm === "npm" ? "install" : "add";
148
+ const flag = dev ? [pm === "bun" ? "-d" : "-D"] : [];
149
+ return [pm, [verb, ...flag, ...specs]];
150
+ }
151
+ function outputTail(output) {
152
+ return output.trimEnd().split("\n").slice(-OUTPUT_TAIL_LINES).join("\n");
153
+ }
154
+ async function run(exec, cwd, cmd, args) {
155
+ const { code: code2, output } = await exec(cmd, args, { cwd });
156
+ if (code2 === 0) return;
157
+ throw new StepError(`${cmd} ${args.join(" ")} failed (exit ${code2}).`, outputTail(output));
158
+ }
159
+ function findGlobalStylesheet(info) {
160
+ const candidates = info.framework === "next" ? ["app/globals.css", "src/app/globals.css"] : info.framework === "vite" ? ["src/index.css"] : ["app/globals.css", "src/app/globals.css", "src/index.css"];
161
+ const found = candidates.find((file) => existsSync2(join2(info.root, file)));
162
+ if (!found) throw new CliError(NO_STYLESHEET);
163
+ return found;
164
+ }
165
+ function maskComments(text, { line = true } = {}) {
166
+ let out = "";
167
+ let i = 0;
168
+ while (i < text.length) {
169
+ const c = text[i];
170
+ if (c === '"' || c === "'" || c === "`") {
171
+ let j = i + 1;
172
+ while (j < text.length && text[j] !== c) j += text[j] === "\\" ? 2 : 1;
173
+ const end = Math.min(j + 1, text.length);
174
+ out += text.slice(i, end);
175
+ i = end;
176
+ } else if (line && c === "/" && text[i + 1] === "/") {
177
+ let j = i;
178
+ while (j < text.length && text[j] !== "\n") j++;
179
+ out += " ".repeat(j - i);
180
+ i = j;
181
+ } else if (c === "/" && text[i + 1] === "*") {
182
+ const close = text.indexOf("*/", i + 2);
183
+ const end = close === -1 ? text.length : close + 2;
184
+ out += text.slice(i, end).replace(/[^\n]/g, " ");
185
+ i = end;
186
+ } else {
187
+ out += c;
188
+ i++;
189
+ }
190
+ }
191
+ return out;
192
+ }
193
+ function pinned(manifest, name) {
194
+ const range = manifest.devPackages[name];
195
+ if (!range) throw new CliError(`The kit manifest does not pin ${name}.`);
196
+ return range;
197
+ }
198
+ function readText(info, rel) {
199
+ return readFileSync2(resolveInside(info.root, rel), "utf8");
200
+ }
201
+ function writeText(info, rel, text) {
202
+ writeFileSync(resolveInside(info.root, rel), text);
203
+ }
204
+ function firstExisting(info, files) {
205
+ return files.find((file) => existsSync2(join2(info.root, file))) ?? null;
206
+ }
207
+ function insertAt(text, index, insert) {
208
+ return text.slice(0, index) + insert + text.slice(index);
209
+ }
210
+ function insertImports(text, lines) {
211
+ const masked = maskComments(text);
212
+ let end = -1;
213
+ for (const m of masked.matchAll(/^[ \t]*import\s[^;]*?['"][^'"\n]*['"][ \t]*;?/gm)) end = m.index + m[0].length;
214
+ if (end !== -1) {
215
+ const semi = text[end - 1] === ";" ? ";" : "";
216
+ return insertAt(text, end, lines.map((line) => `
217
+ ${line}${semi}`).join(""));
218
+ }
219
+ const leading = /^(?:\s*(?:\/\/[^\n]*|\/\*[\s\S]*?\*\/))*/.exec(text)[0].length;
220
+ const block = lines.join("\n");
221
+ return leading === 0 ? `${block}
222
+ ${text}` : insertAt(text, leading, `
223
+ ${block}`);
224
+ }
225
+ function editViteTailwind(text) {
226
+ const masked = maskComments(text);
227
+ const plugins = /\bplugins\s*:\s*\[/.exec(masked);
228
+ if (!plugins) throw new CliError(NO_VITE_TAILWIND);
229
+ const imported = /\bimport\s+(\w+)\s+from\s*['"]@tailwindcss\/vite['"]/.exec(masked);
230
+ if (!imported && masked.includes("@tailwindcss/vite")) throw new CliError(NO_VITE_TAILWIND);
231
+ const local = imported?.[1] ?? "tailwindcss";
232
+ if (new RegExp(`\\b${local}\\s*\\(`).test(masked)) return text;
233
+ const withCall = insertAt(text, plugins.index + plugins[0].length, `${local}(), `);
234
+ return imported ? withCall : insertImports(withCall, ["import tailwindcss from '@tailwindcss/vite'"]);
235
+ }
236
+ function viteHasAlias(masked) {
237
+ return /['"]@['"]\s*:/.test(masked) || /\bfind\s*:\s*['"]@['"]/.test(masked);
238
+ }
239
+ function ensureNodeUrlImports(text) {
240
+ const masked = maskComments(text);
241
+ const wanted = ["fileURLToPath", "URL"];
242
+ const named = /\bimport\s*\{([^}]*)\}\s*from\s*(['"])(?:node:)?url\2/.exec(masked);
243
+ if (!named) {
244
+ if (/\bfrom\s*['"](?:node:)?url['"]/.test(masked)) throw new CliError(NO_VITE_ALIAS);
245
+ return insertImports(text, [`import { ${wanted.join(", ")} } from 'node:url'`]);
246
+ }
247
+ const have = named[1].split(",").map((name) => name.trim());
248
+ const missing = wanted.filter((name) => !have.includes(name));
249
+ if (missing.length === 0) return text;
250
+ const inner = named[1];
251
+ const start = named.index + named[0].indexOf("{") + 1;
252
+ const next = inner.trim() === "" ? ` ${missing.join(", ")} ` : `${inner.trimEnd()}, ${missing.join(", ")}${/\s*$/.exec(inner)[0]}`;
253
+ return text.slice(0, start) + next + text.slice(start + inner.length);
254
+ }
255
+ function editViteAlias(text, srcDir) {
256
+ const masked = maskComments(text);
257
+ if (viteHasAlias(masked)) return text;
258
+ const define = /\bdefineConfig\(\s*\{/.exec(masked);
259
+ if (/\bresolve\s*:/.test(masked) || !define) throw new CliError(NO_VITE_ALIAS);
260
+ const alias = `
261
+ resolve: { alias: { '@': fileURLToPath(new URL('./${srcDir}', import.meta.url)) } },`;
262
+ return ensureNodeUrlImports(insertAt(text, define.index + define[0].length, alias));
263
+ }
264
+ function aliasTarget(baseUrl, srcDir) {
265
+ const rel = posix2.relative(posix2.normalize(baseUrl), srcDir) || ".";
266
+ return `${rel === "." ? "." : rel.startsWith("..") ? rel : `./${rel}`}/*`;
267
+ }
268
+ function editTsconfig(text, config, file, srcDir) {
269
+ const options = config.compilerOptions;
270
+ const masked = maskComments(text);
271
+ if (typeof options !== "object" || options === null) {
272
+ const open2 = /^\s*\{/.exec(masked);
273
+ if (config.extends !== void 0 || !config.references || !open2) throw noTsconfigAlias(file);
274
+ return insertAt(text, open2[0].length, `
275
+ "compilerOptions": {
276
+ "paths": { "@/*": ["${aliasTarget(".", srcDir)}"] }
277
+ },`);
278
+ }
279
+ const { paths, baseUrl } = options;
280
+ if (typeof paths === "object" && paths !== null && "@/*" in paths) return text;
281
+ const entry = `"@/*": ["${aliasTarget(typeof baseUrl === "string" ? baseUrl : ".", srcDir)}"]`;
282
+ if (typeof paths === "object" && paths !== null) {
283
+ const open2 = /"paths"\s*:\s*\{/.exec(masked);
284
+ if (!open2) throw noTsconfigAlias(file);
285
+ return insertAt(text, open2.index + open2[0].length, ` ${entry},`);
286
+ }
287
+ const open = /"compilerOptions"\s*:\s*\{/.exec(masked);
288
+ if (config.extends !== void 0 || !open) throw noTsconfigAlias(file);
289
+ return insertAt(text, open.index + open[0].length, `
290
+ "paths": { ${entry} },`);
291
+ }
292
+ function addTailwind(info, manifest, exec) {
293
+ const vite = info.framework === "vite";
294
+ const plugin = vite ? "@tailwindcss/vite" : "@tailwindcss/postcss";
295
+ const pkgs = { tailwindcss: pinned(manifest, "tailwindcss"), [plugin]: pinned(manifest, plugin) };
296
+ const viteFile = vite ? firstExisting(info, VITE_CONFIGS) : null;
297
+ if (vite) {
298
+ if (!viteFile) throw new CliError(NO_VITE_TAILWIND);
299
+ editViteTailwind(readText(info, viteFile));
300
+ } else {
301
+ const postcss = firstExisting(info, POSTCSS_CONFIGS);
302
+ if (postcss && !readText(info, postcss).includes("@tailwindcss/postcss")) throw new CliError(NO_POSTCSS_TAILWIND);
303
+ }
304
+ return {
305
+ line: "Adding Tailwind",
306
+ run: async () => {
307
+ const [cmd, args] = installArgs(info.packageManager, pkgs, true);
308
+ await run(exec, info.root, cmd, args);
309
+ if (viteFile) writeText(info, viteFile, editViteTailwind(readText(info, viteFile)));
310
+ else if (!firstExisting(info, POSTCSS_CONFIGS)) writeText(info, "postcss.config.mjs", `export default {
311
+ plugins: {
312
+ '@tailwindcss/postcss': {},
313
+ },
314
+ }
315
+ `);
316
+ }
317
+ };
318
+ }
319
+ function upgradeTailwind(info, manifest, exec) {
320
+ const version = pinned(manifest, "tailwindcss").replace(/^[\s^~>=v]+/, "");
321
+ return { line: "Upgrading Tailwind to v4", run: () => run(exec, info.root, "npx", ["--yes", `@tailwindcss/upgrade@${version}`]) };
322
+ }
323
+ function aliasEdits(info, srcDir, viteText) {
324
+ const edits = [];
325
+ if (!readPaths(info.root)?.paths["@/*"]) {
326
+ if (!existsSync2(join2(info.root, "tsconfig.json"))) throw noTsconfigAlias("tsconfig.json");
327
+ for (const file of ["tsconfig.json", "tsconfig.app.json"]) {
328
+ if (file === "tsconfig.app.json" && !existsSync2(join2(info.root, file))) continue;
329
+ const config = readTsconfig(join2(info.root, file));
330
+ if (!config) throw noTsconfigAlias(file);
331
+ edits.push([file, editTsconfig(readText(info, file), config, file, srcDir)]);
332
+ }
333
+ }
334
+ if (info.framework === "vite") {
335
+ const file = firstExisting(info, VITE_CONFIGS);
336
+ if (!file) throw new CliError(NO_VITE_ALIAS);
337
+ edits.push([file, editViteAlias(viteText(file), srcDir)]);
338
+ }
339
+ return edits;
340
+ }
341
+ function addAlias(info, srcDir, tailwindAddedToVite) {
342
+ aliasEdits(info, srcDir, (file) => tailwindAddedToVite ? editViteTailwind(readText(info, file)) : readText(info, file));
343
+ return {
344
+ line: "Adding the @/ import alias",
345
+ run: async () => {
346
+ for (const [file, text] of aliasEdits(info, srcDir, (f) => readText(info, f))) writeText(info, file, text);
347
+ }
348
+ };
349
+ }
350
+ function needsAlias(info) {
351
+ if (!readPaths(info.root)?.paths["@/*"]) return true;
352
+ if (info.framework !== "vite") return false;
353
+ const file = firstExisting(info, VITE_CONFIGS);
354
+ return !file || !viteHasAlias(maskComments(readText(info, file)));
355
+ }
356
+ function addShadcnConfig(info, css) {
357
+ return {
358
+ line: "Adding the shadcn config",
359
+ run: async () => {
360
+ const config = {
361
+ $schema: "https://ui.shadcn.com/schema.json",
362
+ style: "new-york",
363
+ rsc: info.framework === "next",
364
+ tsx: true,
365
+ tailwind: { config: "", css, baseColor: "neutral", cssVariables: true, prefix: "" },
366
+ iconLibrary: "lucide",
367
+ aliases: { components: "@/components", utils: "@/lib/utils", ui: "@/components/ui", lib: "@/lib", hooks: "@/hooks" }
368
+ };
369
+ writeText(info, "components.json", `${JSON.stringify(config, null, 2)}
370
+ `);
371
+ }
372
+ };
373
+ }
374
+ function stylesheetHasPreflight(info, css) {
375
+ try {
376
+ const text = maskComments(readText(info, css), { line: false });
377
+ return /@import\s+(?:url\(\s*)?(["'])tailwindcss\1/.test(text) || /@tailwind\s+base\b/.test(text);
378
+ } catch {
379
+ return false;
380
+ }
381
+ }
382
+ function planSetup(info, manifest, exec) {
383
+ const steps = [];
384
+ const css = typeof info.shadcn?.tailwind?.css === "string" ? info.shadcn.tailwind.css : info.shadcn ? null : findGlobalStylesheet(info);
385
+ const srcDir = existsSync2(join2(info.root, "src")) ? "src" : ".";
386
+ if (info.tailwindMajor === null) steps.push(addTailwind(info, manifest, exec));
387
+ else if (info.tailwindMajor < 4) steps.push(upgradeTailwind(info, manifest, exec));
388
+ if (info.shadcn === null) {
389
+ if (needsAlias(info)) steps.push(addAlias(info, srcDir, info.tailwindMajor === null && info.framework === "vite"));
390
+ steps.push(addShadcnConfig(info, css));
391
+ }
392
+ return { steps, preflight: css !== null && stylesheetHasPreflight(info, css) };
393
+ }
394
+
395
+ // src/connect/secret-backends.ts
396
+ var SECRET_SERVICE = "designsource";
397
+ var STORE_TIMEOUT_MS = 15e3;
398
+ var PROJECT_ID = /^[A-Za-z0-9_-]+$/;
399
+ var TOKEN_SHAPE = /^[A-Za-z0-9._-]+$/;
400
+ function assertProjectId(projectId) {
401
+ if (!PROJECT_ID.test(projectId)) throw new CliError("Unexpected project id from the API.");
402
+ }
403
+ function readOutput(result) {
404
+ if (result.code !== 0) return null;
405
+ const value = result.output.trimEnd();
406
+ return value === "" ? null : value;
407
+ }
408
+ function readToken(result) {
409
+ const value = readOutput(result);
410
+ return value !== null && TOKEN_SHAPE.test(value) ? value : null;
411
+ }
412
+ function keychain(exec, cwd) {
413
+ const run2 = (args, opts = {}) => exec("security", args, { cwd, timeoutMs: STORE_TIMEOUT_MS, ...opts });
414
+ const backend = {
415
+ where: "keychain",
416
+ async put(projectId, _name, token) {
417
+ assertProjectId(projectId);
418
+ if (!TOKEN_SHAPE.test(token)) return null;
419
+ const wrote = await run2(["-i"], { input: `add-generic-password -U -s ${SECRET_SERVICE} -a "${projectId}" -w "${token}"
420
+ ` });
421
+ if (wrote.code === 0 && await backend.get(projectId, void 0) === token) return {};
422
+ await backend.remove(projectId);
423
+ return null;
424
+ },
425
+ async get(projectId) {
426
+ assertProjectId(projectId);
427
+ return readToken(await run2(["find-generic-password", "-s", SECRET_SERVICE, "-a", projectId, "-w"], { stdoutOnly: true }));
428
+ },
429
+ async remove(projectId) {
430
+ assertProjectId(projectId);
431
+ await run2(["delete-generic-password", "-s", SECRET_SERVICE, "-a", projectId]);
432
+ }
433
+ };
434
+ return backend;
435
+ }
436
+ function secretService(exec, cwd) {
437
+ const run2 = (args, opts = {}) => exec("secret-tool", args, { cwd, timeoutMs: STORE_TIMEOUT_MS, ...opts });
438
+ const backend = {
439
+ where: "secret-service",
440
+ async put(projectId, name, token) {
441
+ assertProjectId(projectId);
442
+ const wrote = await run2(["store", `--label=${SECRET_SERVICE} ${name}`, "service", SECRET_SERVICE, "project", projectId], { input: token });
443
+ if (wrote.code === 0 && await backend.get(projectId, void 0) === token) return {};
444
+ await backend.remove(projectId);
445
+ return null;
446
+ },
447
+ async get(projectId) {
448
+ assertProjectId(projectId);
449
+ return readToken(await run2(["lookup", "service", SECRET_SERVICE, "project", projectId], { stdoutOnly: true }));
450
+ },
451
+ async remove(projectId) {
452
+ assertProjectId(projectId);
453
+ await run2(["clear", "service", SECRET_SERVICE, "project", projectId]);
454
+ }
455
+ };
456
+ return backend;
457
+ }
458
+ var DPAPI_ENCRYPT = [
459
+ // PowerShell 5.1 otherwise writes progress records (`#< CLIXML`) to stderr.
460
+ "$ProgressPreference = 'SilentlyContinue'",
461
+ "$ErrorActionPreference = 'Stop'",
462
+ "$plain = [Console]::In.ReadToEnd()",
463
+ "[Console]::Out.Write((ConvertTo-SecureString -String $plain -AsPlainText -Force | ConvertFrom-SecureString))"
464
+ ].join("\n");
465
+ var DPAPI_DECRYPT = [
466
+ "$ProgressPreference = 'SilentlyContinue'",
467
+ "$ErrorActionPreference = 'Stop'",
468
+ "$secure = ConvertTo-SecureString -String ([Console]::In.ReadToEnd().Trim())",
469
+ "$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)",
470
+ "try { [Console]::Out.Write([Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) }"
471
+ ].join("\n");
472
+ function powershellArgs(script) {
473
+ return ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")];
474
+ }
475
+ function dpapi(exec, cwd) {
476
+ const run2 = (script, input) => exec("powershell", powershellArgs(script), { cwd, timeoutMs: STORE_TIMEOUT_MS, input, stdoutOnly: true });
477
+ const backend = {
478
+ where: "dpapi",
479
+ async put(projectId, _name, token) {
480
+ assertProjectId(projectId);
481
+ const ciphertext = readOutput(await run2(DPAPI_ENCRYPT, token));
482
+ if (ciphertext === null || !/^[0-9a-fA-F]+$/.test(ciphertext)) return null;
483
+ return await backend.get(projectId, ciphertext) === token ? { secret: ciphertext } : null;
484
+ },
485
+ async get(_projectId, secret) {
486
+ if (!secret) return null;
487
+ return readToken(await run2(DPAPI_DECRYPT, secret));
488
+ },
489
+ // The ciphertext lives in the credentials file, which the store rewrites without it.
490
+ async remove() {
491
+ }
492
+ };
493
+ return backend;
494
+ }
495
+ function backendFor(where, exec, cwd) {
496
+ if (where === "keychain") return keychain(exec, cwd);
497
+ if (where === "secret-service") return secretService(exec, cwd);
498
+ return dpapi(exec, cwd);
499
+ }
500
+ async function secretServiceAnswers(exec, cwd) {
501
+ const probe = await exec("secret-tool", ["lookup", "service", SECRET_SERVICE, "project", "designsource-probe"], { cwd, timeoutMs: STORE_TIMEOUT_MS });
502
+ return (probe.code === 0 || probe.code === 1) && !/d-?bus/i.test(probe.output);
503
+ }
504
+ async function chooseBackend(opts) {
505
+ const { platform, exec, cwd, token } = opts;
506
+ if (platform === "darwin") return TOKEN_SHAPE.test(token) ? keychain(exec, cwd) : null;
507
+ if (platform === "linux") return await secretServiceAnswers(exec, cwd) ? secretService(exec, cwd) : null;
508
+ if (platform === "win32") return dpapi(exec, cwd);
509
+ return null;
510
+ }
511
+
512
+ // src/connect/apps.ts
513
+ var SPECS = [
514
+ { id: "claude", label: "Claude Code", file: ".mcp.json", format: { kind: "json", key: "mcpServers", stdioType: false } },
515
+ { id: "cursor", label: "Cursor", file: ".cursor/mcp.json", format: { kind: "json", key: "mcpServers", stdioType: true } },
516
+ { id: "vscode", label: "VS Code", file: ".vscode/mcp.json", format: { kind: "json", key: "servers", stdioType: true } },
517
+ { id: "codex", label: "Codex", file: ".codex/config.toml", format: { kind: "toml" } },
518
+ { id: "gemini", label: "Gemini CLI", file: ".gemini/settings.json", format: { kind: "json", key: "mcpServers", stdioType: false } }
519
+ ];
520
+ var APPS = SPECS.map(({ id, label, file, format }) => ({
521
+ id,
522
+ label,
523
+ file,
524
+ format: format.kind,
525
+ key: format.kind === "json" ? format.key : "mcp_servers"
526
+ }));
527
+ function serverEntry(projectId) {
528
+ assertProjectId(projectId);
529
+ return { command: "npx", args: ["-y", "designsource@latest", "mcp", "--project", projectId] };
530
+ }
531
+ function detectApps({ env, platform, home, exists, onPath: onPath2 }) {
532
+ const path = platform === "win32" ? win32 : posix3;
533
+ const inHome = (...parts) => path.join(home, ...parts);
534
+ const bundle = (name) => platform === "darwin" && exists(`/Applications/${name}.app`);
535
+ const appData = platform === "darwin" ? inHome("Library", "Application Support") : platform === "win32" ? env.APPDATA || inHome("AppData", "Roaming") : env.XDG_CONFIG_HOME && posix3.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : inHome(".config");
536
+ const found = {
537
+ claude: () => onPath2("claude") || exists(inHome(".claude")) || exists(inHome(".claude.json")),
538
+ cursor: () => onPath2("cursor") || exists(inHome(".cursor")) || bundle("Cursor"),
539
+ vscode: () => onPath2("code") || onPath2("code-insiders") || exists(path.join(appData, "Code")) || exists(path.join(appData, "Code - Insiders")) || bundle("Visual Studio Code") || bundle("Visual Studio Code - Insiders"),
540
+ codex: () => onPath2("codex") || exists(inHome(".codex")),
541
+ gemini: () => onPath2("gemini") || exists(inHome(".gemini"))
542
+ };
543
+ return SPECS.map((s) => s.id).filter((id) => found[id]());
544
+ }
545
+ function planAppFile(root, app2, projectId) {
546
+ const spec = SPECS.find((s) => s.id === app2);
547
+ const entry = spec.format.kind === "json" && spec.format.stdioType ? { type: "stdio", ...serverEntry(projectId) } : serverEntry(projectId);
548
+ const abs = resolveInside(root, spec.file);
549
+ let text = null;
550
+ if (existsSync3(abs)) {
551
+ try {
552
+ text = readFileSync3(abs, "utf8");
553
+ } catch {
554
+ throw new CliError(`Could not read ${spec.file}.`);
555
+ }
556
+ }
557
+ return spec.format.kind === "toml" ? planToml(spec.file, text, projectId) : planJson(spec.file, text, spec.format.key, entry, projectId);
558
+ }
559
+ function namesProject(words, projectId) {
560
+ return words.some((w, i) => w === "--project" && words[i + 1] === projectId || w === `--project=${projectId}`);
561
+ }
562
+ function entryWords(entry) {
563
+ if (!isObject(entry)) return [];
564
+ const words = typeof entry.command === "string" ? entry.command.split(/\s+/) : [];
565
+ if (Array.isArray(entry.args)) {
566
+ for (const a of entry.args) if (typeof a === "string") words.push(a);
567
+ }
568
+ return words;
569
+ }
570
+ function isObject(value) {
571
+ return typeof value === "object" && value !== null && !Array.isArray(value);
572
+ }
573
+ function carries(value) {
574
+ return value !== void 0 && !(isObject(value) && Object.keys(value).length === 0);
575
+ }
576
+ function planJson(path, text, key, entry, projectId) {
577
+ if (text === null || text.trim() === "") return { path, status: "create", contents: `${JSON.stringify({ [key]: { designsource: entry } }, null, 2)}
578
+ ` };
579
+ const manual = { path, status: "manual", contents: null, manualEntry: `"designsource": ${JSON.stringify(entry, null, 2)}` };
580
+ const bom = text.startsWith("\uFEFF") ? "\uFEFF" : "";
581
+ const body = text.slice(bom.length);
582
+ if (maskComments(body) !== body) return manual;
583
+ let parsed;
584
+ try {
585
+ parsed = JSON.parse(body);
586
+ } catch {
587
+ return manual;
588
+ }
589
+ if (!isObject(parsed)) return manual;
590
+ const servers = Object.hasOwn(parsed, key) ? parsed[key] : void 0;
591
+ if (servers !== void 0 && !isObject(servers)) return manual;
592
+ const existing = servers && Object.hasOwn(servers, "designsource") ? servers.designsource : void 0;
593
+ if (existing !== void 0 && namesProject(entryWords(existing), projectId)) {
594
+ return { path, status: "unchanged", contents: text, hasEnv: isObject(existing) && carries(existing.env) };
595
+ }
596
+ return { path, status: "update", contents: bom + insertJsonEntry(body, key, entry) };
597
+ }
598
+ var WS = " \n\r";
599
+ function skipWs(text, i) {
600
+ while (i < text.length && WS.includes(text[i])) i++;
601
+ return i;
602
+ }
603
+ function skipString(text, i) {
604
+ let j = i + 1;
605
+ while (text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
606
+ return j + 1;
607
+ }
608
+ function skipValue(text, i) {
609
+ const c = text[i];
610
+ if (c === '"') return skipString(text, i);
611
+ if (c === "{" || c === "[") {
612
+ let depth = 0;
613
+ let j2 = i;
614
+ for (; ; ) {
615
+ const d = text[j2];
616
+ if (d === '"') {
617
+ j2 = skipString(text, j2);
618
+ continue;
619
+ }
620
+ if (d === "{" || d === "[") depth++;
621
+ else if (d === "}" || d === "]") {
622
+ depth--;
623
+ if (depth === 0) return j2 + 1;
624
+ }
625
+ j2++;
626
+ }
627
+ }
628
+ let j = i;
629
+ while (j < text.length && !",}]".includes(text[j]) && !WS.includes(text[j])) j++;
630
+ return j;
631
+ }
632
+ function objectMembers(text, open) {
633
+ const members = [];
634
+ let i = skipWs(text, open + 1);
635
+ if (text[i] === "}") return { members, close: i };
636
+ for (; ; ) {
637
+ const keyStart = i;
638
+ const keyEnd = skipString(text, i);
639
+ const valueStart = skipWs(text, skipWs(text, keyEnd) + 1);
640
+ const valueEnd = skipValue(text, valueStart);
641
+ members.push({ key: JSON.parse(text.slice(keyStart, keyEnd)), keyStart, valueStart, valueEnd });
642
+ i = skipWs(text, valueEnd);
643
+ if (text[i] !== ",") return { members, close: i };
644
+ i = skipWs(text, i + 1);
645
+ }
646
+ }
647
+ function lastMember(members, key) {
648
+ return members.filter((m) => m.key === key).at(-1);
649
+ }
650
+ function ownLineIndent(text, pos) {
651
+ const before = text.slice(text.lastIndexOf("\n", pos - 1) + 1, pos);
652
+ return /^[ \t]*$/.test(before) ? before : null;
653
+ }
654
+ function lineIndent(text, pos) {
655
+ return /^[ \t]*/.exec(text.slice(text.lastIndexOf("\n", pos - 1) + 1))[0];
656
+ }
657
+ function render(value, unit, indent, eol) {
658
+ return JSON.stringify(value, null, unit).split("\n").join(eol + indent);
659
+ }
660
+ function insertJsonEntry(text, key, entry) {
661
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
662
+ const open = skipWs(text, 0);
663
+ const top = objectMembers(text, open);
664
+ const firstTop = top.members[0];
665
+ const unit = firstTop && text.slice(open + 1, firstTop.keyStart).includes("\n") && ownLineIndent(text, firstTop.keyStart) || " ";
666
+ const servers = lastMember(top.members, key);
667
+ if (!servers) {
668
+ const value = { designsource: entry };
669
+ if (!firstTop) return text.slice(0, open + 1) + eol + unit + `${JSON.stringify(key)}: ` + render(value, unit, unit, eol) + eol + text.slice(top.close);
670
+ const indent2 = text.slice(open + 1, firstTop.keyStart).includes("\n") ? ownLineIndent(text, firstTop.keyStart) : null;
671
+ if (indent2 === null) return text.slice(0, open + 1) + `${JSON.stringify(key)}: ${JSON.stringify(value)}, ` + text.slice(open + 1);
672
+ return text.slice(0, open + 1) + eol + indent2 + `${JSON.stringify(key)}: ` + render(value, unit, indent2, eol) + "," + text.slice(open + 1);
673
+ }
674
+ const inner = objectMembers(text, servers.valueStart);
675
+ const existing = lastMember(inner.members, "designsource");
676
+ if (existing) {
677
+ const indent2 = ownLineIndent(text, existing.keyStart);
678
+ const value = indent2 === null ? JSON.stringify(entry) : render(entry, unit, indent2, eol);
679
+ return text.slice(0, existing.valueStart) + value + text.slice(existing.valueEnd);
680
+ }
681
+ const first = inner.members[0];
682
+ const last = inner.members.at(-1);
683
+ if (!first || !last) {
684
+ if (ownLineIndent(text, servers.keyStart) === null && !text.slice(servers.valueStart + 1, inner.close).includes("\n")) {
685
+ return text.slice(0, servers.valueStart + 1) + `"designsource": ${JSON.stringify(entry)}` + text.slice(inner.close);
686
+ }
687
+ const outer = lineIndent(text, servers.keyStart);
688
+ const indent2 = outer + unit;
689
+ return text.slice(0, servers.valueStart + 1) + eol + indent2 + '"designsource": ' + render(entry, unit, indent2, eol) + eol + outer + text.slice(inner.close);
690
+ }
691
+ const indent = text.slice(servers.valueStart + 1, first.keyStart).includes("\n") ? ownLineIndent(text, first.keyStart) : null;
692
+ const addition = indent === null ? `, "designsource": ${JSON.stringify(entry)}` : `,${eol}${indent}"designsource": ${render(entry, unit, indent, eol)}`;
693
+ return text.slice(0, last.valueEnd) + addition + text.slice(last.valueEnd);
694
+ }
695
+ var OURS = ["mcp_servers", "designsource"];
696
+ function codexTable(projectId, eol) {
697
+ const { command, args } = serverEntry(projectId);
698
+ return [`[mcp_servers.designsource]`, `command = "${command}"`, `args = [${args.map((a) => `"${a}"`).join(", ")}]`, "startup_timeout_sec = 60", ""].join(eol);
699
+ }
700
+ function tomlLines(text) {
701
+ const lines = [];
702
+ let inString = null;
703
+ let depth = 0;
704
+ let start = 0;
705
+ for (; ; ) {
706
+ const nl = text.indexOf("\n", start);
707
+ const end = nl === -1 ? text.length : nl;
708
+ lines.push({ start, end, free: inString === null && depth === 0 });
709
+ let i = start;
710
+ while (i < end) {
711
+ if (inString !== null) {
712
+ if (inString === '"""' && text[i] === "\\") i += 2;
713
+ else if (text.startsWith(inString, i)) {
714
+ inString = null;
715
+ i += 3;
716
+ } else i++;
717
+ continue;
718
+ }
719
+ const c = text[i];
720
+ if (c === "#") break;
721
+ if (text.startsWith('"""', i) || text.startsWith("'''", i)) {
722
+ inString = text.slice(i, i + 3);
723
+ i += 3;
724
+ } else if (c === '"' || c === "'") {
725
+ i++;
726
+ while (i < end && text[i] !== c) i += c === '"' && text[i] === "\\" ? 2 : 1;
727
+ i++;
728
+ } else {
729
+ if (c === "[" || c === "{") depth++;
730
+ else if ((c === "]" || c === "}") && depth > 0) depth--;
731
+ i++;
732
+ }
733
+ }
734
+ if (nl === -1) return lines;
735
+ start = nl + 1;
736
+ }
737
+ }
738
+ function skipSpaces(s, i) {
739
+ while (s[i] === " " || s[i] === " ") i++;
740
+ return i;
741
+ }
742
+ function parseKeyPath(s, i) {
743
+ const path = [];
744
+ for (; ; ) {
745
+ i = skipSpaces(s, i);
746
+ if (s[i] === '"') {
747
+ let j = i + 1;
748
+ while (j < s.length && s[j] !== '"') j += s[j] === "\\" ? 2 : 1;
749
+ if (j >= s.length) return null;
750
+ const raw = s.slice(i, j + 1);
751
+ path.push(jsonOr(raw));
752
+ i = j + 1;
753
+ } else if (s[i] === "'") {
754
+ const j = s.indexOf("'", i + 1);
755
+ if (j === -1) return null;
756
+ path.push(s.slice(i + 1, j));
757
+ i = j + 1;
758
+ } else {
759
+ const bare = /^[A-Za-z0-9_-]+/.exec(s.slice(i));
760
+ if (!bare) return null;
761
+ path.push(bare[0]);
762
+ i += bare[0].length;
763
+ }
764
+ i = skipSpaces(s, i);
765
+ if (s[i] !== ".") return { path, end: i };
766
+ i++;
767
+ }
768
+ }
769
+ function jsonOr(raw) {
770
+ try {
771
+ return JSON.parse(raw);
772
+ } catch {
773
+ return raw.slice(1, -1);
774
+ }
775
+ }
776
+ function tomlHeader(s) {
777
+ const i = skipSpaces(s, 0);
778
+ if (s[i] !== "[") return null;
779
+ const array = s[i + 1] === "[";
780
+ const key = parseKeyPath(s, i + (array ? 2 : 1));
781
+ if (!key || !s.startsWith(array ? "]]" : "]", key.end)) return null;
782
+ return { path: key.path, array };
783
+ }
784
+ function tomlKey(s) {
785
+ const key = parseKeyPath(s, 0);
786
+ if (!key || s[key.end] !== "=") return null;
787
+ return { path: key.path, valueAt: key.end + 1 };
788
+ }
789
+ function tomlStrings(text, from) {
790
+ const out = [];
791
+ let i = skipSpaces(text, from);
792
+ let depth = 0;
793
+ do {
794
+ const c = text[i];
795
+ if (c === void 0) break;
796
+ if (text.startsWith('"""', i) || text.startsWith("'''", i)) {
797
+ const close = text.indexOf(text.slice(i, i + 3), i + 3);
798
+ const end = close === -1 ? text.length : close;
799
+ out.push(text.slice(i + 3, end));
800
+ i = end + 3;
801
+ } else if (c === '"' || c === "'") {
802
+ let j = i + 1;
803
+ while (j < text.length && text[j] !== c && text[j] !== "\n") j += c === '"' && text[j] === "\\" ? 2 : 1;
804
+ out.push(c === '"' ? jsonOr(text.slice(i, j + 1)) : text.slice(i + 1, j));
805
+ i = j + 1;
806
+ } else if (c === "#") {
807
+ while (i < text.length && text[i] !== "\n") i++;
808
+ } else if (c === "[" || c === "{") {
809
+ depth++;
810
+ i++;
811
+ } else if (c === "]" || c === "}") {
812
+ depth--;
813
+ i++;
814
+ } else if (depth === 0) {
815
+ break;
816
+ } else i++;
817
+ } while (depth > 0);
818
+ return out;
819
+ }
820
+ var startsWithPath = (path, prefix) => prefix.every((p, i) => path[i] === p);
821
+ var samePath = (a, b) => a.length === b.length && startsWithPath(a, b);
822
+ function planToml(path, text, projectId) {
823
+ if (text === null) return { path, status: "create", contents: codexTable(projectId, "\n") };
824
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
825
+ const lines = tomlLines(text).map((line) => ({ ...line, text: text.slice(line.start, line.end).replace(/\r$/, "") }));
826
+ const headers = lines.map((line) => line.free ? tomlHeader(line.text) : null);
827
+ const ours = headers.findIndex((h) => h !== null && !h.array && samePath(h.path, OURS));
828
+ if (ours === -1) {
829
+ let table = [];
830
+ const elsewhere = lines.some((line, n) => {
831
+ if (!line.free) return false;
832
+ const header = headers[n];
833
+ if (header) {
834
+ table = header.path;
835
+ return startsWithPath(header.path, OURS);
836
+ }
837
+ const key = tomlKey(line.text);
838
+ const full = key ? [...table, ...key.path] : [];
839
+ return key !== null && (startsWithPath(full, OURS) || samePath(full, ["mcp_servers"]));
840
+ });
841
+ if (elsewhere) return { path, status: "manual", contents: null, manualEntry: codexTable(projectId, "\n").trimEnd() };
842
+ const separator = text.trim() === "" ? null : /\r?\n\r?\n$/.test(text) ? "" : /\n$/.test(text) ? eol : eol + eol;
843
+ return { path, status: "update", contents: separator === null ? codexTable(projectId, eol) : text + separator + codexTable(projectId, eol) };
844
+ }
845
+ const words = [];
846
+ let hasEnv = false;
847
+ for (let n = ours + 1; n < lines.length && !headers[n]; n++) {
848
+ const line = lines[n];
849
+ const key = line.free ? tomlKey(line.text) : null;
850
+ if (key && key.path.length === 1 && (key.path[0] === "command" || key.path[0] === "args")) {
851
+ const values = tomlStrings(text, line.start + key.valueAt);
852
+ words.push(...key.path[0] === "command" ? values.flatMap((v) => v.split(/\s+/)) : values);
853
+ }
854
+ if (key && key.path[0] === "env" && (key.path.length > 1 || !/^\s*\{\s*\}/.test(line.text.slice(key.valueAt)))) hasEnv = true;
855
+ }
856
+ if (namesProject(words, projectId)) {
857
+ for (let n = ours + 1; n < lines.length && !hasEnv; n++) {
858
+ const header = headers[n];
859
+ if (!header || header.array || !samePath(header.path, [...OURS, "env"])) continue;
860
+ for (let m = n + 1; m < lines.length && !headers[m]; m++) if (lines[m].free && tomlKey(lines[m].text)) hasEnv = true;
861
+ }
862
+ return { path, status: "unchanged", contents: text, hasEnv };
863
+ }
864
+ let next = ours + 1;
865
+ while (next < lines.length && !(headers[next] && !startsWithPath(headers[next].path, OURS))) next++;
866
+ const stray = headers.some((h, n) => h !== null && (n < ours || n >= next) && startsWithPath(h.path, OURS));
867
+ if (stray) return { path, status: "manual", contents: null, manualEntry: codexTable(projectId, "\n").trimEnd() };
868
+ let last = next - 1;
869
+ while (last > ours && lines[last].free && /^\s*(#.*)?$/.test(lines[last].text)) last--;
870
+ const cut = Math.min(lines[last].end + 1, text.length);
871
+ return { path, status: "update", contents: text.slice(0, lines[ours].start) + codexTable(projectId, eol) + text.slice(cut) };
872
+ }
873
+
3
874
  // src/args.ts
4
875
  var FRAMEWORKS = ["next", "vue", "svelte", "angular", "css"];
5
876
  var INTEGRATE_FRAMEWORKS = ["vue", "svelte", "angular", "css"];
@@ -9,6 +880,8 @@ var INTEGRATE_DEFAULT_FOLDER = ".";
9
880
  var USAGE = `designsource <command> [options] (also installed as: dss)
10
881
 
11
882
  Commands
883
+ add [names\u2026] add your design system's UI kit to this React app (theme, components, libraries)
884
+ connect connect your coding apps (Claude Code, Cursor, VS Code, Codex, Gemini CLI) to this design system
12
885
  integrate [folder] add the design system to an existing app \u2014 writes design-system/ (default folder: .)
13
886
  create [folder] new Next.js project with the tokens, every component and your mockup page (default folder: ${CREATE_DEFAULT_FOLDER})
14
887
  mcp serve the design system to a coding agent over MCP (stdio) \u2014 for .mcp.json, not for a terminal
@@ -34,24 +907,53 @@ ${TOKEN_LINE}
34
907
  ${API_LINE}
35
908
  --force overwrite files the bundle writes when design-system/ already exists
36
909
  `;
37
- var MCP_USAGE = `designsource mcp [--token <project token>] [--api <origin>]
910
+ var ADD_USAGE = `designsource add [names\u2026] [--yes] [--all] [--force] [--skip-install] [--token <project token>] [--api <origin>]
911
+
912
+ Adds your design system's UI kit to the React app in this folder: the theme in its global stylesheet, the
913
+ components and the libraries they import. Sets up Tailwind and the shadcn config when the app has none.
914
+ Run it again to pull updates: it refreshes the theme and every component it added before.
915
+ names components to add, plus the kit files they import (default: what an earlier run added, else asked)
916
+ --all every component, no question
917
+ --yes no questions (also outside a terminal): all components on a first run, edited files kept
918
+ --force replace component files add did not write, and edited ones
919
+ --skip-install write the files, then print the install command instead of running it
920
+ --token the project token (workbench \u2192 Project settings); or DS_SYNC_TOKEN
921
+ --api API origin (default ${DEFAULT_API_ORIGIN})
922
+ `;
923
+ var APP_IDS = APPS.map((a) => a.id);
924
+ var CONNECT_USAGE = `designsource connect [--apps ${APP_IDS.join(",")}] [--yes] [--token <project token>] [--api <origin>]
925
+ designsource connect --forget [--project <id>]
926
+
927
+ Connects your coding apps to this design system: saves the project token once, privately, on this computer, and writes
928
+ each app's MCP settings in the project folder (the nearest folder holding .git, else this one). The settings hold no
929
+ token, so they are safe to commit; a teammate runs npx designsource connect once to save their own.
930
+ --apps the apps to set up, comma-separated: ${APP_IDS.join(",")} (default: picked, the ones found ticked)
931
+ --yes no questions: the apps found on this computer (also outside a terminal)
932
+ ${TOKEN_LINE}
933
+ ${API_LINE}
934
+ --forget remove the token saved for this folder from this computer; settings files are left as they are
935
+ --project with --forget: which project, when several are connected to this folder
936
+ `;
937
+ var MCP_USAGE = `designsource mcp [--project <id>] [--token <project token>] [--api <origin>]
38
938
 
39
939
  Serves the design system to a coding agent over MCP on stdin/stdout. Put it in your MCP
40
- client's config (Claude Code, Cursor, Codex\u2026); the token comes from --token or DS_SYNC_TOKEN.
41
- Read-only: tokens, component source, the mockup page and an integration guide.
940
+ client's config (Claude Code, Cursor, Codex\u2026); npx designsource connect writes the entry for you.
941
+ Tokens, component source, the mockup page, an integration guide, and add_ui_kit, which adds the UI kit to the React app in the current folder.
42
942
 
43
943
  Options
44
- ${TOKEN_LINE}
944
+ --project the project id; the token comes from this computer's saved one (npx designsource connect)
945
+ --token the project token (workbench \u2192 Project settings); or DS_SYNC_TOKEN, which wins over a saved one
45
946
  ${API_LINE}
46
947
  `;
47
948
  function usageFor(verb) {
48
- return verb === "create" ? CREATE_USAGE : verb === "integrate" ? INTEGRATE_USAGE : verb === "mcp" ? MCP_USAGE : USAGE;
949
+ return verb === "add" ? ADD_USAGE : verb === "connect" ? CONNECT_USAGE : verb === "create" ? CREATE_USAGE : verb === "integrate" ? INTEGRATE_USAGE : verb === "mcp" ? MCP_USAGE : USAGE;
49
950
  }
50
951
  var ArgsError = class extends Error {
51
952
  constructor(message, usage) {
52
953
  super(message);
53
954
  this.usage = usage;
54
955
  }
956
+ usage;
55
957
  };
56
958
  function baseArgs(env) {
57
959
  const args = { api: DEFAULT_API_ORIGIN, force: false };
@@ -59,14 +961,17 @@ function baseArgs(env) {
59
961
  return args;
60
962
  }
61
963
  var HELP = /* @__PURE__ */ new Set(["--help", "-h", "help"]);
964
+ var USE_VERBS = "Use add, connect, integrate, create or mcp.";
62
965
  function parseArgs(argv, env) {
63
966
  const [first, ...rest] = argv;
64
967
  if (first === void 0) return { kind: "menu" };
65
968
  if (HELP.has(first)) return { kind: "help", verb: void 0 };
66
969
  if (first === "create" || first === "integrate") return parseVerb(first, rest, env);
67
970
  if (first === "mcp") return parseMcp(rest, env);
68
- if (first.startsWith("-")) throw new ArgsError("Missing command. Use integrate, create or mcp.", USAGE);
69
- throw new ArgsError(`Unknown command "${first}". Use integrate, create or mcp.`, USAGE);
971
+ if (first === "add") return parseAdd(rest, env);
972
+ if (first === "connect") return parseConnect(rest, env);
973
+ if (first.startsWith("-")) throw new ArgsError(`Missing command. ${USE_VERBS}`, USAGE);
974
+ throw new ArgsError(`Unknown command "${first}". ${USE_VERBS}`, USAGE);
70
975
  }
71
976
  function parseApiOrigin(value, usage) {
72
977
  const origin = value.replace(/\/+$/, "");
@@ -78,6 +983,72 @@ function parseApiOrigin(value, usage) {
78
983
  if (!parsed || !parsed.host) throw new ArgsError(`Option --api needs a full origin such as http://localhost:3001 (got "${value}")`, usage);
79
984
  return origin;
80
985
  }
986
+ var ADD_SWITCHES = { yes: "yes", all: "all", force: "force", "skip-install": "skipInstall" };
987
+ function parseAdd(argv, env) {
988
+ const args = { components: [], api: DEFAULT_API_ORIGIN, yes: false, all: false, force: false, skipInstall: false };
989
+ if (env.DS_SYNC_TOKEN) args.token = env.DS_SYNC_TOKEN;
990
+ for (let i = 0; i < argv.length; i++) {
991
+ const arg = argv[i];
992
+ if (arg === "--help" || arg === "-h") return { kind: "help", verb: "add" };
993
+ if (!arg.startsWith("-")) {
994
+ args.components.push(arg);
995
+ continue;
996
+ }
997
+ if (!arg.startsWith("--")) throw new ArgsError(`Unknown option ${arg}`, ADD_USAGE);
998
+ const eq = arg.indexOf("=");
999
+ const key = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
1000
+ if (key in ADD_SWITCHES) {
1001
+ if (eq !== -1) throw new ArgsError(`Option --${key} takes no value`, ADD_USAGE);
1002
+ args[ADD_SWITCHES[key]] = true;
1003
+ continue;
1004
+ }
1005
+ if (key !== "token" && key !== "api") throw new ArgsError(`Unknown option --${key}`, ADD_USAGE);
1006
+ const value = eq === -1 ? argv[++i] : arg.slice(eq + 1);
1007
+ if (value === void 0) throw new ArgsError(`Option --${key} needs a value`, ADD_USAGE);
1008
+ if (key === "token") args.token = value;
1009
+ else {
1010
+ args.api = parseApiOrigin(value, ADD_USAGE);
1011
+ args.apiGiven = true;
1012
+ }
1013
+ }
1014
+ return { kind: "add", args };
1015
+ }
1016
+ function appsIn(value) {
1017
+ const ids = [...new Set(value.split(/[\s,]+/).filter(Boolean))];
1018
+ if (ids.length === 0) throw new ArgsError(`Option --apps needs one or more of ${APP_IDS.join(", ")}`, CONNECT_USAGE);
1019
+ const unknown = ids.find((id) => !APP_IDS.includes(id));
1020
+ if (unknown !== void 0) throw new ArgsError(`Unknown app "${unknown}". Use ${APP_IDS.slice(0, -1).join(", ")} or ${APP_IDS.at(-1)}.`, CONNECT_USAGE);
1021
+ return ids;
1022
+ }
1023
+ var CONNECT_SWITCHES = { yes: "yes", forget: "forget" };
1024
+ function parseConnect(argv, env) {
1025
+ const args = { api: DEFAULT_API_ORIGIN, yes: false, forget: false };
1026
+ if (env.DS_SYNC_TOKEN) args.token = env.DS_SYNC_TOKEN;
1027
+ for (let i = 0; i < argv.length; i++) {
1028
+ const arg = argv[i];
1029
+ if (arg === "--help" || arg === "-h") return { kind: "help", verb: "connect" };
1030
+ if (!arg.startsWith("--")) throw new ArgsError(arg.startsWith("-") ? `Unknown option ${arg}` : "connect takes no folder: run it in the project folder", CONNECT_USAGE);
1031
+ const eq = arg.indexOf("=");
1032
+ const key = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
1033
+ if (key in CONNECT_SWITCHES) {
1034
+ if (eq !== -1) throw new ArgsError(`Option --${key} takes no value`, CONNECT_USAGE);
1035
+ args[CONNECT_SWITCHES[key]] = true;
1036
+ continue;
1037
+ }
1038
+ if (key !== "apps" && key !== "token" && key !== "api" && key !== "project") throw new ArgsError(`Unknown option --${key}`, CONNECT_USAGE);
1039
+ const value = eq === -1 ? argv[++i] : arg.slice(eq + 1);
1040
+ if (value === void 0) throw new ArgsError(`Option --${key} needs a value`, CONNECT_USAGE);
1041
+ if (key === "apps") args.apps = appsIn(value);
1042
+ else if (key === "token") args.token = value;
1043
+ else if (key === "project") args.project = value;
1044
+ else {
1045
+ args.api = parseApiOrigin(value, CONNECT_USAGE);
1046
+ args.apiGiven = true;
1047
+ }
1048
+ }
1049
+ if (args.project !== void 0 && !args.forget) throw new ArgsError("Option --project goes with --forget", CONNECT_USAGE);
1050
+ return { kind: "connect", args };
1051
+ }
81
1052
  function parseMcp(argv, env) {
82
1053
  const args = { api: DEFAULT_API_ORIGIN };
83
1054
  if (env.DS_SYNC_TOKEN) args.token = env.DS_SYNC_TOKEN;
@@ -88,10 +1059,16 @@ function parseMcp(argv, env) {
88
1059
  const eq = arg.indexOf("=");
89
1060
  const key = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
90
1061
  const value = eq === -1 ? argv[++i] : arg.slice(eq + 1);
91
- if (key !== "token" && key !== "api") throw new ArgsError(`Unknown option --${key}`, MCP_USAGE);
1062
+ if (key !== "token" && key !== "api" && key !== "project") throw new ArgsError(`Unknown option --${key}`, MCP_USAGE);
92
1063
  if (value === void 0) throw new ArgsError(`Option --${key} needs a value`, MCP_USAGE);
93
1064
  if (key === "token") args.token = value;
94
- else args.api = parseApiOrigin(value, MCP_USAGE);
1065
+ else if (key === "project") {
1066
+ if (!/^[A-Za-z0-9_-]+$/.test(value)) throw new ArgsError("--project must be a project id from the workbench (letters, digits, - and _).", MCP_USAGE);
1067
+ args.project = value;
1068
+ } else {
1069
+ args.api = parseApiOrigin(value, MCP_USAGE);
1070
+ args.apiGiven = true;
1071
+ }
95
1072
  }
96
1073
  return { kind: "mcp", args };
97
1074
  }
@@ -124,6 +1101,7 @@ function parseVerb(verb, argv, env) {
124
1101
  } else if (key === "api") {
125
1102
  needs();
126
1103
  args.api = parseApiOrigin(value, usage);
1104
+ args.apiGiven = true;
127
1105
  } else throw new ArgsError(`Unknown option --${key}`, usage);
128
1106
  continue;
129
1107
  }
@@ -133,54 +1111,298 @@ function parseVerb(verb, argv, env) {
133
1111
  }
134
1112
  if (verb === "create") {
135
1113
  const { framework: _drop, ...common } = args;
1114
+ void _drop;
136
1115
  return { kind: "create", args: common };
137
1116
  }
138
1117
  return { kind: "integrate", args };
139
1118
  }
140
1119
 
141
- // src/errors.ts
142
- var CliError = class extends Error {
143
- constructor(message, exitCode = 1) {
144
- super(message);
145
- this.exitCode = exitCode;
1120
+ // src/add/detect.ts
1121
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
1122
+ import { join as join3 } from "node:path";
1123
+ var NO_PACKAGE_JSON = "No package.json here. Run this in your React app's folder.";
1124
+ var NO_REACT = "This folder has no React app. Run this in your React app's folder; for Vue, Svelte, Angular or plain CSS use the AI prompt in the workbench's Export dialog.";
1125
+ var OLD_REACT = (major) => `The UI kit needs React 19 \u2014 this app is on React ${major}.`;
1126
+ var NO_TYPESCRIPT = "The UI kit is TypeScript and this app is plain JavaScript. Use the AI prompt in the workbench's Export dialog instead.";
1127
+ var LOCKFILES = [["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["bun.lockb", "bun"], ["bun.lock", "bun"], ["package-lock.json", "npm"]];
1128
+ function majorOf(spec) {
1129
+ if (spec === void 0) return null;
1130
+ const match = /^[\s^~>=v]*(\d+)/.exec(spec);
1131
+ return match ? Number(match[1]) : Number.POSITIVE_INFINITY;
1132
+ }
1133
+ function readJson(path, message) {
1134
+ try {
1135
+ return JSON.parse(readFileSync4(path, "utf8"));
1136
+ } catch {
1137
+ throw new CliError(message);
146
1138
  }
147
- };
148
- var CANCELLED = "Cancelled.";
149
- var TOKEN_MESSAGE = "Project token not recognised. In the workbench open Project settings and copy the project token.";
150
- var UNREACHABLE = (api) => `Could not reach ${api}.`;
151
- var UPDATE_MESSAGE = "This design system needs a newer designsource CLI. Update it (for example `npx designsource@latest`) and run again.";
152
- var PLAN_MESSAGE = "This project's account is on the free plan. Exports need Pro: https://designsource.app/pricing";
153
- function messageForResponse(status, body, api) {
154
- if (status === 401) return TOKEN_MESSAGE;
155
- if (status === 402) return PLAN_MESSAGE;
156
- const serverMessage = typeof body === "object" && body !== null && typeof body.error === "string" ? body.error : null;
157
- if (status === 400) return serverMessage ?? `${api} rejected the request (400).`;
158
- return `${api} answered ${status}.`;
1139
+ }
1140
+ function stringMap(value) {
1141
+ if (typeof value !== "object" || value === null) return {};
1142
+ return Object.fromEntries(Object.entries(value).filter((e) => typeof e[1] === "string"));
1143
+ }
1144
+ function detectApp(root) {
1145
+ const packagePath = join3(root, "package.json");
1146
+ if (!existsSync4(packagePath)) throw new CliError(NO_PACKAGE_JSON);
1147
+ const pkg = readJson(packagePath, "package.json is not valid JSON.");
1148
+ const deps = { ...stringMap(pkg?.dependencies), ...stringMap(pkg?.devDependencies) };
1149
+ const componentsPath = join3(root, "components.json");
1150
+ const shadcn = existsSync4(componentsPath) ? readJson(componentsPath, "components.json is not valid JSON.") : null;
1151
+ return {
1152
+ root,
1153
+ reactMajor: majorOf(deps.react),
1154
+ typescript: "typescript" in deps || existsSync4(join3(root, "tsconfig.json")),
1155
+ tailwindMajor: majorOf(deps.tailwindcss),
1156
+ shadcn,
1157
+ framework: "next" in deps ? "next" : "vite" in deps ? "vite" : "other",
1158
+ packageManager: LOCKFILES.find(([file]) => existsSync4(join3(root, file)))?.[1] ?? "npm",
1159
+ deps
1160
+ };
1161
+ }
1162
+ function assertCanAdd(info) {
1163
+ if (info.reactMajor === null) throw new CliError(NO_REACT);
1164
+ if (info.reactMajor < 19) throw new CliError(OLD_REACT(info.reactMajor));
1165
+ if (!info.typescript) throw new CliError(NO_TYPESCRIPT);
159
1166
  }
160
1167
 
161
- // src/manifest.ts
162
- var malformed = () => new CliError("Unexpected response from the API \u2014 not a starter manifest.");
163
- function validateManifest(json) {
164
- if (typeof json !== "object" || json === null) throw malformed();
165
- const m = json;
166
- if (typeof m.version !== "number") throw malformed();
167
- if (m.version !== 1) throw new CliError(UPDATE_MESSAGE);
168
- if (typeof m.framework !== "string" || !FRAMEWORKS.includes(m.framework)) throw malformed();
169
- if (typeof m.name !== "string" || !Array.isArray(m.files) || !Array.isArray(m.nextSteps)) throw malformed();
170
- for (const f of m.files) {
171
- if (typeof f !== "object" || f === null) throw malformed();
172
- const { path, contents } = f;
173
- if (typeof path !== "string" || typeof contents !== "string") throw malformed();
1168
+ // src/add/exec.ts
1169
+ import { spawn } from "node:child_process";
1170
+ function quoteArg(arg) {
1171
+ return `"${arg.replace(/"/g, '\\"')}"`;
1172
+ }
1173
+ function childEnv(env) {
1174
+ return Object.fromEntries(Object.entries(env).filter(([name]) => name.toUpperCase() !== "DS_SYNC_TOKEN"));
1175
+ }
1176
+ var spawnExec = (cmd, args, { cwd, timeoutMs, input, stdoutOnly }) => new Promise((resolve6) => {
1177
+ let output = "";
1178
+ let child;
1179
+ try {
1180
+ const shell = process.platform === "win32";
1181
+ child = spawn(cmd, shell ? args.map(quoteArg) : args, { cwd, env: childEnv(process.env), stdio: [input === void 0 ? "ignore" : "pipe", "pipe", "pipe"], shell });
1182
+ } catch (e) {
1183
+ resolve6({ code: 127, output: e instanceof Error ? e.message : String(e) });
1184
+ return;
174
1185
  }
175
- if (!m.nextSteps.every((s) => typeof s === "string")) throw malformed();
176
- return { version: 1, framework: m.framework, name: m.name, files: m.files, nextSteps: m.nextSteps };
1186
+ let timedOut = false;
1187
+ const timer = timeoutMs === void 0 ? null : setTimeout(() => {
1188
+ timedOut = true;
1189
+ child.kill("SIGKILL");
1190
+ }, timeoutMs);
1191
+ const done = (result) => {
1192
+ if (timer) clearTimeout(timer);
1193
+ resolve6(timedOut ? { code: result.code === 0 ? 124 : result.code, output: `${result.output.trimEnd()}
1194
+ timed out after ${timeoutMs / 1e3}s` } : result);
1195
+ };
1196
+ child.stdout?.on("data", (chunk) => {
1197
+ output += chunk.toString();
1198
+ });
1199
+ child.stderr?.on("data", (chunk) => {
1200
+ if (!stdoutOnly) output += chunk.toString();
1201
+ });
1202
+ child.on("error", (e) => done({ code: 127, output: output + e.message }));
1203
+ child.on("close", (code2) => done({ code: code2 ?? 124, output }));
1204
+ if (input !== void 0 && child.stdin) {
1205
+ child.stdin.on("error", () => {
1206
+ });
1207
+ child.stdin.end(input);
1208
+ }
1209
+ });
1210
+
1211
+ // src/add/plan-files.ts
1212
+ import { existsSync as existsSync5, readdirSync, readFileSync as readFileSync5 } from "node:fs";
1213
+ import { posix as posix4 } from "node:path";
1214
+
1215
+ // src/add/stamp.ts
1216
+ import { createHash } from "node:crypto";
1217
+ var PREFIX = "// designsource: ";
1218
+ var STAMP_LINE = /^\/\/ designsource: (\S+) ([0-9a-f]{12})\r?$/;
1219
+ var hashOf = (body) => createHash("sha256").update(body.replace(/\r\n/g, "\n")).digest("hex").slice(0, 12);
1220
+ function stampContents(name, contents) {
1221
+ return `${PREFIX}${name} ${hashOf(contents)}
1222
+ ${contents}`;
1223
+ }
1224
+ function readStamp(text) {
1225
+ const end = text.indexOf("\n");
1226
+ if (end === -1) return null;
1227
+ const match = STAMP_LINE.exec(text.slice(0, end));
1228
+ if (!match) return null;
1229
+ const [, name, hash] = match;
1230
+ return { name, hash, edited: hashOf(text.slice(end + 1)) !== hash };
177
1231
  }
178
1232
 
179
- // src/fetch-manifest.ts
180
- async function fetchManifest(opts, fetchImpl = fetch) {
181
- const url = new URL("/api/starter", `${opts.api}/`);
182
- url.searchParams.set("framework", opts.framework);
183
- if (opts.name) url.searchParams.set("name", opts.name);
1233
+ // src/add/plan-files.ts
1234
+ var readText2 = (abs) => {
1235
+ try {
1236
+ return readFileSync5(abs, "utf8");
1237
+ } catch {
1238
+ return null;
1239
+ }
1240
+ };
1241
+ function stampedFiles(root, t) {
1242
+ let entries;
1243
+ try {
1244
+ entries = readdirSync(resolveInside(root, t.uiDir), { withFileTypes: true });
1245
+ } catch {
1246
+ return [];
1247
+ }
1248
+ const found = [];
1249
+ for (const entry of entries) {
1250
+ if (!entry.name.endsWith(".tsx") || !entry.isFile()) continue;
1251
+ const path = posix4.join(t.uiDir, entry.name);
1252
+ const text = readText2(resolveInside(root, path));
1253
+ const stamp2 = text === null ? null : readStamp(text);
1254
+ if (stamp2) found.push({ path, name: stamp2.name });
1255
+ }
1256
+ return found.sort((a, b) => a.path < b.path ? -1 : 1);
1257
+ }
1258
+ function previouslyAdded(root, t) {
1259
+ return stampedFiles(root, t).map((f) => f.name).sort();
1260
+ }
1261
+ var EXPORTS_CN = /export\s+(function|const)\s+cn\b/;
1262
+ function assertKitUtils(root, info, t) {
1263
+ if (info.shadcn !== null) return;
1264
+ const text = readText2(resolveInside(root, t.utilsFile));
1265
+ if (text === null || EXPORTS_CN.test(text)) return;
1266
+ throw new CliError(`${t.utilsFile} exists and has no cn helper, which every kit component imports. Add one (see https://ui.shadcn.com/docs/installation/manual) or rename that file, then run this again.`);
1267
+ }
1268
+ function planFiles(root, t, components, manifest) {
1269
+ const byName = new Map(manifest.components.map((c) => [c.name, c]));
1270
+ const plan = { write: [], replaceForeign: [], edited: [], previouslyAdded: [], gone: [] };
1271
+ for (const name of components) {
1272
+ const component = byName.get(name);
1273
+ if (!component) throw new CliError(`The kit has no component "${name}".`);
1274
+ const path = t.uiDir ? `${t.uiDir}/${component.file}` : component.file;
1275
+ const abs = resolveInside(root, path);
1276
+ plan.write.push({ path, contents: stampContents(name, rewriteForApp(component.contents, t)), component: name });
1277
+ if (!existsSync5(abs)) continue;
1278
+ const text = readText2(abs);
1279
+ const stamp2 = text === null ? null : readStamp(text);
1280
+ if (!stamp2) plan.replaceForeign.push(path);
1281
+ else if (stamp2.edited) plan.edited.push(path);
1282
+ }
1283
+ const utilsAbs = resolveInside(root, t.utilsFile);
1284
+ if (!existsSync5(utilsAbs)) {
1285
+ plan.write.push({ path: t.utilsFile, contents: stampContents("utils", rewriteForApp(manifest.utils, t)), component: "utils" });
1286
+ }
1287
+ const stamped = stampedFiles(root, t);
1288
+ plan.previouslyAdded = stamped.map((f) => f.name).sort();
1289
+ plan.gone = stamped.filter((f) => f.name !== "utils" && !byName.has(f.name)).map((f) => f.path);
1290
+ return plan;
1291
+ }
1292
+
1293
+ // src/add/run-add.ts
1294
+ import { existsSync as existsSync7, readFileSync as readFileSync7, statSync as statSync2 } from "node:fs";
1295
+ import { join as join4 } from "node:path";
1296
+
1297
+ // src/write.ts
1298
+ import { existsSync as existsSync6, mkdirSync, readFileSync as readFileSync6, readdirSync as readdirSync2, rmSync, statSync, writeFileSync as writeFileSync2 } from "node:fs";
1299
+ import { dirname, relative, resolve as resolve2 } from "node:path";
1300
+ function planTarget(cwd, folder, framework, force) {
1301
+ const root = resolve2(cwd, folder);
1302
+ if (!existsSync6(root)) return { root, created: true };
1303
+ if (!statSync(root).isDirectory()) throw new CliError(`${folder} exists and is not a folder.`);
1304
+ if (framework === "next") {
1305
+ if (readdirSync2(root).length > 0 && !force) throw new CliError(`Folder ${folder} is not empty. Pick another name, or pass --force to overwrite the files the starter writes.`);
1306
+ } else if (existsSync6(resolve2(root, "design-system")) && !force) {
1307
+ throw new CliError(`${folder}/design-system/ already exists. Remove it, or pass --force to overwrite the files the bundle writes.`);
1308
+ }
1309
+ return { root, created: false };
1310
+ }
1311
+ function writeFiles(root, files, opts, writeFile = writeFileSync2) {
1312
+ const targets = files.map((f) => ({ file: f, abs: resolveInside(root, f.path) }));
1313
+ if (!opts.force) {
1314
+ const clash = targets.find((t) => existsSync6(t.abs));
1315
+ if (clash) throw new CliError(`${clash.file.path} already exists. Pass --force to overwrite the files the starter writes.`);
1316
+ }
1317
+ const written = [];
1318
+ const previous = /* @__PURE__ */ new Map();
1319
+ const madeDirs = [];
1320
+ let failingPath;
1321
+ try {
1322
+ for (const { file, abs } of targets) {
1323
+ failingPath = file.path;
1324
+ if (!previous.has(file.path)) previous.set(file.path, existsSync6(abs) ? readFileSync6(abs) : void 0);
1325
+ madeDirs.push(...missingDirs(root, dirname(abs)));
1326
+ mkdirSync(dirname(abs), { recursive: true });
1327
+ writeFile(abs, file.path === "package.json" && opts.packageManager ? withPackageManager(file.contents, opts.packageManager) : file.contents);
1328
+ written.push(file.path);
1329
+ }
1330
+ } catch (e) {
1331
+ const code2 = e?.code ?? e.message;
1332
+ if (opts.created) {
1333
+ rmSync(root, { recursive: true, force: true });
1334
+ throw new CliError(`Could not write ${failingPath} (${code2}). Removed ${root} again; nothing was left behind.`);
1335
+ }
1336
+ let restored = 0;
1337
+ let removed = 0;
1338
+ for (const [p, before] of previous) {
1339
+ const abs = resolveInside(root, p);
1340
+ if (before === void 0) {
1341
+ if (existsSync6(abs) && statSync(abs).isFile()) {
1342
+ rmSync(abs, { force: true });
1343
+ removed++;
1344
+ }
1345
+ } else {
1346
+ writeFileSync2(abs, before);
1347
+ restored++;
1348
+ }
1349
+ }
1350
+ for (const dir of [...madeDirs].reverse()) rmSync(dir, { recursive: true, force: true });
1351
+ throw new CliError(`Could not write ${failingPath} (${code2}). Restored ${restored} file(s) and removed ${removed} new file(s); the folder is as it was.`);
1352
+ }
1353
+ return { written };
1354
+ }
1355
+ function missingDirs(root, dir) {
1356
+ const missing = [];
1357
+ let d = dir;
1358
+ while (relative(root, d) !== "" && !relative(root, d).startsWith("..") && !existsSync6(d)) {
1359
+ missing.unshift(d);
1360
+ d = dirname(d);
1361
+ }
1362
+ return missing;
1363
+ }
1364
+ function withPackageManager(contents, packageManager) {
1365
+ const pkg = JSON.parse(contents);
1366
+ return `${JSON.stringify({ ...pkg, packageManager }, null, 2)}
1367
+ `;
1368
+ }
1369
+
1370
+ // src/add/kit-manifest.ts
1371
+ var malformed = () => new CliError("Unexpected response from the API \u2014 not a kit manifest.");
1372
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1373
+ var isStrings = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
1374
+ var isStringMap = (v) => isRecord(v) && Object.values(v).every((s) => typeof s === "string");
1375
+ function validateKitManifest(json) {
1376
+ if (!isRecord(json)) throw malformed();
1377
+ if (typeof json.version !== "number") throw malformed();
1378
+ if (json.version !== 1) throw new CliError(UPDATE_MESSAGE);
1379
+ if (json.kind !== "kit" || typeof json.name !== "string" || typeof json.utils !== "string") throw malformed();
1380
+ const { theme } = json;
1381
+ if (!isRecord(theme) || typeof theme.css !== "string" || !isStrings(theme.fontImports)) throw malformed();
1382
+ if (!Array.isArray(json.components)) throw malformed();
1383
+ for (const c of json.components) {
1384
+ if (!isRecord(c)) throw malformed();
1385
+ if (typeof c.name !== "string" || typeof c.file !== "string" || typeof c.contents !== "string") throw malformed();
1386
+ if (!isStrings(c.kitImports) || !isStrings(c.packages)) throw malformed();
1387
+ }
1388
+ if (!isStrings(json.utilsPackages)) throw malformed();
1389
+ if (!isStringMap(json.packages) || !isStringMap(json.devPackages)) throw malformed();
1390
+ return {
1391
+ version: 1,
1392
+ kind: "kit",
1393
+ name: json.name,
1394
+ theme: { css: theme.css, fontImports: theme.fontImports },
1395
+ components: json.components,
1396
+ utils: json.utils,
1397
+ utilsPackages: json.utilsPackages,
1398
+ packages: json.packages,
1399
+ devPackages: json.devPackages
1400
+ };
1401
+ }
1402
+
1403
+ // src/add/fetch-kit.ts
1404
+ async function fetchKit(opts, fetchImpl = fetch) {
1405
+ const url = new URL("/api/kit", `${opts.api}/`);
184
1406
  let res;
185
1407
  try {
186
1408
  res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" } });
@@ -189,19 +1411,558 @@ async function fetchManifest(opts, fetchImpl = fetch) {
189
1411
  }
190
1412
  const body = await res.json().catch(() => null);
191
1413
  if (!res.ok) throw new CliError(messageForResponse(res.status, body, opts.api));
192
- return validateManifest(body);
1414
+ return validateKitManifest(body);
193
1415
  }
194
1416
 
195
- // src/package-name.ts
196
- function packageNameFor(folder) {
197
- const trimmed = folder.replace(/[\\/]+$/, "");
198
- const segments = trimmed.split(/[\\/]/).filter((p) => p !== "" && p !== ".");
199
- const last = segments[segments.length - 1];
200
- if (!last) return void 0;
201
- const slug = last.normalize("NFKD").replace(new RegExp("\\p{M}", "gu"), "").toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[-._]+/, "").replace(/[-._]+$/, "").slice(0, 214).replace(/[-._]+$/, "");
202
- return slug || void 0;
1417
+ // src/add/plan-packages.ts
1418
+ function componentClosure(picked, manifest) {
1419
+ const byName = new Map(manifest.components.map((c) => [c.name, c]));
1420
+ const seen = /* @__PURE__ */ new Set();
1421
+ const queue = [...picked];
1422
+ for (let name = queue.shift(); name !== void 0; name = queue.shift()) {
1423
+ if (seen.has(name)) continue;
1424
+ seen.add(name);
1425
+ queue.push(...byName.get(name)?.kitImports ?? []);
1426
+ }
1427
+ return [...seen];
1428
+ }
1429
+ function conflictBetween(pkg, have, need) {
1430
+ const haveMajor = majorOf(have);
1431
+ const needMajor = majorOf(need);
1432
+ if (haveMajor === null || needMajor === null || !Number.isFinite(haveMajor) || !Number.isFinite(needMajor) || haveMajor === needMajor) return null;
1433
+ return { pkg, have, need };
1434
+ }
1435
+ var reasonFor = (c) => `this app uses ${c.pkg} ${majorOf(c.have)}, the kit needs ${majorOf(c.need)}`;
1436
+ function planPackages(components, manifest, appDeps) {
1437
+ const byName = new Map(manifest.components.map((c) => [c.name, c]));
1438
+ const conflictOf = /* @__PURE__ */ new Map();
1439
+ for (const name of componentClosure(components, manifest)) {
1440
+ for (const pkg of byName.get(name)?.packages ?? []) {
1441
+ const have = appDeps[pkg];
1442
+ const need = manifest.packages[pkg];
1443
+ if (have === void 0 || need === void 0 || conflictOf.has(pkg)) continue;
1444
+ const conflict = conflictBetween(pkg, have, need);
1445
+ if (conflict) conflictOf.set(pkg, conflict);
1446
+ }
1447
+ }
1448
+ const skipped = [];
1449
+ const kept = [];
1450
+ for (const name of components) {
1451
+ const blocking = componentClosure([name], manifest).flatMap((n) => byName.get(n)?.packages ?? []).map((pkg) => conflictOf.get(pkg)).find((c) => c !== void 0);
1452
+ if (blocking) skipped.push({ name, reason: reasonFor(blocking) });
1453
+ else kept.push(name);
1454
+ }
1455
+ const needed = new Set(componentClosure(kept, manifest).flatMap((n) => byName.get(n)?.packages ?? []));
1456
+ const install = {};
1457
+ for (const pkg of needed) {
1458
+ const need = manifest.packages[pkg];
1459
+ if (need !== void 0 && appDeps[pkg] === void 0) install[pkg] = need;
1460
+ }
1461
+ for (const pkg of manifest.utilsPackages) {
1462
+ const need = manifest.packages[pkg];
1463
+ if (need !== void 0 && appDeps[pkg] === void 0) install[pkg] = need;
1464
+ }
1465
+ const reactIs = manifest.packages["react-is"];
1466
+ if ("recharts" in install && reactIs !== void 0 && appDeps["react-is"] === void 0) install["react-is"] = reactIs;
1467
+ return { install, conflicts: [...conflictOf.values()], skipped, components: kept };
1468
+ }
1469
+
1470
+ // src/add/css-blocks.ts
1471
+ var isSpace = (c) => c === " " || c === " " || c === "\n" || c === "\r" || c === "\f";
1472
+ function commentEnd(css, at) {
1473
+ const close = css.indexOf("*/", at + 2);
1474
+ return close === -1 ? css.length : close + 2;
1475
+ }
1476
+ function stringEnd(css, at) {
1477
+ const quote = css[at];
1478
+ let i = at + 1;
1479
+ while (i < css.length) {
1480
+ const c = css[i];
1481
+ if (c === "\\") i += 2;
1482
+ else if (c === quote) return i + 1;
1483
+ else i++;
1484
+ }
1485
+ return css.length;
1486
+ }
1487
+ function skipBlank(css, from) {
1488
+ let i = from;
1489
+ while (i < css.length) {
1490
+ if (isSpace(css[i])) i++;
1491
+ else if (css[i] === "/" && css[i + 1] === "*") i = commentEnd(css, i);
1492
+ else break;
1493
+ }
1494
+ return i;
1495
+ }
1496
+ function scanStatements(css) {
1497
+ const out = [];
1498
+ const n = css.length;
1499
+ let i = 0;
1500
+ while (true) {
1501
+ i = skipBlank(css, i);
1502
+ if (i >= n) break;
1503
+ if (css[i] === "}") {
1504
+ i++;
1505
+ continue;
1506
+ }
1507
+ const start = i;
1508
+ let open = -1;
1509
+ let depth = 0;
1510
+ let paren = 0;
1511
+ let end = -1;
1512
+ let j = i;
1513
+ while (j < n) {
1514
+ const c = css[j];
1515
+ if (c === "/" && css[j + 1] === "*") j = commentEnd(css, j);
1516
+ else if (c === '"' || c === "'") j = stringEnd(css, j);
1517
+ else if (c === "\\") j += 2;
1518
+ else {
1519
+ if (c === "(") paren++;
1520
+ else if (c === ")") paren = Math.max(0, paren - 1);
1521
+ else if (c === ";" && depth === 0 && paren === 0) {
1522
+ end = j + 1;
1523
+ break;
1524
+ } else if (c === "{") {
1525
+ if (depth === 0) open = j;
1526
+ depth++;
1527
+ } else if (c === "}") {
1528
+ if (depth === 0) {
1529
+ end = j;
1530
+ break;
1531
+ }
1532
+ depth--;
1533
+ if (depth === 0) {
1534
+ end = j + 1;
1535
+ break;
1536
+ }
1537
+ }
1538
+ j++;
1539
+ }
1540
+ }
1541
+ const closed2 = end !== -1 || open === -1;
1542
+ if (end === -1) end = n;
1543
+ const raw = css.slice(start, end);
1544
+ const text = (raw.endsWith(";") ? raw.slice(0, -1) : raw).trimEnd();
1545
+ const preludeSource = open === -1 ? text : css.slice(start, open);
1546
+ out.push({
1547
+ start,
1548
+ end,
1549
+ text,
1550
+ prelude: preludeSource.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/\s+/g, " ").trim(),
1551
+ body: open !== -1 && closed2 ? css.slice(open + 1, end - 1) : null,
1552
+ closed: closed2
1553
+ });
1554
+ i = end;
1555
+ }
1556
+ return out;
1557
+ }
1558
+
1559
+ // src/add/stylesheet.ts
1560
+ var THEME_START = "/* designsource:theme:start \u2014 generated, edit tokens in the workbench */";
1561
+ var THEME_END = "/* designsource:theme:end */";
1562
+ var FONTS_START = "/* designsource:fonts:start */";
1563
+ var FONTS_END = "/* designsource:fonts:end */";
1564
+ var APP_THEME_KEPT = "/* designsource:app-theme \u2014 this app's own :root, .dark and @theme blocks are left as they were */";
1565
+ var KEPT_COMMENT = "/* designsource:kept \u2014 variables from the previous theme that this design system does not define */";
1566
+ var KIT_SCOPED_RESET = `@layer base {
1567
+ :where([data-slot], [data-slot]::before, [data-slot]::after) { box-sizing: border-box; border: 0 solid; }
1568
+ :where(button, input, select, textarea)[data-slot] { font: inherit; color: inherit; background-color: transparent; }
1569
+ }`;
1570
+ var STAGE_CONTAINER = `html {
1571
+ container: stage / inline-size;
1572
+ }`;
1573
+ var BASE_BLOCK = `@layer base {
1574
+ * {
1575
+ border-color: var(--border);
1576
+ }
1577
+ body {
1578
+ background-color: var(--background);
1579
+ color: var(--foreground);
1580
+ font-family: var(--font-sans);
1581
+ }
1582
+ }`;
1583
+ var ANIMATE_IMPORT = '@import "tw-animate-css";';
1584
+ var SHADCN_IMPORT = '@import "shadcn/tailwind.css";';
1585
+ var DARK_VARIANT = "@custom-variant dark (&:is(.dark *));";
1586
+ var LAYER_ORDER = "@layer theme, base, components, utilities;";
1587
+ var LAYERED_IMPORTS = [
1588
+ '@import "tailwindcss/theme.css" layer(theme);',
1589
+ '@import "tailwindcss/utilities.css" layer(utilities);'
1590
+ ];
1591
+ var SHADCN_APPLY = /^(border-border|outline-ring(\/\d+)?|bg-background|text-foreground)$/;
1592
+ function findRegion(css, start, end) {
1593
+ const s = css.indexOf(start);
1594
+ if (s === -1) return null;
1595
+ const e = css.indexOf(end, s + start.length);
1596
+ return e === -1 ? null : { start: s, end: e + end.length };
1597
+ }
1598
+ var within = (s, r) => r !== null && s.start >= r.start && s.end <= r.end;
1599
+ function declarationsOf(body) {
1600
+ const out = [];
1601
+ for (const s of scanStatements(body)) {
1602
+ if (s.body !== null || !s.closed) return null;
1603
+ const colon = s.text.indexOf(":");
1604
+ out.push({
1605
+ name: colon === -1 ? "" : s.text.slice(0, colon).trim(),
1606
+ value: colon === -1 ? "" : s.text.slice(colon + 1).trim(),
1607
+ text: s.text
1608
+ });
1609
+ }
1610
+ return out;
1611
+ }
1612
+ function isShadcnBaseRule(rule) {
1613
+ if (rule.body === null) return false;
1614
+ const selectors = rule.prelude.split(",").map((p) => p.trim());
1615
+ if (!selectors.every((p) => p === "*" || p === "body" || p === "html")) return false;
1616
+ const inner = scanStatements(rule.body);
1617
+ if (inner.length === 0) return false;
1618
+ return inner.every((s) => {
1619
+ if (s.body !== null || !s.closed) return false;
1620
+ if (!s.text.startsWith("@apply")) return false;
1621
+ const classes = s.text.slice("@apply".length).trim().split(/\s+/);
1622
+ return classes.every((c) => SHADCN_APPLY.test(c));
1623
+ });
1624
+ }
1625
+ function classify(s) {
1626
+ if (s.body === null) return null;
1627
+ if (s.prelude === ":root" || s.prelude === ".dark") {
1628
+ return declarationsOf(s.body) === null ? null : s.prelude === ":root" ? "root" : "dark";
1629
+ }
1630
+ if (s.prelude === "@theme inline") return declarationsOf(s.body) === null ? null : "theme";
1631
+ if (s.prelude === "@layer base") {
1632
+ const rules = scanStatements(s.body);
1633
+ return rules.length > 0 && rules.every(isShadcnBaseRule) ? "base" : null;
1634
+ }
1635
+ return null;
1636
+ }
1637
+ function definedBy(themeCss) {
1638
+ const defs = { root: /* @__PURE__ */ new Set(), dark: /* @__PURE__ */ new Set(), theme: /* @__PURE__ */ new Set() };
1639
+ for (const s of scanStatements(themeCss)) {
1640
+ const kind = classify(s);
1641
+ if (kind === null || kind === "base") continue;
1642
+ for (const d of declarationsOf(s.body ?? "") ?? []) defs[kind].add(d.name);
1643
+ }
1644
+ return defs;
1645
+ }
1646
+ function keptBlockOf(css, statements) {
1647
+ const at = css.indexOf(KEPT_COMMENT);
1648
+ if (at === -1) return null;
1649
+ const kept = [];
1650
+ let prev = at + KEPT_COMMENT.length;
1651
+ let rank = -1;
1652
+ for (const s of statements) {
1653
+ if (s.start < prev) continue;
1654
+ const order = [":root", ".dark", "@theme inline"].indexOf(s.prelude);
1655
+ if (order <= rank || s.body === null || declarationsOf(s.body) === null || css.slice(prev, s.start).trim() !== "") break;
1656
+ kept.push(s);
1657
+ rank = order;
1658
+ prev = s.end;
1659
+ }
1660
+ return { statements: kept, start: at, end: prev };
1661
+ }
1662
+ var importTarget = (prelude) => /^@import\s+(?:url\(\s*)?["']?([^"')\s]+)/.exec(prelude)?.[1] ?? null;
1663
+ var isImport = (s) => s.prelude.startsWith("@import");
1664
+ var importsOf = (live, target) => live.find((s) => isImport(s) && importTarget(s.prelude) === target) ?? null;
1665
+ function render2(parts, idx, rest) {
1666
+ parts.sort((a, b) => a.seq - b.seq);
1667
+ let out = "";
1668
+ parts.forEach((p, i) => {
1669
+ out += (i === 0 ? "" : p.kind === "line" && parts[i - 1].kind === "line" ? "\n" : "\n\n") + p.text;
1670
+ });
1671
+ if (idx === 0) return `${out}${parts[parts.length - 1].kind === "chunk" && rest.trim() !== "" ? "\n\n" : "\n"}`;
1672
+ return `${parts[0].kind === "line" ? "\n" : "\n\n"}${out}`;
1673
+ }
1674
+ var isThemeRoot = (prelude) => prelude.split(",").some((p) => p.trim() === ":root" || p.trim() === ".dark");
1675
+ function collisionsAfterRegion(css, wanted) {
1676
+ const region = findRegion(css, THEME_START, THEME_END);
1677
+ if (!region) return [];
1678
+ const all = scanStatements(css);
1679
+ const kept = keptBlockOf(css, all);
1680
+ const found = /* @__PURE__ */ new Set();
1681
+ const visit = (statements) => {
1682
+ for (const s of statements) {
1683
+ if (s.body === null) continue;
1684
+ if (isThemeRoot(s.prelude)) {
1685
+ for (const d of scanStatements(s.body)) {
1686
+ const name = d.body === null ? d.text.slice(0, Math.max(0, d.text.indexOf(":"))).trim() : "";
1687
+ if (name.startsWith("--") && wanted.has(name)) found.add(name);
1688
+ }
1689
+ } else if (s.prelude.startsWith("@") && !/^@(layer|theme|keyframes|font-face|property)\b/.test(s.prelude)) visit(scanStatements(s.body));
1690
+ }
1691
+ };
1692
+ visit(all.filter((s) => s.start >= region.end && !kept?.statements.includes(s)));
1693
+ return [...found].sort();
1694
+ }
1695
+ var hasThemeRegion = (css) => findRegion(css, THEME_START, THEME_END) !== null;
1696
+ var THEME_RADIUS_RUNGS = /^--radius-(sm|md|lg|xl)$/;
1697
+ function applyTheme(css, theme, opts) {
1698
+ const all = scanStatements(css);
1699
+ const fontsRegion = findRegion(css, FONTS_START, FONTS_END);
1700
+ const themeRegion = findRegion(css, THEME_START, THEME_END);
1701
+ const keptBlock = keptBlockOf(css, all);
1702
+ const removeScaffolding = opts.removeScaffolding && !(themeRegion !== null && css.slice(themeRegion.start, themeRegion.end).includes(APP_THEME_KEPT));
1703
+ const live = all.filter((s) => !within(s, fontsRegion) && !within(s, themeRegion) && !keptBlock?.statements.includes(s));
1704
+ const edits = [];
1705
+ const inserts = [];
1706
+ const fontsText = theme.fontImports.length > 0 ? [FONTS_START, ...theme.fontImports, FONTS_END].join("\n") : null;
1707
+ if (fontsRegion && fontsText) edits.push({ ...fontsRegion, text: fontsText });
1708
+ else if (fontsRegion) {
1709
+ const nl = css.startsWith("\r\n", fontsRegion.end) ? 2 : css[fontsRegion.end] === "\n" ? 1 : 0;
1710
+ edits.push({ start: fontsRegion.start, end: fontsRegion.end + nl, text: "" });
1711
+ } else if (fontsText) inserts.push({ idx: 0, seq: 0, kind: "line", text: fontsText });
1712
+ const headIdx = fontsRegion ? fontsText ? fontsRegion.end : fontsRegion.start : 0;
1713
+ const tailwinds = live.filter((s) => {
1714
+ const target = isImport(s) ? importTarget(s.prelude) : null;
1715
+ return target === "tailwindcss" || (target?.startsWith("tailwindcss/") ?? false);
1716
+ });
1717
+ const tailwind = tailwinds.length > 0 ? tailwinds.reduce((a, b) => b.end > a.end ? b : a) : null;
1718
+ const fullTailwind = tailwinds.some((s) => importTarget(s.prelude) === "tailwindcss");
1719
+ const animate = importsOf(live, "tw-animate-css");
1720
+ const shadcnCss = importsOf(live, "shadcn/tailwind.css");
1721
+ const head = [];
1722
+ if (!tailwind) {
1723
+ if (opts.preflight) head.push('@import "tailwindcss";');
1724
+ else {
1725
+ if (!live.some((s) => s.body === null && /^@layer theme ?, ?base ?, ?components ?, ?utilities$/.test(s.prelude))) head.push(LAYER_ORDER);
1726
+ head.push(...LAYERED_IMPORTS);
1727
+ }
1728
+ }
1729
+ if (tailwind) {
1730
+ if (!animate) inserts.push({ idx: tailwind.end, seq: 1, kind: "line", text: ANIMATE_IMPORT });
1731
+ if (!shadcnCss) inserts.push({ idx: (animate ?? tailwind).end, seq: 2, kind: "line", text: SHADCN_IMPORT });
1732
+ } else {
1733
+ if (!animate) head.push(ANIMATE_IMPORT);
1734
+ if (!shadcnCss) head.push(SHADCN_IMPORT);
1735
+ }
1736
+ head.forEach((text, i) => inserts.push({ idx: headIdx, seq: 1 + i / 100, kind: "line", text }));
1737
+ const anchors = live.filter((s) => isImport(s) || s.prelude.startsWith("@custom-variant") || s.prelude.startsWith("@plugin"));
1738
+ const anchorIdx = anchors.length > 0 ? Math.max(...anchors.map((s) => s.end)) : headIdx;
1739
+ if (!live.some((s) => /^@custom-variant dark\b/.test(s.prelude))) inserts.push({ idx: anchorIdx, seq: 3, kind: "line", text: DARK_VARIANT });
1740
+ const removed = live.flatMap((s) => {
1741
+ const kind = removeScaffolding ? classify(s) : null;
1742
+ return kind ? [{ s, kind }] : [];
1743
+ });
1744
+ const defs = definedBy(theme.css);
1745
+ const SELECTORS = { root: ":root", dark: ".dark", theme: "@theme inline" };
1746
+ const kinds = ["root", "dark", "theme"];
1747
+ const keptLines = { root: /* @__PURE__ */ new Map(), dark: /* @__PURE__ */ new Map(), theme: /* @__PURE__ */ new Map() };
1748
+ const addKept = (kind, d) => {
1749
+ if (defs[kind].has(d.name) || kind === "theme" && THEME_RADIUS_RUNGS.test(d.name)) return;
1750
+ keptLines[kind].set(d.name || d.text, d.name ? ` ${d.name}: ${d.value};` : ` ${d.text};`);
1751
+ };
1752
+ for (const s of keptBlock?.statements ?? []) {
1753
+ const kind = kinds.find((k) => SELECTORS[k] === s.prelude);
1754
+ if (kind) for (const d of declarationsOf(s.body ?? "") ?? []) addKept(kind, d);
1755
+ }
1756
+ for (const { s, kind } of removed) {
1757
+ if (kind === "base") continue;
1758
+ for (const d of declarationsOf(s.body ?? "") ?? []) addKept(kind, d);
1759
+ }
1760
+ const keptBlocksText = kinds.filter((k) => keptLines[k].size > 0).map((k) => `${SELECTORS[k]} {
1761
+ ${[...keptLines[k].values()].join("\n")}
1762
+ }`);
1763
+ const keptText = keptBlocksText.length > 0 ? `${KEPT_COMMENT}
1764
+ ${keptBlocksText.join("\n")}` : null;
1765
+ const useReset = !opts.preflight && !fullTailwind;
1766
+ const region = [THEME_START, ...removeScaffolding ? [] : [APP_THEME_KEPT], theme.css.trimEnd(), "", STAGE_CONTAINER, "", useReset ? KIT_SCOPED_RESET : BASE_BLOCK, THEME_END].join("\n");
1767
+ const keptAfter = keptText !== null && keptBlock === null;
1768
+ const chunk = keptAfter ? `${region}
1769
+
1770
+ ${keptText}` : region;
1771
+ if (keptBlock) {
1772
+ if (keptText !== null) edits.push({ start: keptBlock.start, end: keptBlock.end, text: keptText });
1773
+ else {
1774
+ let end = keptBlock.end;
1775
+ while (end < css.length && /\s/.test(css[end])) end++;
1776
+ edits.push({ start: keptBlock.start, end, text: "" });
1777
+ }
1778
+ }
1779
+ if (themeRegion) {
1780
+ edits.push({ ...themeRegion, text: chunk });
1781
+ } else if (removed.length === 0) {
1782
+ inserts.push({ idx: anchorIdx, seq: 4, kind: "chunk", text: chunk });
1783
+ }
1784
+ removed.forEach(({ s }, i) => {
1785
+ if (i === 0 && !themeRegion) {
1786
+ edits.push({ start: s.start, end: s.end, text: chunk });
1787
+ return;
1788
+ }
1789
+ let end = s.end;
1790
+ while (end < css.length && /\s/.test(css[end])) end++;
1791
+ edits.push({ start: s.start, end, text: "" });
1792
+ });
1793
+ const groups = /* @__PURE__ */ new Map();
1794
+ for (const p of inserts) groups.set(p.idx, [...groups.get(p.idx) ?? [], p]);
1795
+ for (const [idx, parts] of groups) edits.push({ start: idx, end: idx, text: render2(parts, idx, css.slice(idx)) });
1796
+ let result = css;
1797
+ for (const e of edits.sort((a, b) => b.start - a.start || b.end - a.end)) {
1798
+ result = result.slice(0, e.start) + e.text + result.slice(e.end);
1799
+ }
1800
+ const wanted = /* @__PURE__ */ new Set([...defs.root, ...defs.dark]);
1801
+ return { css: result, replacedShadcnTheme: removed.length > 0, collisions: collisionsAfterRegion(result, wanted) };
1802
+ }
1803
+
1804
+ // src/add/run-add.ts
1805
+ var NO_SHADCN = "This app doesn't use shadcn yet. Setting it up: adds Tailwind and the shadcn config.";
1806
+ var REPLACE_DECLINED = "Nothing was changed. Run again and answer yes to replace them, or remove those files first.";
1807
+ var REPLACE_NEEDS_FORCE = (paths) => `These files exist and were not added by designsource: ${paths.join(", ")}. Pass --force to replace them.`;
1808
+ var UNKNOWN_COMPONENTS = (names) => `Unknown component(s): ${names.join(", ")}. Run without names to pick from the list.`;
1809
+ var NO_THEME_FILE = (file) => `${file} does not exist. components.json names it as the app's stylesheet (tailwind.css); create it or fix the path, then run this again.`;
1810
+ var INSTALL_FAILED = (command) => `Installing libraries failed. The files were written; run this to finish: ${command}`;
1811
+ var UnknownComponentsError = class extends CliError {
1812
+ constructor(names) {
1813
+ super(UNKNOWN_COMPONENTS(names));
1814
+ this.names = names;
1815
+ }
1816
+ names;
1817
+ };
1818
+ var PORTAL = "preview-portal";
1819
+ var ALIASES = { components: "@/components", utils: "@/lib/utils", ui: "@/components/ui" };
1820
+ var InstallError = class extends StepError {
1821
+ constructor(message, outputTail2, installCommand) {
1822
+ super(message, outputTail2);
1823
+ this.installCommand = installCommand;
1824
+ }
1825
+ installCommand;
1826
+ };
1827
+ function nonInteractiveQuestions(args) {
1828
+ return {
1829
+ pickComponents: async (all) => all,
1830
+ confirmReplace: async (paths) => {
1831
+ if (!args.force) throw new CliError(REPLACE_NEEDS_FORCE(paths));
1832
+ return true;
1833
+ },
1834
+ keepEdits: async () => !args.force
1835
+ };
1836
+ }
1837
+ function defaultTargets(root, info) {
1838
+ const cssFile = findGlobalStylesheet(info);
1839
+ if (readPaths(root)?.paths["@/*"]) return resolveTargets(root, { tailwind: { css: cssFile }, aliases: ALIASES });
1840
+ const src = join4(root, "src");
1841
+ const prefix = existsSync7(src) && statSync2(src).isDirectory() ? "src/" : "";
1842
+ return { uiDir: `${prefix}components/ui`, utilsFile: `${prefix}lib/utils.ts`, cssFile, uiAlias: ALIASES.ui, utilsAlias: ALIASES.utils };
1843
+ }
1844
+ function assertSameTargets(planned, actual) {
1845
+ for (const key of Object.keys(planned)) {
1846
+ if (planned[key] === actual[key]) continue;
1847
+ throw new CliError(`After setup, components.json resolves ${key} to "${actual[key]}" instead of "${planned[key]}". The kit was not written; run this again to add it there.`);
1848
+ }
1849
+ }
1850
+ async function chooseComponents(input, manifest, before, questions) {
1851
+ const known = new Set(manifest.components.map((c) => c.name));
1852
+ const offered = manifest.components.map((c) => c.name).filter((n) => n !== PORTAL);
1853
+ const checked = (names) => {
1854
+ const unknown = names.filter((n) => !known.has(n));
1855
+ if (unknown.length > 0) throw new UnknownComponentsError(unknown);
1856
+ return [...new Set(names)];
1857
+ };
1858
+ if (input.components.length > 0) return checked(input.components);
1859
+ if (input.all) return offered;
1860
+ const earlier = before.filter((n) => known.has(n));
1861
+ if (earlier.length > 0) return earlier;
1862
+ return checked(await questions.pickComponents(offered));
1863
+ }
1864
+ function installCommands(info, manifest, install) {
1865
+ const lacks = (pkg) => info.deps[pkg] === void 0;
1866
+ const runtime = { ...install };
1867
+ const animate = manifest.devPackages["tw-animate-css"];
1868
+ if (animate && lacks("tw-animate-css")) runtime["tw-animate-css"] = animate;
1869
+ const dev = {};
1870
+ const shadcn = manifest.devPackages.shadcn;
1871
+ if (shadcn && lacks("shadcn")) dev.shadcn = shadcn;
1872
+ const commands = [];
1873
+ if (Object.keys(runtime).length > 0) commands.push(installArgs(info.packageManager, runtime, false));
1874
+ if (Object.keys(dev).length > 0) commands.push(installArgs(info.packageManager, dev, true));
1875
+ return commands;
1876
+ }
1877
+ function printedCommand([cmd, args]) {
1878
+ return [cmd, ...args.map((a) => a.includes("@") ? `"${a}"` : a)].join(" ");
1879
+ }
1880
+ async function runAdd(input, deps) {
1881
+ const { root } = input;
1882
+ const info = detectApp(root);
1883
+ assertCanAdd(info);
1884
+ const planned = info.shadcn ? resolveTargets(root, info.shadcn) : defaultTargets(root, info);
1885
+ const cssAbs = resolveInside(root, planned.cssFile);
1886
+ if (!existsSync7(cssAbs)) throw new CliError(NO_THEME_FILE(planned.cssFile));
1887
+ assertKitUtils(root, info, planned);
1888
+ const manifest = await fetchKit({ api: input.api, token: input.token }, deps.fetchImpl);
1889
+ const chosen = await chooseComponents(input, manifest, previouslyAdded(root, planned), deps.questions);
1890
+ const packages = planPackages(chosen, manifest, info.deps);
1891
+ const plan = planFiles(root, planned, componentClosure(packages.components, manifest), manifest);
1892
+ const setup = planSetup(info, manifest, deps.exec);
1893
+ if (plan.replaceForeign.length > 0 && !await deps.questions.confirmReplace(plan.replaceForeign)) throw new CliError(REPLACE_DECLINED);
1894
+ const kept = [];
1895
+ for (const path of plan.edited) if (await deps.questions.keepEdits(path)) kept.push(path);
1896
+ const writes = plan.write.filter((w) => !kept.includes(w.path));
1897
+ if (!info.shadcn) deps.progress(NO_SHADCN);
1898
+ for (const step of setup.steps) {
1899
+ await step.run();
1900
+ deps.progress(`${step.line} \u2713`);
1901
+ }
1902
+ if (!info.shadcn) {
1903
+ const written = detectApp(root).shadcn;
1904
+ if (!written) throw new CliError("Setup did not leave a components.json. Run this again.");
1905
+ assertSameTargets(planned, resolveTargets(root, written));
1906
+ }
1907
+ const sheet = readFileSync7(cssAbs, "utf8");
1908
+ const removeScaffolding = info.shadcn !== null || hasThemeRegion(sheet);
1909
+ const themed = applyTheme(sheet, manifest.theme, { preflight: setup.preflight, removeScaffolding });
1910
+ try {
1911
+ writeFiles(root, [{ path: planned.cssFile, contents: themed.css }, ...writes.map(({ path, contents }) => ({ path, contents }))], { force: true, created: false });
1912
+ } catch (e) {
1913
+ if (!(e instanceof CliError) || setup.steps.length === 0) throw e;
1914
+ throw new CliError(`${e.message} Setup changes (${setup.steps.map((s) => s.line).join(", ")}) were kept; run this again to finish.`, e.exitCode);
1915
+ }
1916
+ deps.progress("Adding theme\u2026 \u2713");
1917
+ const added = writes.filter((w) => w.component !== "utils").map((w) => w.component);
1918
+ const shown = added.filter((n) => n !== PORTAL).length;
1919
+ if (shown > 0) deps.progress(`Adding ${shown} component${shown === 1 ? "" : "s"}\u2026 \u2713`);
1920
+ const commands = installCommands(info, manifest, packages.install);
1921
+ const installCommand = commands.map(printedCommand).join(" && ") || null;
1922
+ if (installCommand && input.skipInstall) deps.progress(`Skipped installing libraries. Run: ${installCommand}`);
1923
+ else if (installCommand) {
1924
+ for (const [cmd, args] of commands) {
1925
+ const { code: code2, output } = await deps.exec(cmd, args, { cwd: root });
1926
+ if (code2 !== 0) throw new InstallError(INSTALL_FAILED(installCommand), outputTail(output), installCommand);
1927
+ }
1928
+ deps.progress("Installing libraries\u2026 \u2713");
1929
+ }
1930
+ return {
1931
+ setup: setup.steps.map((s) => s.line),
1932
+ added,
1933
+ skipped: packages.skipped,
1934
+ kept,
1935
+ gone: plan.gone,
1936
+ themeFile: planned.cssFile,
1937
+ installCommand: input.skipInstall ? installCommand : null,
1938
+ projectName: manifest.name,
1939
+ replacedTheme: themed.replacedShadcnTheme,
1940
+ collisions: themed.collisions,
1941
+ uiAlias: planned.uiAlias
1942
+ };
203
1943
  }
204
1944
 
1945
+ // src/add/summary.ts
1946
+ function summaryLines(r) {
1947
+ return [
1948
+ ...r.replacedTheme ? [`Replaced the theme in ${r.themeFile}`] : [],
1949
+ ...r.collisions.length > 0 ? [`${r.themeFile} also sets ${r.collisions.join(", ")} in its own :root; those values win over the theme. Rename them there to let the theme apply.`] : [],
1950
+ ...r.skipped.map((s) => `Skipped ${s.name}: ${s.reason}`),
1951
+ ...r.kept.map((path) => `Kept your edits to ${path}`),
1952
+ ...r.gone.map((path) => `${path} is no longer in the kit; left it in place`),
1953
+ `Done. Your components now use "${r.projectName}" from designsource.app.`,
1954
+ "Run it again any time to pull updates."
1955
+ ];
1956
+ }
1957
+
1958
+ // src/connect/api-for.ts
1959
+ function apiFor(args, entry) {
1960
+ return args.apiGiven ? args.api : entry?.api ?? args.api;
1961
+ }
1962
+
1963
+ // src/picker.ts
1964
+ import { emitKeypressEvents } from "node:readline";
1965
+
205
1966
  // src/prompts.ts
206
1967
  import { createInterface } from "node:readline";
207
1968
  var shared;
@@ -241,10 +2002,10 @@ function nextLine() {
241
2002
  if (line !== void 0) return Promise.resolve(line);
242
2003
  if (closed) return Promise.reject(new CliError(EOF_MESSAGE));
243
2004
  process.stdin.ref?.();
244
- return new Promise((resolve3, reject) => waiting.push({
2005
+ return new Promise((resolve6, reject) => waiting.push({
245
2006
  resolve: (line2) => {
246
2007
  process.stdin.unref?.();
247
- resolve3(line2);
2008
+ resolve6(line2);
248
2009
  },
249
2010
  reject: (err) => {
250
2011
  process.stdin.unref?.();
@@ -261,6 +2022,13 @@ function promptLine(promptText, fallback) {
261
2022
  function ask(question, fallback) {
262
2023
  return promptLine(`${question} (${fallback}) `, fallback);
263
2024
  }
2025
+ async function confirm(question, defaultYes = false) {
2026
+ const answer = await promptLine(`${question} ${defaultYes ? "(Y/n)" : "(y/N)"} `, "");
2027
+ return /^y/i.test(answer) ? true : /^n/i.test(answer) ? false : defaultYes;
2028
+ }
2029
+ function askLine(question) {
2030
+ return promptLine(`${question} `, "");
2031
+ }
264
2032
  async function askChoice(question, options, defaultIndex) {
265
2033
  const list = options.map((o, i) => ` ${i + 1}) ${o}${i === defaultIndex ? " (default)" : ""}`).join("\n");
266
2034
  process.stdout.write(`${question}
@@ -276,27 +2044,396 @@ ${list}
276
2044
  `);
277
2045
  }
278
2046
  }
279
- async function askHidden(question) {
280
- const r = iface();
281
- const original = typeof r._writeToOutput === "function" ? r._writeToOutput.bind(r) : void 0;
282
- if (!original) {
283
- throw new CliError("Cannot hide input on this terminal. Pass --token or set DS_SYNC_TOKEN instead.");
2047
+ async function askHidden(question) {
2048
+ const r = iface();
2049
+ const original = typeof r._writeToOutput === "function" ? r._writeToOutput.bind(r) : void 0;
2050
+ if (!original) {
2051
+ throw new CliError("Cannot hide input on this terminal. Pass --token or set DS_SYNC_TOKEN instead.");
2052
+ }
2053
+ let muted = false;
2054
+ r._writeToOutput = (s) => {
2055
+ if (!muted) original(s);
2056
+ };
2057
+ r.setPrompt(`${question} `);
2058
+ r.prompt();
2059
+ muted = true;
2060
+ try {
2061
+ const a = await nextLine();
2062
+ return a.trim();
2063
+ } finally {
2064
+ muted = false;
2065
+ original("\n");
2066
+ r._writeToOutput = original;
2067
+ }
2068
+ }
2069
+
2070
+ // src/picker.ts
2071
+ function pick(question, options, defaultIndex = 0) {
2072
+ if (!rawTerminal()) return askChoice(question, options.map((o) => o.value), defaultIndex);
2073
+ return pickTty(question, options, defaultIndex, process.stdin, process.stdout);
2074
+ }
2075
+ function rawTerminal() {
2076
+ const { stdin, stdout } = process;
2077
+ return stdin.isTTY === true && stdout.isTTY === true && typeof stdin.setRawMode === "function" && !hasInterface();
2078
+ }
2079
+ function pickMany(question, options, preselected) {
2080
+ if (!rawTerminal()) return pickManyNumbered(question, options, preselected);
2081
+ return pickManyTty(question, options, preselected, process.stdin, process.stdout);
2082
+ }
2083
+ async function pickManyNumbered(question, options, preselected) {
2084
+ const list = options.map((o, i) => ` ${i + 1}) ${o.label}${preselected.includes(o.value) ? " (picked)" : ""}`).join("\n");
2085
+ process.stdout.write(`${question}
2086
+ ${list}
2087
+ `);
2088
+ const defaults = options.flatMap((o, i) => preselected.includes(o.value) ? [String(i + 1)] : []);
2089
+ const fallback = defaults.length > 0 ? defaults.join(",") : "none";
2090
+ for (; ; ) {
2091
+ const answer = await ask("Choices", fallback);
2092
+ if (answer === "none") return [];
2093
+ const indexes = answer.split(/[\s,]+/).filter(Boolean).map((part) => {
2094
+ const byValue = options.findIndex((o) => o.value === part.toLowerCase());
2095
+ if (byValue !== -1) return byValue;
2096
+ const byNumber = /^\d+$/.test(part) ? Number(part) - 1 : -1;
2097
+ return options[byNumber] !== void 0 ? byNumber : -1;
2098
+ });
2099
+ if (indexes.length > 0 && !indexes.includes(-1)) return options.filter((_, i) => indexes.includes(i)).map((o) => o.value);
2100
+ process.stdout.write(`Pick from 1-${options.length}, separated by commas.
2101
+ `);
2102
+ }
2103
+ }
2104
+ function pickTty(question, options, start, stdin, stdout) {
2105
+ const color = !process.env.NO_COLOR;
2106
+ const bold = (s) => color ? `\x1B[1m${s}\x1B[22m` : s;
2107
+ const dim = (s) => color ? `\x1B[2m${s}\x1B[22m` : s;
2108
+ const n = options.length;
2109
+ let index = start;
2110
+ const rows = () => options.map((o, i) => {
2111
+ const label = i === index ? bold(o.label) : o.label;
2112
+ return `${i === index ? "\u276F" : " "} ${label}${o.hint ? ` ${dim(o.hint)}` : ""}`;
2113
+ });
2114
+ const draw = (lines) => stdout.write(lines.map((l) => `\r\x1B[2K${l}`).join("\n") + "\n");
2115
+ const up = () => stdout.write(`\x1B[${n + 1}A`);
2116
+ emitKeypressEvents(stdin);
2117
+ stdin.setRawMode(true);
2118
+ stdin.resume();
2119
+ stdout.write("\x1B[?25l");
2120
+ draw([question, ...rows()]);
2121
+ return new Promise((resolve6, reject) => {
2122
+ const finish = (after) => {
2123
+ stdin.off("keypress", onKey);
2124
+ stdin.setRawMode(false);
2125
+ stdin.pause();
2126
+ after();
2127
+ stdout.write("\x1B[?25h");
2128
+ };
2129
+ const onKey = (str, key = {}) => {
2130
+ if (key.ctrl && key.name === "c" || key.name === "escape") {
2131
+ finish(() => stdout.write("\n"));
2132
+ reject(new CliError(CANCELLED, 130));
2133
+ return;
2134
+ }
2135
+ if (key.name === "return" || key.name === "enter") {
2136
+ const chosen = options[index];
2137
+ finish(() => {
2138
+ up();
2139
+ stdout.write(`\r\x1B[J${question} ${chosen.label}
2140
+ `);
2141
+ });
2142
+ resolve6(chosen.value);
2143
+ return;
2144
+ }
2145
+ if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
2146
+ else if (key.name === "down" || str === "j") index = (index + 1) % n;
2147
+ else if (str && /^[1-9]$/.test(str) && Number(str) <= n) index = Number(str) - 1;
2148
+ else return;
2149
+ up();
2150
+ draw([question, ...rows()]);
2151
+ };
2152
+ stdin.on("keypress", onKey);
2153
+ });
2154
+ }
2155
+ function pickManyTty(question, options, preselected, stdin, stdout) {
2156
+ const color = !process.env.NO_COLOR;
2157
+ const bold = (s) => color ? `\x1B[1m${s}\x1B[22m` : s;
2158
+ const dim = (s) => color ? `\x1B[2m${s}\x1B[22m` : s;
2159
+ const n = options.length;
2160
+ const ticked = options.map((o) => preselected.includes(o.value));
2161
+ let index = 0;
2162
+ const rows = () => options.map((o, i) => {
2163
+ const label = i === index ? bold(o.label) : o.label;
2164
+ return `${i === index ? "\u276F" : " "} ${ticked[i] ? "\u25C9" : "\u25EF"} ${label}${o.hint ? ` ${dim(o.hint)}` : ""}`;
2165
+ });
2166
+ const head = `${question} ${dim("space toggles, a all, enter confirms")}`;
2167
+ const draw = (lines) => stdout.write(lines.map((l) => `\r\x1B[2K${l}`).join("\n") + "\n");
2168
+ const up = () => stdout.write(`\x1B[${n + 1}A`);
2169
+ emitKeypressEvents(stdin);
2170
+ stdin.setRawMode(true);
2171
+ stdin.resume();
2172
+ stdout.write("\x1B[?25l");
2173
+ draw([head, ...rows()]);
2174
+ return new Promise((resolve6, reject) => {
2175
+ const finish = (after) => {
2176
+ stdin.off("keypress", onKey);
2177
+ stdin.setRawMode(false);
2178
+ stdin.pause();
2179
+ after();
2180
+ stdout.write("\x1B[?25h");
2181
+ };
2182
+ const onKey = (str, key = {}) => {
2183
+ if (key.ctrl && key.name === "c" || key.name === "escape") {
2184
+ finish(() => stdout.write("\n"));
2185
+ reject(new CliError(CANCELLED, 130));
2186
+ return;
2187
+ }
2188
+ if (key.name === "return" || key.name === "enter") {
2189
+ const chosen = options.filter((_, i) => ticked[i]);
2190
+ finish(() => {
2191
+ up();
2192
+ stdout.write(`\r\x1B[J${question} ${chosen.length > 0 ? chosen.map((o) => o.label).join(", ") : "none"}
2193
+ `);
2194
+ });
2195
+ resolve6(chosen.map((o) => o.value));
2196
+ return;
2197
+ }
2198
+ if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
2199
+ else if (key.name === "down" || str === "j") index = (index + 1) % n;
2200
+ else if (key.name === "space" || str === " ") ticked[index] = !ticked[index];
2201
+ else if (str === "a") ticked.fill(!ticked.every(Boolean));
2202
+ else return;
2203
+ up();
2204
+ draw([head, ...rows()]);
2205
+ };
2206
+ stdin.on("keypress", onKey);
2207
+ });
2208
+ }
2209
+
2210
+ // src/connect/resolve-token.ts
2211
+ import { homedir } from "node:os";
2212
+
2213
+ // src/connect/store.ts
2214
+ import { randomBytes } from "node:crypto";
2215
+ import { chmodSync, constants, copyFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync8, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
2216
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join5, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
2217
+ var WHERE = ["keychain", "secret-service", "dpapi", "file"];
2218
+ function credentialsPath(env, platform, home) {
2219
+ if (platform === "win32") return join5(env.APPDATA || join5(home, "AppData", "Roaming"), "designsource", "credentials.json");
2220
+ const config = env.XDG_CONFIG_HOME && isAbsolute2(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join5(home, ".config");
2221
+ return join5(config, "designsource", "credentials.json");
2222
+ }
2223
+ function isFileEntry(value) {
2224
+ if (typeof value !== "object" || value === null) return false;
2225
+ const e = value;
2226
+ return typeof e.name === "string" && Array.isArray(e.folders) && e.folders.every((f) => typeof f === "string") && WHERE.includes(e.where) && (e.secret === void 0 || typeof e.secret === "string") && (e.api === void 0 || typeof e.api === "string");
2227
+ }
2228
+ function readCredentials(path) {
2229
+ let text;
2230
+ try {
2231
+ text = readFileSync8(path, "utf8");
2232
+ } catch {
2233
+ return { version: 1, projects: {} };
2234
+ }
2235
+ let parsed;
2236
+ try {
2237
+ parsed = JSON.parse(text);
2238
+ } catch {
2239
+ return { version: 1, projects: {}, unreadable: true };
2240
+ }
2241
+ const raw = parsed;
2242
+ if (typeof raw !== "object" || raw === null || raw.version !== 1 || typeof raw.projects !== "object" || raw.projects === null) return { version: 1, projects: {}, unreadable: true };
2243
+ const projects = {};
2244
+ for (const [id, entry] of Object.entries(raw.projects)) if (isFileEntry(entry)) projects[id] = entry;
2245
+ return { version: 1, projects };
2246
+ }
2247
+ function stamp(d) {
2248
+ const p = (n) => String(n).padStart(2, "0");
2249
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
2250
+ }
2251
+ function backUp(path) {
2252
+ const base = `${path}.bak-${stamp(/* @__PURE__ */ new Date())}`;
2253
+ for (let n = 0; ; n++) {
2254
+ const target = n === 0 ? base : `${base}-${n}`;
2255
+ try {
2256
+ copyFileSync(path, target, constants.COPYFILE_EXCL);
2257
+ } catch (e) {
2258
+ if (e.code === "EEXIST") continue;
2259
+ throw e;
2260
+ }
2261
+ chmodSync(target, 384);
2262
+ return target;
2263
+ }
2264
+ }
2265
+ function detach(data, keep, folder) {
2266
+ let changed = false;
2267
+ for (const [id, entry] of Object.entries(data.projects)) {
2268
+ if (id === keep) continue;
2269
+ const folders = entry.folders.filter((f) => !isWithin(resolve3(f), folder));
2270
+ if (folders.length !== entry.folders.length) {
2271
+ entry.folders = folders;
2272
+ changed = true;
2273
+ }
2274
+ }
2275
+ return changed;
2276
+ }
2277
+ function writeCredentials(path, data) {
2278
+ const dir = dirname2(path);
2279
+ mkdirSync2(dir, { recursive: true, mode: 448 });
2280
+ chmodSync(dir, 448);
2281
+ const temp = join5(dir, `.credentials.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
2282
+ try {
2283
+ writeFileSync3(temp, `${JSON.stringify(data, null, 2)}
2284
+ `, { mode: 384, flag: "wx" });
2285
+ chmodSync(temp, 384);
2286
+ renameSync(temp, path);
2287
+ } catch (e) {
2288
+ rmSync2(temp, { force: true });
2289
+ throw e;
2290
+ }
2291
+ }
2292
+ function publicEntry(projectId, e) {
2293
+ return { projectId, name: e.name, folders: [...e.folders], where: e.where, ...e.api === void 0 ? {} : { api: e.api } };
2294
+ }
2295
+ function isWithin(folder, root) {
2296
+ const rel = relative2(root, folder);
2297
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute2(rel);
2298
+ }
2299
+ function createStore(opts) {
2300
+ const { env, platform, exec, home } = opts;
2301
+ const path = credentialsPath(env, platform, home);
2302
+ const forceFile = env.DESIGNSOURCE_STORE === "file";
2303
+ const osBackend = (where) => where === "file" ? null : backendFor(where, exec, home);
2304
+ return {
2305
+ async save({ projectId, name, folder, token, api }) {
2306
+ assertProjectId(projectId);
2307
+ const { unreadable, ...data } = readCredentials(path);
2308
+ const previous = data.projects[projectId];
2309
+ const folders = [.../* @__PURE__ */ new Set([...previous?.folders ?? [], resolve3(folder)])];
2310
+ detach(data, projectId, resolve3(folder));
2311
+ const origin = api === void 0 ? {} : { api };
2312
+ let entry = { name, folders, where: "file", secret: token, ...origin };
2313
+ const backend = forceFile ? null : await chooseBackend({ platform, exec, cwd: home, token });
2314
+ if (backend) {
2315
+ const kept = await backend.put(projectId, name, token);
2316
+ if (kept) entry = { name, folders, where: backend.where, ...kept.secret === void 0 ? {} : { secret: kept.secret }, ...origin };
2317
+ }
2318
+ data.projects[projectId] = entry;
2319
+ const backup = unreadable ? backUp(path) : void 0;
2320
+ writeCredentials(path, data);
2321
+ if (previous && previous.where !== entry.where) await osBackend(previous.where)?.remove(projectId);
2322
+ return { ...publicEntry(projectId, entry), ...backup === void 0 ? {} : { backup } };
2323
+ },
2324
+ async token(projectId) {
2325
+ assertProjectId(projectId);
2326
+ const entry = readCredentials(path).projects[projectId];
2327
+ if (!entry) return null;
2328
+ if (entry.where === "file") return entry.secret ?? null;
2329
+ return osBackend(entry.where).get(projectId, entry.secret);
2330
+ },
2331
+ byFolder(folder) {
2332
+ const target = resolve3(folder);
2333
+ return Object.entries(readCredentials(path).projects).filter(([, e]) => e.folders.some((saved) => isWithin(target, resolve3(saved)))).map(([id, e]) => publicEntry(id, e));
2334
+ },
2335
+ entry(projectId) {
2336
+ const found = readCredentials(path).projects;
2337
+ return Object.hasOwn(found, projectId) ? publicEntry(projectId, found[projectId]) : null;
2338
+ },
2339
+ addFolder(projectId, folder, api) {
2340
+ assertProjectId(projectId);
2341
+ const data = readCredentials(path);
2342
+ if (!Object.hasOwn(data.projects, projectId)) return null;
2343
+ const entry = data.projects[projectId];
2344
+ const target = resolve3(folder);
2345
+ const changed = detach(data, projectId, target) || !entry.folders.includes(target) || entry.api !== api;
2346
+ if (!entry.folders.includes(target)) entry.folders = [...entry.folders, target];
2347
+ if (api === void 0) delete entry.api;
2348
+ else entry.api = api;
2349
+ if (changed) writeCredentials(path, data);
2350
+ return publicEntry(projectId, entry);
2351
+ },
2352
+ async forget(projectId) {
2353
+ const data = readCredentials(path);
2354
+ const entry = data.projects[projectId];
2355
+ if (!entry) return null;
2356
+ await osBackend(entry.where)?.remove(projectId);
2357
+ delete data.projects[projectId];
2358
+ writeCredentials(path, data);
2359
+ return publicEntry(projectId, entry);
2360
+ }
2361
+ };
2362
+ }
2363
+
2364
+ // src/connect/resolve-token.ts
2365
+ var NO_TOKEN_FOR_PROJECT = (nameOrId) => `This computer has no token for the "${nameOrId}" design system. Run npx designsource connect in the project folder.`;
2366
+ function defaultStore(env = process.env) {
2367
+ return createStore({ env, platform: process.platform, exec: spawnExec, home: homedir() });
2368
+ }
2369
+ var TERMINAL = { askHidden, pick: (q, options) => pick(q, options, 0) };
2370
+ async function resolveToken(input, prompts = TERMINAL) {
2371
+ const { given, cwd, projectId, store, interactive, prompt } = input;
2372
+ if (given) return { token: given, entry: projectId ? store.entry(projectId) : null };
2373
+ if (projectId) {
2374
+ const token = await store.token(projectId);
2375
+ return token ? { token, entry: store.entry(projectId) } : null;
2376
+ }
2377
+ const matches = store.byFolder(cwd);
2378
+ let chosen = matches[0];
2379
+ if (matches.length > 1) {
2380
+ if (!interactive) {
2381
+ throw new CliError(`More than one design system is connected to this folder: ${matches.map((m) => m.name).join(", ")}. Pass --token, or run in the project folder you mean.`);
2382
+ }
2383
+ const id = await prompts.pick("Which design system?", matches.map((m) => ({ value: m.projectId, label: m.name })));
2384
+ chosen = matches.find((m) => m.projectId === id);
2385
+ }
2386
+ if (chosen) {
2387
+ const token = await store.token(chosen.projectId);
2388
+ if (token) return { token, entry: chosen };
2389
+ }
2390
+ if (!prompt) return null;
2391
+ const typed = await prompts.askHidden("Project token (workbench \u2192 Project settings):");
2392
+ return typed ? { token: typed, entry: null } : null;
2393
+ }
2394
+
2395
+ // src/manifest.ts
2396
+ var malformed2 = () => new CliError("Unexpected response from the API \u2014 not a starter manifest.");
2397
+ function validateManifest(json) {
2398
+ if (typeof json !== "object" || json === null) throw malformed2();
2399
+ const m = json;
2400
+ if (typeof m.version !== "number") throw malformed2();
2401
+ if (m.version !== 1) throw new CliError(UPDATE_MESSAGE);
2402
+ if (typeof m.framework !== "string" || !FRAMEWORKS.includes(m.framework)) throw malformed2();
2403
+ if (typeof m.name !== "string" || !Array.isArray(m.files) || !Array.isArray(m.nextSteps)) throw malformed2();
2404
+ for (const f of m.files) {
2405
+ if (typeof f !== "object" || f === null) throw malformed2();
2406
+ const { path, contents } = f;
2407
+ if (typeof path !== "string" || typeof contents !== "string") throw malformed2();
284
2408
  }
285
- let muted = false;
286
- r._writeToOutput = (s) => {
287
- if (!muted) original(s);
288
- };
289
- r.setPrompt(`${question} `);
290
- r.prompt();
291
- muted = true;
2409
+ if (!m.nextSteps.every((s) => typeof s === "string")) throw malformed2();
2410
+ return { version: 1, framework: m.framework, name: m.name, files: m.files, nextSteps: m.nextSteps };
2411
+ }
2412
+
2413
+ // src/fetch-manifest.ts
2414
+ async function fetchManifest(opts, fetchImpl = fetch) {
2415
+ const url = new URL("/api/starter", `${opts.api}/`);
2416
+ url.searchParams.set("framework", opts.framework);
2417
+ if (opts.name) url.searchParams.set("name", opts.name);
2418
+ let res;
292
2419
  try {
293
- const a = await nextLine();
294
- return a.trim();
295
- } finally {
296
- muted = false;
297
- original("\n");
298
- r._writeToOutput = original;
2420
+ res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" } });
2421
+ } catch {
2422
+ throw new CliError(UNREACHABLE(opts.api));
299
2423
  }
2424
+ const body = await res.json().catch(() => null);
2425
+ if (!res.ok) throw new CliError(messageForResponse(res.status, body, opts.api));
2426
+ return validateManifest(body);
2427
+ }
2428
+
2429
+ // src/package-name.ts
2430
+ function packageNameFor(folder) {
2431
+ const trimmed = folder.replace(/[\\/]+$/, "");
2432
+ const segments = trimmed.split(/[\\/]/).filter((p) => p !== "" && p !== ".");
2433
+ const last = segments[segments.length - 1];
2434
+ if (!last) return void 0;
2435
+ const slug = last.normalize("NFKD").replace(new RegExp("\\p{M}", "gu"), "").toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[-._]+/, "").replace(/[-._]+$/, "").slice(0, 214).replace(/[-._]+$/, "");
2436
+ return slug || void 0;
300
2437
  }
301
2438
 
302
2439
  // src/runner.ts
@@ -321,88 +2458,27 @@ function nextStepsText({ runner, framework, folder, created }) {
321
2458
  `;
322
2459
  }
323
2460
 
324
- // src/write.ts
325
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
326
- import { dirname, resolve as resolve2 } from "node:path";
327
-
328
- // src/paths.ts
329
- import { isAbsolute, resolve, sep } from "node:path";
330
- function resolveInside(root, relPath) {
331
- const escapes = (why) => new CliError(`Manifest path "${relPath}" is outside the target folder (${why}).`);
332
- if (!relPath) throw escapes("empty");
333
- if (isAbsolute(relPath) || /^[a-zA-Z]:[\\/]/.test(relPath) || relPath.startsWith("\\")) throw escapes("absolute");
334
- if (relPath.split(/[\\/]/).includes("..")) throw escapes("..");
335
- const abs = resolve(root, relPath);
336
- if (abs === root || !abs.startsWith(root.endsWith(sep) ? root : root + sep)) throw escapes("resolves above it");
337
- return abs;
338
- }
339
-
340
- // src/write.ts
341
- function planTarget(cwd, folder, framework, force) {
342
- const root = resolve2(cwd, folder);
343
- if (!existsSync(root)) return { root, created: true };
344
- if (!statSync(root).isDirectory()) throw new CliError(`${folder} exists and is not a folder.`);
345
- if (framework === "next") {
346
- if (readdirSync(root).length > 0 && !force) throw new CliError(`Folder ${folder} is not empty. Pick another name, or pass --force to overwrite the files the starter writes.`);
347
- } else if (existsSync(resolve2(root, "design-system")) && !force) {
348
- throw new CliError(`${folder}/design-system/ already exists. Remove it, or pass --force to overwrite the files the bundle writes.`);
349
- }
350
- return { root, created: false };
351
- }
352
- function writeFiles(root, files, opts) {
353
- const targets = files.map((f) => ({ file: f, abs: resolveInside(root, f.path) }));
354
- if (!opts.force) {
355
- const clash = targets.find((t) => existsSync(t.abs));
356
- if (clash) throw new CliError(`${clash.file.path} already exists. Pass --force to overwrite the files the starter writes.`);
357
- }
358
- const written = [];
359
- const previous = /* @__PURE__ */ new Map();
360
- let failingPath;
361
- try {
362
- for (const { file, abs } of targets) {
363
- failingPath = file.path;
364
- if (!previous.has(file.path)) previous.set(file.path, existsSync(abs) ? readFileSync(abs) : void 0);
365
- mkdirSync(dirname(abs), { recursive: true });
366
- writeFileSync(abs, file.path === "package.json" && opts.packageManager ? withPackageManager(file.contents, opts.packageManager) : file.contents);
367
- written.push(file.path);
368
- }
369
- } catch (e) {
370
- const code2 = e?.code ?? e.message;
371
- if (opts.created) {
372
- rmSync(root, { recursive: true, force: true });
373
- throw new CliError(`Could not write ${failingPath} (${code2}). Removed ${root} again; nothing was left behind.`);
374
- }
375
- let restored = 0;
376
- let removed = 0;
377
- for (const p of written) {
378
- const abs = resolveInside(root, p);
379
- const before = previous.get(p);
380
- if (before === void 0) {
381
- rmSync(abs, { force: true });
382
- removed++;
383
- } else {
384
- writeFileSync(abs, before);
385
- restored++;
386
- }
387
- }
388
- throw new CliError(`Could not write ${failingPath} (${code2}). Restored ${restored} file(s) and removed ${removed} new file(s); the folder is as it was.`);
389
- }
390
- return { written };
391
- }
392
- function withPackageManager(contents, packageManager) {
393
- const pkg = JSON.parse(contents);
394
- return `${JSON.stringify({ ...pkg, packageManager }, null, 2)}
395
- `;
396
- }
397
-
398
2461
  // src/commands/scaffold.ts
399
2462
  function askFolder(fallback) {
400
2463
  return process.stdin.isTTY === true ? ask("Folder", fallback) : Promise.resolve(fallback);
401
2464
  }
402
- async function requireToken(given) {
403
- const token = given ?? await askHidden("Project token (workbench \u2192 Project settings):");
404
- if (!token) throw new CliError("A project token is required. In the workbench open Project settings and copy the project token.");
405
- return token;
2465
+ var TOKEN_REQUIRED = "A project token is required. In the workbench open Project settings and copy the project token.";
2466
+ var isTerminal = () => process.stdin.isTTY === true && process.stdout.isTTY === true;
2467
+ async function requireToken(given, opts) {
2468
+ if (!opts) {
2469
+ const token = given ?? await askHidden("Project token (workbench \u2192 Project settings):");
2470
+ if (!token) throw new CliError(TOKEN_REQUIRED);
2471
+ return token;
2472
+ }
2473
+ return (await requireSavedToken(given, opts)).token;
2474
+ }
2475
+ async function requireSavedToken(given, opts) {
2476
+ const resolved = await resolveToken({ given, cwd: opts.cwd, store: opts.store ?? defaultStore(), interactive: opts.interactive ?? isTerminal(), prompt: true });
2477
+ if (!resolved) throw new CliError(TOKEN_REQUIRED);
2478
+ return resolved;
2479
+ }
2480
+ async function savedToken(given, opts) {
2481
+ return resolveToken({ given, cwd: opts.cwd, store: opts.store ?? defaultStore(), interactive: opts.interactive ?? isTerminal(), prompt: false });
406
2482
  }
407
2483
  async function scaffold(input, env, io) {
408
2484
  const { folder, framework, token, api, force } = input;
@@ -418,72 +2494,283 @@ ${written.map((p) => ` ${p}`).join("\n")}
418
2494
  io.stdout(nextStepsText({ runner, framework, folder, created }));
419
2495
  }
420
2496
 
421
- // src/commands/create.ts
422
- async function runCreate(args, env, io) {
423
- const folder = args.folder ?? await askFolder(CREATE_DEFAULT_FOLDER);
424
- const token = await requireToken(args.token);
425
- await scaffold({ folder, framework: "next", token, api: args.api, force: args.force }, env, io);
2497
+ // src/commands/add.ts
2498
+ var ADD_MODES = [
2499
+ { value: "all", label: "All" },
2500
+ { value: "some", label: "Pick some\u2026" }
2501
+ ];
2502
+ var PICK_QUESTION = "Add which components?";
2503
+ var namesIn = (line) => [...new Set(line.split(/[\s,]+/).filter(Boolean))];
2504
+ function ttyQuestions(args, mode, io) {
2505
+ return {
2506
+ async pickComponents(all) {
2507
+ if ((mode ?? await pick(PICK_QUESTION, ADD_MODES, 0)) === "all") return all;
2508
+ const valid = new Set(all);
2509
+ for (let attempt = 0; ; attempt++) {
2510
+ const names = namesIn(await askLine("Components (comma-separated):"));
2511
+ const unknown = names.filter((n) => !valid.has(n));
2512
+ if (names.length > 0 && unknown.length === 0) return names;
2513
+ if (attempt > 0) throw new CliError(unknown.length > 0 ? `Unknown component(s): ${unknown.join(", ")}.` : "No components given.");
2514
+ io.stdout(`${unknown.length > 0 ? `Unknown: ${unknown.join(", ")}. ` : ""}The components are: ${all.join(", ")}
2515
+ `);
2516
+ }
2517
+ },
2518
+ async confirmReplace(paths) {
2519
+ if (args.force) return true;
2520
+ io.stdout(`${paths.map((p) => ` ${p}`).join("\n")}
2521
+ `);
2522
+ return confirm(`Replace ${paths.length} existing component${paths.length === 1 ? "" : "s"} with your design system's?`, false);
2523
+ },
2524
+ async keepEdits(path) {
2525
+ if (args.force) return false;
2526
+ return confirm(`Keep your edits to ${path}?`, true);
2527
+ }
2528
+ };
2529
+ }
2530
+ async function runAddCommand(args, io, exec = spawnExec, store) {
2531
+ const root = io.cwd;
2532
+ const terminal = process.stdin.isTTY === true && process.stdout.isTTY === true;
2533
+ const interactive = !args.yes && terminal;
2534
+ const info = detectApp(root);
2535
+ assertCanAdd(info);
2536
+ const targets = info.shadcn ? resolveTargets(root, info.shadcn) : defaultTargets(root, info);
2537
+ assertKitUtils(root, info, targets);
2538
+ let mode;
2539
+ if (interactive && args.components.length === 0 && !args.all) {
2540
+ if (previouslyAdded(root, targets).every((n) => n === "utils")) mode = await pick(PICK_QUESTION, ADD_MODES, 0);
2541
+ }
2542
+ const { token, entry } = await requireSavedToken(args.token, { cwd: root, store, interactive: terminal });
2543
+ const questions = interactive ? ttyQuestions(args, mode, io) : nonInteractiveQuestions(args);
2544
+ try {
2545
+ const result = await runAdd(
2546
+ { root, token, api: apiFor(args, entry), components: args.components, skipInstall: args.skipInstall, all: args.all },
2547
+ { fetchImpl: io.fetchImpl, exec, questions, progress: (line) => io.stdout(`${line}
2548
+ `) }
2549
+ );
2550
+ io.stdout(summaryLines(result).map((line) => `${line}
2551
+ `).join(""));
2552
+ } catch (e) {
2553
+ if (e instanceof StepError && e.outputTail) io.stderr(`${e.outputTail}
2554
+ `);
2555
+ throw e;
2556
+ }
426
2557
  }
427
2558
 
428
- // src/picker.ts
429
- import { emitKeypressEvents } from "node:readline";
430
- function pick(question, options, defaultIndex = 0) {
431
- const stdin = process.stdin;
432
- const stdout = process.stdout;
433
- const tty = stdin.isTTY === true && stdout.isTTY === true && typeof stdin.setRawMode === "function" && !hasInterface();
434
- if (!tty) return askChoice(question, options.map((o) => o.value), defaultIndex);
435
- return pickTty(question, options, defaultIndex, stdin, stdout);
2559
+ // src/commands/connect.ts
2560
+ import { accessSync, constants as constants2, existsSync as existsSync9, statSync as statSync3 } from "node:fs";
2561
+ import { homedir as homedir2 } from "node:os";
2562
+ import { join as join7 } from "node:path";
2563
+
2564
+ // src/connect/fetch-project.ts
2565
+ var RejectedTokenError = class extends CliError {
2566
+ constructor() {
2567
+ super(TOKEN_MESSAGE);
2568
+ }
2569
+ };
2570
+ var malformed3 = () => new CliError("Unexpected response from the API \u2014 not a project.");
2571
+ async function fetchProject(opts, fetchImpl = fetch) {
2572
+ const url = new URL("/api/project", `${opts.api}/`);
2573
+ let res;
2574
+ try {
2575
+ res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" } });
2576
+ } catch {
2577
+ throw new CliError(UNREACHABLE(opts.api));
2578
+ }
2579
+ const body = await res.json().catch(() => null);
2580
+ if (res.status === 401) throw new RejectedTokenError();
2581
+ if (!res.ok) throw new CliError(messageForResponse(res.status, body, opts.api));
2582
+ if (typeof body !== "object" || body === null) throw malformed3();
2583
+ const { id, name } = body;
2584
+ if (typeof id !== "string" || typeof name !== "string") throw malformed3();
2585
+ assertProjectId(id);
2586
+ return { id, name };
436
2587
  }
437
- function pickTty(question, options, start, stdin, stdout) {
438
- const color = !process.env.NO_COLOR;
439
- const bold = (s) => color ? `\x1B[1m${s}\x1B[22m` : s;
440
- const dim = (s) => color ? `\x1B[2m${s}\x1B[22m` : s;
441
- const n = options.length;
442
- let index = start;
443
- const rows = () => options.map((o, i) => {
444
- const label = i === index ? bold(o.label) : o.label;
445
- return `${i === index ? "\u276F" : " "} ${label}${o.hint ? ` ${dim(o.hint)}` : ""}`;
446
- });
447
- const draw = (lines) => stdout.write(lines.map((l) => `\r\x1B[2K${l}`).join("\n") + "\n");
448
- const up = () => stdout.write(`\x1B[${n + 1}A`);
449
- emitKeypressEvents(stdin);
450
- stdin.setRawMode(true);
451
- stdin.resume();
452
- stdout.write("\x1B[?25l");
453
- draw([question, ...rows()]);
454
- return new Promise((resolve3, reject) => {
455
- const finish = (after) => {
456
- stdin.off("keypress", onKey);
457
- stdin.setRawMode(false);
458
- stdin.pause();
459
- after();
460
- stdout.write("\x1B[?25h");
461
- };
462
- const onKey = (str, key = {}) => {
463
- if (key.ctrl && key.name === "c" || key.name === "escape") {
464
- finish(() => stdout.write("\n"));
465
- reject(new CliError(CANCELLED, 130));
466
- return;
467
- }
468
- if (key.name === "return" || key.name === "enter") {
469
- const chosen = options[index];
470
- finish(() => {
471
- up();
472
- stdout.write(`\r\x1B[J${question} ${chosen.label}
473
- `);
474
- });
475
- resolve3(chosen.value);
476
- return;
2588
+
2589
+ // src/connect/project-root.ts
2590
+ import { existsSync as existsSync8 } from "node:fs";
2591
+ import { dirname as dirname3, isAbsolute as isAbsolute3, join as join6, relative as relative3, resolve as resolve4, sep as sep3 } from "node:path";
2592
+ function projectRoot(cwd, exists = existsSync8) {
2593
+ let dir = resolve4(cwd);
2594
+ for (; ; ) {
2595
+ if (exists(join6(dir, ".git"))) return dir;
2596
+ const parent = dirname3(dir);
2597
+ if (parent === dir) return resolve4(cwd);
2598
+ dir = parent;
2599
+ }
2600
+ }
2601
+ function within2(folder, root) {
2602
+ const rel = relative3(root, folder);
2603
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep3}`) && !isAbsolute3(rel);
2604
+ }
2605
+ function homeFolderRefusal(root, home) {
2606
+ const folder = resolve4(root);
2607
+ const homeDir = resolve4(home);
2608
+ const tail = "and writing there would set up every project on this computer.";
2609
+ if (folder === homeDir) return `Run this in your project folder \u2014 ${folder} is your home folder, ${tail}`;
2610
+ if (dirname3(folder) === folder || within2(homeDir, folder)) return `Run this in your project folder \u2014 ${folder} is a system folder, ${tail}`;
2611
+ return null;
2612
+ }
2613
+
2614
+ // src/commands/connect.ts
2615
+ var TERMINAL_PROMPTS = { pickMany, pick: (question, options) => pick(question, options, 0), askHidden };
2616
+ function onPath(bin, env, platform) {
2617
+ const windows = platform === "win32";
2618
+ const dirs = (env.PATH ?? env.Path ?? "").split(windows ? ";" : ":").filter(Boolean);
2619
+ const exts = windows ? ["", ...(env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""];
2620
+ return dirs.some(
2621
+ (dir) => exts.some((ext) => {
2622
+ const file = join7(dir, bin + ext);
2623
+ try {
2624
+ if (!statSync3(file).isFile()) return false;
2625
+ if (!windows) accessSync(file, constants2.X_OK);
2626
+ return true;
2627
+ } catch {
2628
+ return false;
477
2629
  }
478
- if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
479
- else if (key.name === "down" || str === "j") index = (index + 1) % n;
480
- else if (str && /^[1-9]$/.test(str) && Number(str) <= n) index = Number(str) - 1;
481
- else return;
482
- up();
483
- draw([question, ...rows()]);
484
- };
485
- stdin.on("keypress", onKey);
486
- });
2630
+ })
2631
+ );
2632
+ }
2633
+ function defaultConnectDeps(env) {
2634
+ const home = homedir2();
2635
+ const platform = process.platform;
2636
+ return {
2637
+ store: defaultStore(env),
2638
+ detect: () => detectApps({ env, platform, home, exists: existsSync9, onPath: (bin) => onPath(bin, env, platform) }),
2639
+ credentialsPath: credentialsPath(env, platform, home)
2640
+ };
2641
+ }
2642
+ var APP_OPTIONS = APPS.map((a) => ({ value: a.id, label: a.label, hint: a.file }));
2643
+ var app = (id) => APPS.find((a) => a.id === id);
2644
+ var NO_APPS_FOUND = "No coding apps found. Pass --apps claude,cursor,vscode,codex,gemini.";
2645
+ var NO_APPS_PICKED = "No apps picked. Nothing was changed.";
2646
+ var SAVED_TOKEN_REJECTED = "The saved token for this project was not accepted. Run again with --token <project token> (or DS_SYNC_TOKEN) to replace it.";
2647
+ function savedLine(name, where, file) {
2648
+ if (where === "keychain") return `Saved your token for "${name}" in the macOS keychain \u2713`;
2649
+ if (where === "secret-service") return `Saved your token for "${name}" in the system keyring \u2713`;
2650
+ if (where === "dpapi") return `Saved your token for "${name}" with Windows protection \u2713`;
2651
+ return `Saved your token for "${name}" in ${file} (readable only by you) \u2713`;
2652
+ }
2653
+ function whereFrom(where, file) {
2654
+ return where === "keychain" ? "the macOS keychain" : where === "secret-service" ? "the system keyring" : file;
2655
+ }
2656
+ function appLines(id, plan) {
2657
+ const { label, format, key } = app(id);
2658
+ const head = ` ${label} ${plan.path}`;
2659
+ if (plan.status === "create" || plan.status === "update") return [`${head} \u2713`];
2660
+ if (plan.status === "unchanged") {
2661
+ const lines = [`${head} (already set up)`];
2662
+ if (plan.hasEnv) lines.push(` ${plan.path} still holds a token in its env; connect does not need it, so you can delete that env block.`);
2663
+ return lines;
2664
+ }
2665
+ const entry = (plan.manualEntry ?? "").split("\n").map((l) => ` ${l}`);
2666
+ const why = format === "toml" ? `${head}: it defines designsource another way, so it was not changed. Put this table in its place:` : `${head}: it has comments or is not plain JSON, so it was not changed. Add this entry under "${key}":`;
2667
+ return [why, ...entry];
2668
+ }
2669
+ function closingLines(apps, changed) {
2670
+ const has = (id) => apps.includes(id);
2671
+ const restart = [changed.includes("cursor") && "Cursor", changed.includes("vscode") && "VS Code"].filter((s) => typeof s === "string");
2672
+ return [
2673
+ "Done.",
2674
+ ...restart.length > 0 ? [`Restart ${restart.join(" and ")}.`] : [],
2675
+ ...has("claude") ? ["Claude Code asks once to allow the server."] : [],
2676
+ ...has("codex") ? ["Codex reads it once you trust this project in Codex."] : [],
2677
+ ...has("gemini") ? ["Gemini CLI reads it unless folder trust is on and this folder is not trusted."] : [],
2678
+ "Then ask your agent to add the UI kit.",
2679
+ "These files hold no token and are safe to commit; teammates run npx designsource connect once."
2680
+ ];
2681
+ }
2682
+ async function runConnect(args, io, deps = defaultConnectDeps(process.env)) {
2683
+ const { store } = deps;
2684
+ const terminal = deps.terminal ?? (process.stdin.isTTY === true && process.stdout.isTTY === true);
2685
+ const interactive = terminal && !args.yes;
2686
+ const prompts = deps.prompts ?? TERMINAL_PROMPTS;
2687
+ const root = projectRoot(io.cwd);
2688
+ const say = (lines) => io.stdout(lines.map((l) => `${l}
2689
+ `).join(""));
2690
+ if (args.forget) return forget(args, root, store, interactive, prompts, deps.credentialsPath, say);
2691
+ const refusal = homeFolderRefusal(root, deps.home ?? homedir2());
2692
+ if (refusal) throw new CliError(refusal);
2693
+ say([`Connecting ${root}`]);
2694
+ let apps;
2695
+ const connected = args.apps ? null : connectedApps(root, store);
2696
+ if (args.apps) apps = args.apps;
2697
+ else if (connected) apps = connected;
2698
+ else {
2699
+ const detected = deps.detect();
2700
+ if (interactive) {
2701
+ apps = await prompts.pickMany("Connect which apps?", APP_OPTIONS, detected);
2702
+ if (apps.length === 0) throw new CliError(NO_APPS_PICKED);
2703
+ } else {
2704
+ if (detected.length === 0) throw new CliError(NO_APPS_FOUND);
2705
+ apps = detected;
2706
+ }
2707
+ }
2708
+ const resolved = await resolveToken({ given: args.token, cwd: root, store, interactive, prompt: true }, prompts);
2709
+ if (!resolved) throw new CliError(TOKEN_REQUIRED);
2710
+ let token = resolved.token;
2711
+ let saved = args.token === void 0 ? resolved.entry : null;
2712
+ const api = apiFor(args, saved);
2713
+ const savedApi = api === DEFAULT_API_ORIGIN ? void 0 : api;
2714
+ let project;
2715
+ try {
2716
+ project = await fetchProject({ api, token }, io.fetchImpl);
2717
+ } catch (e) {
2718
+ if (!(e instanceof RejectedTokenError) || !saved) throw e;
2719
+ if (!interactive) throw new CliError(SAVED_TOKEN_REJECTED);
2720
+ token = await prompts.askHidden("The saved token was not accepted. Project token (workbench \u2192 Project settings):");
2721
+ if (!token) throw new CliError(TOKEN_REQUIRED);
2722
+ saved = null;
2723
+ project = await fetchProject({ api, token }, io.fetchImpl);
2724
+ }
2725
+ const plans = apps.map((id) => ({ id, plan: planAppFile(root, id, project.id) }));
2726
+ const kept = saved && saved.projectId === project.id ? store.addFolder(project.id, root, savedApi) : null;
2727
+ const entry = kept ?? await store.save({ projectId: project.id, name: project.name, folder: root, token, ...savedApi === void 0 ? {} : { api: savedApi } });
2728
+ const files = plans.flatMap(({ plan }) => plan.contents !== null && (plan.status === "create" || plan.status === "update") ? [{ path: plan.path, contents: plan.contents }] : []);
2729
+ try {
2730
+ if (files.length > 0) writeFiles(root, files, { force: true, created: false });
2731
+ } catch (e) {
2732
+ if (e instanceof CliError) throw new CliError(`${e.message} Your token for "${project.name}" was saved; run connect again to write the settings.`, e.exitCode);
2733
+ throw e;
2734
+ }
2735
+ const changed = plans.filter(({ plan }) => plan.status === "create" || plan.status === "update").map(({ id }) => id);
2736
+ const backup = "backup" in entry && entry.backup ? [`Your old credentials file could not be read, so it was kept as ${entry.backup}.`] : [];
2737
+ say([...backup, savedLine(project.name, entry.where, deps.credentialsPath), ...plans.flatMap(({ id, plan }) => appLines(id, plan)), ...closingLines(apps, changed)]);
2738
+ }
2739
+ function connectedApps(root, store) {
2740
+ const saved = store.byFolder(root);
2741
+ if (saved.length !== 1) return null;
2742
+ const { projectId } = saved[0];
2743
+ const apps = APPS.filter((a) => {
2744
+ try {
2745
+ return planAppFile(root, a.id, projectId).status === "unchanged";
2746
+ } catch {
2747
+ return false;
2748
+ }
2749
+ }).map((a) => a.id);
2750
+ return apps.length > 0 ? apps : null;
2751
+ }
2752
+ async function forget(args, root, store, interactive, prompts, file, say) {
2753
+ const matches = store.byFolder(root).filter((m) => args.project === void 0 || m.projectId === args.project);
2754
+ if (matches.length === 0) return say(["No saved token for this folder."]);
2755
+ let chosen = matches[0];
2756
+ if (matches.length > 1) {
2757
+ if (!interactive) {
2758
+ const names = matches.map((m) => `${m.name} (${m.projectId})`).join(", ");
2759
+ throw new CliError(`More than one design system is connected to this folder: ${names}. Pass --project <id> to say which to forget.`);
2760
+ }
2761
+ const id = await prompts.pick("Forget which design system?", matches.map((m) => ({ value: m.projectId, label: m.name, hint: m.projectId })));
2762
+ chosen = matches.find((m) => m.projectId === id);
2763
+ }
2764
+ const removed = await store.forget(chosen.projectId) ?? chosen;
2765
+ say([`Removed the saved token for "${removed.name}" from ${whereFrom(removed.where, file)}.`]);
2766
+ }
2767
+
2768
+ // src/commands/create.ts
2769
+ async function runCreate(args, env, io, store) {
2770
+ const saved = await savedToken(args.token, { cwd: io.cwd, store });
2771
+ const folder = args.folder ?? await askFolder(CREATE_DEFAULT_FOLDER);
2772
+ const token = saved?.token ?? await requireToken(void 0);
2773
+ await scaffold({ folder, framework: "next", token, api: apiFor(args, saved?.entry), force: args.force }, env, io);
487
2774
  }
488
2775
 
489
2776
  // src/commands/integrate.ts
@@ -493,18 +2780,19 @@ var INTEGRATE_OPTIONS = [
493
2780
  { value: "angular", label: "Angular" },
494
2781
  { value: "css", label: "Plain CSS", hint: "any other stack" }
495
2782
  ];
496
- async function runIntegrate(args, env, io) {
2783
+ async function runIntegrate(args, env, io, store) {
497
2784
  const framework = args.framework ?? await pick("Framework", INTEGRATE_OPTIONS, 0);
2785
+ const saved = await savedToken(args.token, { cwd: io.cwd, store });
498
2786
  const folder = args.folder ?? await askFolder(INTEGRATE_DEFAULT_FOLDER);
499
- const token = await requireToken(args.token);
500
- await scaffold({ folder, framework, token, api: args.api, force: args.force }, env, io);
2787
+ const token = saved?.token ?? await requireToken(void 0);
2788
+ await scaffold({ folder, framework, token, api: apiFor(args, saved?.entry), force: args.force }, env, io);
501
2789
  }
502
2790
 
503
2791
  // src/mcp/server.ts
504
2792
  import { createInterface as createInterface2 } from "node:readline";
505
2793
 
506
2794
  // src/version.ts
507
- var VERSION = true ? "0.4.0" : "0.0.0-dev";
2795
+ var VERSION = true ? "0.5.0" : "0.0.0-dev";
508
2796
 
509
2797
  // src/mcp/jsonrpc.ts
510
2798
  var PARSE_ERROR = -32700;
@@ -560,7 +2848,23 @@ function getPrompt(name) {
560
2848
  return { description: "Integrate the design system into the current repository.", messages: [{ role: "user", content: { type: "text", text: INTEGRATE_TEXT } }] };
561
2849
  }
562
2850
 
2851
+ // src/mcp/project-folder.ts
2852
+ import { isAbsolute as isAbsolute4, relative as relative4, resolve as resolve5, sep as sep4 } from "node:path";
2853
+ var NOT_SURE_WHICH_FOLDER = "Not sure which project folder to change: run npx designsource connect in it first.";
2854
+ function isWithin2(folder, root) {
2855
+ const rel = relative4(root, folder);
2856
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep4}`) && !isAbsolute4(rel);
2857
+ }
2858
+ function resolveProjectFolder(cwd, entry) {
2859
+ if (!entry) return cwd;
2860
+ const here = resolve5(cwd);
2861
+ const holding = entry.folders.map((f) => resolve5(f)).filter((f) => isWithin2(here, f)).sort((a, b) => b.length - a.length);
2862
+ if (holding[0]) return holding[0];
2863
+ return entry.folders.length === 1 ? resolve5(entry.folders[0]) : null;
2864
+ }
2865
+
563
2866
  // src/mcp/tools.ts
2867
+ var READ_ONLY = { readOnlyHint: true };
564
2868
  var textResult = (text) => ({ content: [{ type: "text", text }] });
565
2869
  var errorResult = (text) => ({ content: [{ type: "text", text }], isError: true });
566
2870
  var TIERS = ["design", "semantic", "component"];
@@ -569,12 +2873,14 @@ var NO_INPUT = { type: "object", properties: {}, additionalProperties: false };
569
2873
  var pretty = (v) => JSON.stringify(v, null, 2);
570
2874
  var NO_BLOCKS = "This server sent no blocks. Update designsource and the server.";
571
2875
  var SOURCE_HEADER = "// Reference implementation. Use verbatim in React + Tailwind; port to your stack otherwise, keeping every var() chain.";
572
- var BLOCK_SOURCE_HEADER = `${SOURCE_HEADER}
2876
+ var FALLBACK_BLOCK_SOURCE_HEADER = `${SOURCE_HEADER}
573
2877
  // The block renders inside BlockStage (components/blocks/stage.tsx, below), which supplies the @container/stage its
574
2878
  // responsive classes query and the frame height its min-h-full fills: render <BlockStage><Block /></BlockStage> as a
575
2879
  // full-viewport page. components/ui/preview-portal.tsx is the portal context the stage provides; the kit components
576
2880
  // list_blocks names for this block come from get_component_source.`;
577
2881
  var UTILS_HEADER = "// The `cn` helper every component imports from `@/lib/utils`. Save as lib/utils.ts in React; port or drop elsewhere.";
2882
+ var PORTAL_HEADER = "// The portal context components import from `./preview-portal`. Save it beside them as components/ui/preview-portal.tsx in React: with no provider it portals to document.body, as stock shadcn does. Port or drop elsewhere.";
2883
+ var blockAppPath = (key) => key.startsWith("kit/") ? `components/ui/${key.slice("kit/".length)}` : `components/${key}`;
578
2884
  var componentsIn = (snapshot) => [...new Set(snapshot.canonical.tokens.map((t) => t.component).filter((c) => c !== null))].sort();
579
2885
  function optionalEnum(args, key, allowed) {
580
2886
  const v = args[key];
@@ -584,11 +2890,55 @@ function optionalEnum(args, key, allowed) {
584
2890
  }
585
2891
  return { ok: true, value: v };
586
2892
  }
2893
+ var MCP_EXEC_TIMEOUT_MS = 10 * 60 * 1e3;
2894
+ var UNKNOWN_FOR_AGENT = (names) => `Unknown component(s): ${names.join(", ")}. Call list_components for the names.`;
2895
+ var FOREIGN_FILES = (paths) => `These files exist and were not added by designsource: ${paths.join(", ")}. Ask the user whether to replace them, then call add_ui_kit again with replace_existing: true.`;
2896
+ async function addUiKit(args, ctx) {
2897
+ const { components, replace_existing: replace } = args;
2898
+ if (components !== void 0 && !(Array.isArray(components) && components.every((c) => typeof c === "string"))) {
2899
+ return errorResult('"components" must be an array of component names.');
2900
+ }
2901
+ if (replace !== void 0 && typeof replace !== "boolean") return errorResult('"replace_existing" must be true or false.');
2902
+ if (ctx.token === null) return errorResult(ctx.missingToken ?? MCP_TOKEN_REQUIRED);
2903
+ const root = resolveProjectFolder(ctx.cwd, ctx.projectFolders === null ? null : { folders: ctx.projectFolders });
2904
+ if (root === null) return errorResult(NOT_SURE_WHICH_FOLDER);
2905
+ const questions = {
2906
+ pickComponents: async (all) => all,
2907
+ confirmReplace: async (paths) => {
2908
+ if (replace !== true) throw new CliError(FOREIGN_FILES(paths));
2909
+ return true;
2910
+ },
2911
+ keepEdits: async () => true
2912
+ };
2913
+ const progress = [];
2914
+ const exec = (cmd, cmdArgs, opts) => ctx.exec(cmd, cmdArgs, { ...opts, timeoutMs: MCP_EXEC_TIMEOUT_MS });
2915
+ try {
2916
+ const result = await runAdd(
2917
+ { root, token: ctx.token, api: ctx.api, components: components ?? [], skipInstall: false },
2918
+ { fetchImpl: ctx.fetchImpl, exec, questions, progress: (line) => progress.push(line) }
2919
+ );
2920
+ const written = result.added.filter((n) => n !== "preview-portal");
2921
+ return textResult(
2922
+ [
2923
+ ...progress,
2924
+ ...summaryLines(result),
2925
+ ...written.length > 0 ? [`Added: ${written.join(", ")}`] : [],
2926
+ `Next: import components from ${result.uiAlias} (for example: import { Button } from "${result.uiAlias}/button").`
2927
+ ].join("\n")
2928
+ );
2929
+ } catch (e) {
2930
+ if (!(e instanceof CliError) && progress.length === 0) throw e;
2931
+ const message = e instanceof UnknownComponentsError ? UNKNOWN_FOR_AGENT(e.names) : e instanceof Error ? e.message : String(e);
2932
+ const tail = e instanceof StepError && e.outputTail ? ["Last output:", e.outputTail] : [];
2933
+ return errorResult([...progress, message, ...tail].join("\n"));
2934
+ }
2935
+ }
587
2936
  var TOOLS = [
588
2937
  {
589
2938
  name: "get_project",
590
2939
  description: "The design system's name, token count, corner-radius strategy, font families and whether it has a mockup page. Call this first.",
591
2940
  inputSchema: NO_INPUT,
2941
+ annotations: READ_ONLY,
592
2942
  run: (snapshot, fetchedAt) => textResult(pretty({ ...snapshot.project, fetchedAt: new Date(fetchedAt).toISOString() }))
593
2943
  },
594
2944
  {
@@ -603,6 +2953,7 @@ var TOOLS = [
603
2953
  },
604
2954
  additionalProperties: false
605
2955
  },
2956
+ annotations: READ_ONLY,
606
2957
  run: (snapshot, _at, args) => {
607
2958
  const tier = optionalEnum(args, "tier", TIERS);
608
2959
  if (!tier.ok) return tier.error;
@@ -620,18 +2971,21 @@ var TOOLS = [
620
2971
  name: "get_css_variables",
621
2972
  description: "The whole design system as plain CSS custom properties for any stack: design tokens in :root, semantic and component tokens as var() aliases per theme, light and dark via [data-theme] and prefers-color-scheme.",
622
2973
  inputSchema: NO_INPUT,
2974
+ annotations: READ_ONLY,
623
2975
  run: (snapshot) => textResult(snapshot.cssVars)
624
2976
  },
625
2977
  {
626
2978
  name: "get_shadcn_theme",
627
2979
  description: "The design system as a shadcn/ui theme stylesheet for Tailwind v4: :root and .dark blocks plus @theme inline. Use on the React + Tailwind path.",
628
2980
  inputSchema: NO_INPUT,
2981
+ annotations: READ_ONLY,
629
2982
  run: (snapshot) => textResult(snapshot.shadcnTheme)
630
2983
  },
631
2984
  {
632
2985
  name: "list_components",
633
2986
  description: "Every component in the kit with the CSS variables its source reads, plus the helper files. Follow with get_component_source.",
634
2987
  inputSchema: NO_INPUT,
2988
+ annotations: READ_ONLY,
635
2989
  run: (snapshot) => textResult(
636
2990
  pretty({
637
2991
  components: Object.entries(snapshot.kit.variables).sort(([a], [b]) => a.localeCompare(b)).map(([name, variables]) => ({ name, variables })),
@@ -641,13 +2995,14 @@ var TOOLS = [
641
2995
  },
642
2996
  {
643
2997
  name: "get_component_source",
644
- description: 'The React + Tailwind source of one component (see list_components), or "utils" for the cn helper. Use verbatim in React; port to any other stack keeping every var() chain.',
645
- inputSchema: { type: "object", properties: { name: { type: "string", description: "A name from list_components, or utils." } }, required: ["name"], additionalProperties: false },
2998
+ description: 'The React + Tailwind source of one component (see list_components), or a helper: "utils" for the cn helper, "preview-portal" for the portal context components import. Use verbatim in React; port to any other stack keeping every var() chain.',
2999
+ inputSchema: { type: "object", properties: { name: { type: "string", description: "A name from list_components, or a helper (utils, preview-portal)." } }, required: ["name"], additionalProperties: false },
3000
+ annotations: READ_ONLY,
646
3001
  run: (snapshot, _at, args) => {
647
3002
  const names = Object.keys(snapshot.kit.sources).sort();
648
3003
  const name = args.name;
649
3004
  if (typeof name !== "string" || !names.includes(name)) return errorResult(`"name" must be one of: ${names.join(", ")}.`);
650
- const header = name in snapshot.kit.variables ? SOURCE_HEADER : UTILS_HEADER;
3005
+ const header = name in snapshot.kit.variables ? SOURCE_HEADER : name === "preview-portal" ? PORTAL_HEADER : UTILS_HEADER;
651
3006
  return textResult(`${header}
652
3007
  ${snapshot.kit.sources[name]}`);
653
3008
  }
@@ -656,6 +3011,7 @@ ${snapshot.kit.sources[name]}`);
656
3011
  name: "get_mockup_page",
657
3012
  description: "The project's own mockup page as a layout spec, followed by the React renderer and schema that paint it. Render it as the first route.",
658
3013
  inputSchema: NO_INPUT,
3014
+ annotations: READ_ONLY,
659
3015
  run: (snapshot) => {
660
3016
  if (!snapshot.mockup) return textResult("This project has no mockup page.");
661
3017
  const files = Object.entries(snapshot.mockup.renderer).sort(([a], [b]) => a.localeCompare(b)).map(([file, source]) => `
@@ -669,34 +3025,51 @@ ${files.join("\n")}`);
669
3025
  name: "get_integration_guide",
670
3026
  description: "Step-by-step instructions for integrating this design system into the current repository: wire the tokens, bring in the components, migrate existing styles, document. Read this before changing anything.",
671
3027
  inputSchema: NO_INPUT,
3028
+ annotations: READ_ONLY,
672
3029
  run: (snapshot) => textResult(snapshot.guide)
673
3030
  },
674
3031
  {
675
3032
  name: "list_blocks",
676
3033
  description: "Ready-made page layouts built from the kit (login, signup, sidebars, a dashboard, chart sets): id, title, family, components used and files. Follow with get_block_source.",
677
3034
  inputSchema: NO_INPUT,
3035
+ annotations: READ_ONLY,
678
3036
  run: (snapshot) => snapshot.blocks ? textResult(pretty(snapshot.blocks.index)) : errorResult(NO_BLOCKS)
679
3037
  },
680
3038
  {
681
3039
  name: "get_block_source",
682
3040
  description: "Every file of one block (see list_blocks), each headed by the path it takes in the app: the block under components/blocks/, plus BlockStage (components/blocks/stage.tsx), which supplies the @container/stage its responsive classes query and the frame height, and the portal context it provides (components/ui/preview-portal.tsx). Render <BlockStage><Block /></BlockStage> as a full-viewport page. Use verbatim in React + Tailwind; port elsewhere keeping every var() chain.",
683
3041
  inputSchema: { type: "object", properties: { id: { type: "string", description: "A block id from list_blocks." } }, required: ["id"], additionalProperties: false },
3042
+ annotations: READ_ONLY,
684
3043
  run: (snapshot, _at, args) => {
685
3044
  const blocks = snapshot.blocks;
686
3045
  if (!blocks) return errorResult(NO_BLOCKS);
687
3046
  const entry = blocks.index.find((b) => b.id === args.id);
688
3047
  if (!entry) return errorResult(`"id" must be one of: ${blocks.index.map((b) => b.id).join(", ")}.`);
689
- const path = (f) => f.startsWith("kit/") ? `components/ui/${f.slice("kit/".length)}` : `components/${f}`;
690
- const files = entry.files.map((f) => `--- file: ${path(f)}
3048
+ const files = entry.files.map((f) => `--- file: ${blockAppPath(f)}
691
3049
  ${blocks.sources[f] ?? ""}`);
692
- return textResult(`${BLOCK_SOURCE_HEADER}
3050
+ return textResult(`${blocks.header ?? FALLBACK_BLOCK_SOURCE_HEADER}
693
3051
  ${files.join("\n\n")}`);
694
3052
  }
3053
+ },
3054
+ {
3055
+ name: "add_ui_kit",
3056
+ description: "Add this design system's UI kit to the React app in the current folder: the theme, the components and their libraries. Sets up Tailwind and shadcn when the app lacks them. Changes files in the project, so your client will ask the user first. Never overwrites components the user edited.",
3057
+ inputSchema: {
3058
+ type: "object",
3059
+ properties: {
3060
+ components: { type: "array", items: { type: "string" }, description: "Component names such as button or dialog. Omit to add everything (or refresh what was added before)." },
3061
+ replace_existing: { type: "boolean", description: "Replace component files that exist but were not added by designsource. Ask the user first." }
3062
+ },
3063
+ additionalProperties: false
3064
+ },
3065
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
3066
+ needsSnapshot: false,
3067
+ run: (_snapshot, _at, args, ctx) => addUiKit(args, ctx)
695
3068
  }
696
3069
  ];
697
3070
  var TOOL_NAMES = TOOLS.map((t) => t.name);
698
3071
  function toolList() {
699
- return { tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) };
3072
+ return { tools: TOOLS.map(({ name, description, inputSchema, annotations }) => ({ name, description, inputSchema, annotations })) };
700
3073
  }
701
3074
  function findTool(name) {
702
3075
  return TOOLS.find((t) => t.name === name);
@@ -704,6 +3077,7 @@ function findTool(name) {
704
3077
 
705
3078
  // src/mcp/protocol.ts
706
3079
  var SUPPORTED_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
3080
+ var NO_SNAPSHOT = {};
707
3081
  var asObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
708
3082
  async function handle(parsed, deps) {
709
3083
  if (parsed.kind === "error") return parsed.response;
@@ -727,17 +3101,29 @@ async function request(msg, deps) {
727
3101
  if (typeof params.name !== "string") return fail(id, INVALID_PARAMS, 'tools/call needs a string "name"');
728
3102
  const tool = findTool(params.name);
729
3103
  if (!tool) return fail(id, INVALID_PARAMS, `Unknown tool: ${params.name}`);
730
- let cached;
3104
+ let context;
731
3105
  try {
732
- cached = await deps.snapshot();
3106
+ context = await deps.context();
733
3107
  } catch (e) {
734
3108
  if (e instanceof CliError) return respond(id, errorResult(e.message));
735
3109
  const message = e instanceof Error ? e.message : String(e);
736
- deps.warn(`designsource mcp: loading the design system failed: ${message}`);
737
- return respond(id, errorResult(`Could not load the design system: ${message}`));
3110
+ deps.warn(`designsource mcp: finding the project token failed: ${message}`);
3111
+ return respond(id, errorResult(`Could not find the project token: ${message}`));
3112
+ }
3113
+ if (context.token === null) return respond(id, errorResult(context.missingToken ?? MCP_TOKEN_REQUIRED));
3114
+ let cached = { snapshot: NO_SNAPSHOT, fetchedAt: 0 };
3115
+ if (tool.needsSnapshot !== false) {
3116
+ try {
3117
+ cached = await deps.snapshot();
3118
+ } catch (e) {
3119
+ if (e instanceof CliError) return respond(id, errorResult(e.message));
3120
+ const message = e instanceof Error ? e.message : String(e);
3121
+ deps.warn(`designsource mcp: loading the design system failed: ${message}`);
3122
+ return respond(id, errorResult(`Could not load the design system: ${message}`));
3123
+ }
738
3124
  }
739
3125
  try {
740
- return respond(id, tool.run(cached.snapshot, cached.fetchedAt, asObject(params.arguments)));
3126
+ return respond(id, await tool.run(cached.snapshot, cached.fetchedAt, asObject(params.arguments), context));
741
3127
  } catch (e) {
742
3128
  if (e instanceof CliError) return respond(id, errorResult(e.message));
743
3129
  const message = e instanceof Error ? e.message : String(e);
@@ -758,23 +3144,25 @@ async function request(msg, deps) {
758
3144
  }
759
3145
 
760
3146
  // src/mcp/snapshot-client.ts
761
- var malformed2 = () => new CliError("Unexpected response from the API \u2014 not a design system snapshot.");
762
- var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
763
- var isStringRecord = (v) => isObject(v) && Object.values(v).every((x) => typeof x === "string");
764
- var isStringListRecord = (v) => isObject(v) && Object.values(v).every((x) => Array.isArray(x) && x.every((s) => typeof s === "string"));
765
- var isBlockEntry = (v) => isObject(v) && typeof v.id === "string" && typeof v.title === "string" && typeof v.family === "string" && Array.isArray(v.components) && v.components.every((c) => typeof c === "string") && Array.isArray(v.files) && v.files.every((f) => typeof f === "string");
3147
+ var malformed4 = () => new CliError("Unexpected response from the API \u2014 not a design system snapshot.");
3148
+ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3149
+ var isStringRecord = (v) => isObject2(v) && Object.values(v).every((x) => typeof x === "string");
3150
+ var isStringListRecord = (v) => isObject2(v) && Object.values(v).every((x) => Array.isArray(x) && x.every((s) => typeof s === "string"));
3151
+ var isBlockEntry = (v) => isObject2(v) && typeof v.id === "string" && typeof v.title === "string" && typeof v.family === "string" && Array.isArray(v.components) && v.components.every((c) => typeof c === "string") && Array.isArray(v.files) && v.files.every((f) => typeof f === "string");
766
3152
  function validateSnapshot(json) {
767
- if (!isObject(json)) throw malformed2();
768
- if (typeof json.version !== "number") throw malformed2();
3153
+ if (!isObject2(json)) throw malformed4();
3154
+ if (typeof json.version !== "number") throw malformed4();
769
3155
  if (json.version !== 1) throw new CliError(UPDATE_MESSAGE);
770
3156
  const { project, canonical, cssVars, shadcnTheme, kit, mockup, blocks, guide } = json;
771
- if (!isObject(project) || typeof project.name !== "string" || typeof project.radiusStrategy !== "string" || typeof project.tokenCount !== "number" || typeof project.hasMockup !== "boolean" || !isStringRecord(project.fonts)) throw malformed2();
772
- if (!isObject(canonical) || !Array.isArray(canonical.tokens) || !canonical.tokens.every(isObject)) throw malformed2();
773
- if (typeof cssVars !== "string" || typeof shadcnTheme !== "string" || typeof guide !== "string") throw malformed2();
774
- if (!isObject(kit) || !isStringRecord(kit.sources) || !isStringListRecord(kit.variables)) throw malformed2();
775
- if (mockup !== null && !(isObject(mockup) && isObject(mockup.spec) && isStringRecord(mockup.renderer))) throw malformed2();
776
- const validBlocks = isObject(blocks) && Array.isArray(blocks.index) && blocks.index.every(isBlockEntry) && isStringRecord(blocks.sources);
777
- return validBlocks ? json : { ...json, blocks: void 0 };
3157
+ if (!isObject2(project) || typeof project.name !== "string" || typeof project.radiusStrategy !== "string" || typeof project.tokenCount !== "number" || typeof project.hasMockup !== "boolean" || !isStringRecord(project.fonts)) throw malformed4();
3158
+ if (!isObject2(canonical) || !Array.isArray(canonical.tokens) || !canonical.tokens.every(isObject2)) throw malformed4();
3159
+ if (typeof cssVars !== "string" || typeof shadcnTheme !== "string" || typeof guide !== "string") throw malformed4();
3160
+ if (!isObject2(kit) || !isStringRecord(kit.sources) || !isStringListRecord(kit.variables)) throw malformed4();
3161
+ if (mockup !== null && !(isObject2(mockup) && isObject2(mockup.spec) && isStringRecord(mockup.renderer))) throw malformed4();
3162
+ const validBlocks = isObject2(blocks) && Array.isArray(blocks.index) && blocks.index.every(isBlockEntry) && isStringRecord(blocks.sources);
3163
+ if (!validBlocks) return { ...json, blocks: void 0 };
3164
+ if (blocks.header !== void 0 && typeof blocks.header !== "string") return { ...json, blocks: { ...blocks, header: void 0 } };
3165
+ return json;
778
3166
  }
779
3167
  var FETCH_TIMEOUT_MS = 3e4;
780
3168
  async function fetchSnapshot(opts, fetchImpl = fetch) {
@@ -817,13 +3205,31 @@ function createSnapshotCache(fetcher, opts = {}) {
817
3205
  }
818
3206
 
819
3207
  // src/mcp/server.ts
820
- async function runMcp(args, io, streams = { input: process.stdin, output: process.stdout }) {
821
- const token = args.token;
822
- if (!token) throw new CliError("A project token is required: pass --token or set DS_SYNC_TOKEN (workbench \u2192 Project settings).");
3208
+ async function runMcp(args, io, streams = { input: process.stdin, output: process.stdout }, deps = {}) {
3209
+ const cwd = deps.cwd ?? process.cwd();
3210
+ const store = deps.store ?? defaultStore();
823
3211
  const warn = (line) => io.stderr(`${line}
824
3212
  `);
825
- const cache = createSnapshotCache(() => fetchSnapshot({ api: args.api, token }, io.fetchImpl), { warn });
826
- const deps = { version: VERSION, snapshot: () => cache.get(), warn };
3213
+ let found = null;
3214
+ const fromStore = !args.token;
3215
+ const session = async () => {
3216
+ if (!found && (args.token || args.project)) found = await resolveToken({ given: args.token, cwd, projectId: args.project, store, interactive: false, prompt: false });
3217
+ else if (found && found.entry === null && args.project) found = { ...found, entry: store.entry(args.project) };
3218
+ if (found) return { token: found.token, projectFolders: args.project ? found.entry?.folders ?? [] : null, api: apiFor(args, found.entry), cwd, fetchImpl: io.fetchImpl, exec: spawnExec };
3219
+ const missingToken = args.project ? NO_TOKEN_FOR_PROJECT(store.entry(args.project)?.name ?? args.project) : MCP_TOKEN_REQUIRED;
3220
+ return { token: null, missingToken, projectFolders: args.project ? [] : null, api: args.api, cwd, fetchImpl: io.fetchImpl, exec: spawnExec };
3221
+ };
3222
+ const cache = createSnapshotCache(async () => {
3223
+ const { token, missingToken, api } = await session();
3224
+ if (token === null) throw new CliError(missingToken);
3225
+ try {
3226
+ return await fetchSnapshot({ api, token }, io.fetchImpl);
3227
+ } catch (e) {
3228
+ if (fromStore && e instanceof CliError && e.message === TOKEN_MESSAGE) found = null;
3229
+ throw e;
3230
+ }
3231
+ }, { warn });
3232
+ const protocol = { version: VERSION, snapshot: () => cache.get(), warn, context: session };
827
3233
  const lines = createInterface2({ input: streams.input, crlfDelay: Infinity });
828
3234
  streams.output.on("error", () => {
829
3235
  lines.close();
@@ -831,13 +3237,15 @@ async function runMcp(args, io, streams = { input: process.stdin, output: proces
831
3237
  for await (const raw of lines) {
832
3238
  const line = raw.trim();
833
3239
  if (!line) continue;
834
- const response = await handle(parseLine(line), deps);
3240
+ const response = await handle(parseLine(line), protocol);
835
3241
  if (response) streams.output.write(encode(response));
836
3242
  }
837
3243
  }
838
3244
 
839
3245
  // src/index.ts
840
3246
  var MENU = [
3247
+ { value: "add", label: "Add the UI kit to a React app", hint: "your components and theme, set up for you" },
3248
+ { value: "connect", label: "Connect your coding apps", hint: "Claude Code, Cursor, VS Code and more" },
841
3249
  { value: "integrate", label: "Add to an existing project", hint: "writes design-system/ \u2014 tokens, prompt, reference kit" },
842
3250
  { value: "create", label: "Create a new project", hint: "a Next.js app with every component and your mockup page" }
843
3251
  ];
@@ -861,20 +3269,22 @@ ${e.usage}`);
861
3269
  try {
862
3270
  if (command.kind === "menu") {
863
3271
  if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
864
- io.stderr(`Missing command. Use integrate, create or mcp.
3272
+ io.stderr(`Missing command. ${USE_VERBS}
865
3273
 
866
3274
  ${USAGE}`);
867
3275
  return 1;
868
3276
  }
869
3277
  const verb = await pick("What do you want to do?", MENU, 0);
870
- command = verb === "create" ? { kind: "create", args: baseArgs(env) } : { kind: "integrate", args: baseArgs(env) };
3278
+ command = parseArgs([verb], env);
871
3279
  }
872
3280
  if (command.kind === "mcp") {
873
3281
  await runMcp(command.args, io);
874
3282
  return 0;
875
3283
  }
876
- if (command.kind === "create") await runCreate(command.args, env, io);
877
- else await runIntegrate(command.args, env, io);
3284
+ if (command.kind === "add") await runAddCommand(command.args, io);
3285
+ else if (command.kind === "connect") await runConnect(command.args, io, defaultConnectDeps(env));
3286
+ else if (command.kind === "create") await runCreate(command.args, env, io);
3287
+ else if (command.kind === "integrate") await runIntegrate(command.args, env, io);
878
3288
  return 0;
879
3289
  } catch (e) {
880
3290
  if (e instanceof CliError) {