designsource 0.5.0 → 0.6.1

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 +14 -9
  2. package/dist/index.js +799 -149
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -114,16 +114,39 @@ function resolveTargets(root, shadcn) {
114
114
  if (typeof aliases?.components !== "string" || typeof aliases.utils !== "string" || typeof tailwind?.css !== "string") throw new CliError(BAD_COMPONENTS_JSON);
115
115
  const tsconfig = readPaths(root);
116
116
  const uiAlias = typeof aliases.ui === "string" ? aliases.ui : `${aliases.components}/ui`;
117
+ const uiDir = resolveAlias(uiAlias, tsconfig);
118
+ const utilsFile = `${resolveAlias(aliases.utils, tsconfig)}.ts`;
117
119
  return {
118
- uiDir: resolveAlias(uiAlias, tsconfig),
119
- utilsFile: `${resolveAlias(aliases.utils, tsconfig)}.ts`,
120
+ uiDir,
121
+ utilsFile,
120
122
  cssFile: tailwind.css,
121
123
  uiAlias,
122
- utilsAlias: aliases.utils
124
+ utilsAlias: aliases.utils,
125
+ componentsDir: componentsDirOf(aliases.components, tsconfig),
126
+ componentsAlias: aliases.components,
127
+ ...libOf(utilsFile, aliases.utils)
123
128
  };
124
129
  }
130
+ function componentsDirOf(alias, tsconfig) {
131
+ try {
132
+ const file = resolveAlias(`${alias}/x`, tsconfig);
133
+ const dir = posix.dirname(file);
134
+ return dir === "." ? "" : dir;
135
+ } catch {
136
+ try {
137
+ return resolveAlias(alias, tsconfig);
138
+ } catch {
139
+ return null;
140
+ }
141
+ }
142
+ }
143
+ function libOf(utilsFile, utilsAlias) {
144
+ const dir = posix.dirname(utilsFile);
145
+ const slash = utilsAlias.lastIndexOf("/");
146
+ return { libDir: dir === "." ? "" : dir, libAlias: slash > 0 ? utilsAlias.slice(0, slash) : "" };
147
+ }
125
148
  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}`);
149
+ return contents.replace(/(['"])@\/components\/ui\//g, (_, q) => `${q}${t.uiAlias}/`).replace(/(['"])@\/lib\/utils\1/g, (_, q) => `${q}${t.utilsAlias}${q}`).replace(/(['"])@\/components\/(design-system|blocks)\//g, (_, q, dir) => `${q}${t.componentsAlias}/${dir}/`).replace(/(['"])@\/components\/(preview-gallery|custom-surface|sample-surfaces)\1/g, (_, q, file) => `${q}${t.componentsAlias}/${file}${q}`).replace(/(['"])@\/lib\/(mockup-schema|surface-inference)\1/g, (_, q, file) => `${q}${t.libAlias}/${file}${q}`);
127
150
  }
128
151
 
129
152
  // src/add/setup.ts
@@ -236,12 +259,12 @@ function editViteTailwind(text) {
236
259
  function viteHasAlias(masked) {
237
260
  return /['"]@['"]\s*:/.test(masked) || /\bfind\s*:\s*['"]@['"]/.test(masked);
238
261
  }
239
- function ensureNodeUrlImports(text) {
262
+ function ensureNodeUrlImports(text, refusal = NO_VITE_ALIAS) {
240
263
  const masked = maskComments(text);
241
264
  const wanted = ["fileURLToPath", "URL"];
242
265
  const named = /\bimport\s*\{([^}]*)\}\s*from\s*(['"])(?:node:)?url\2/.exec(masked);
243
266
  if (!named) {
244
- if (/\bfrom\s*['"](?:node:)?url['"]/.test(masked)) throw new CliError(NO_VITE_ALIAS);
267
+ if (/\bfrom\s*['"](?:node:)?url['"]/.test(masked)) throw new CliError(refusal);
245
268
  return insertImports(text, [`import { ${wanted.join(", ")} } from 'node:url'`]);
246
269
  }
247
270
  const have = named[1].split(",").map((name) => name.trim());
@@ -261,6 +284,33 @@ function editViteAlias(text, srcDir) {
261
284
  resolve: { alias: { '@': fileURLToPath(new URL('./${srcDir}', import.meta.url)) } },`;
262
285
  return ensureNodeUrlImports(insertAt(text, define.index + define[0].length, alias));
263
286
  }
287
+ var VITE_INPUT_MANUAL = "Could not add design-system.html to vite.config automatically. Add it to build.rollupOptions.input beside index.html so the built site includes /design-system.html.";
288
+ var VITE_INPUTS = `
289
+ build: {
290
+ rollupOptions: {
291
+ input: {
292
+ main: fileURLToPath(new URL('./index.html', import.meta.url)),
293
+ 'design-system': fileURLToPath(new URL('./design-system.html', import.meta.url)),
294
+ },
295
+ },
296
+ },`;
297
+ function editViteInputs(text) {
298
+ const masked = maskComments(text);
299
+ if (masked.includes("design-system.html")) return text;
300
+ const define = /\bdefineConfig\(\s*\{/.exec(masked);
301
+ if (/\bbuild\s*:/.test(masked) || !define) throw new CliError(VITE_INPUT_MANUAL);
302
+ return ensureNodeUrlImports(insertAt(text, define.index + define[0].length, VITE_INPUTS), VITE_INPUT_MANUAL);
303
+ }
304
+ function listViteInputStep(info) {
305
+ const file = firstExisting(info, VITE_CONFIGS);
306
+ if (!file || !existsSync2(join2(info.root, "index.html"))) throw new CliError(VITE_INPUT_MANUAL);
307
+ const text = readText(info, file);
308
+ if (editViteInputs(text) === text) return null;
309
+ return {
310
+ line: "Listing design-system.html in vite.config\u2026",
311
+ run: async () => writeText(info, file, editViteInputs(readText(info, file)))
312
+ };
313
+ }
264
314
  function aliasTarget(baseUrl, srcDir) {
265
315
  const rel = posix2.relative(posix2.normalize(baseUrl), srcDir) || ".";
266
316
  return `${rel === "." ? "." : rel.startsWith("..") ? rel : `./${rel}`}/*`;
@@ -907,16 +957,19 @@ ${TOKEN_LINE}
907
957
  ${API_LINE}
908
958
  --force overwrite files the bundle writes when design-system/ already exists
909
959
  `;
910
- var ADD_USAGE = `designsource add [names\u2026] [--yes] [--all] [--force] [--skip-install] [--token <project token>] [--api <origin>]
960
+ var ADD_USAGE = `designsource add [names\u2026] [--yes] [--all] [--force] [--skip-install] [--no-blocks] [--token <project token>] [--api <origin>]
911
961
 
912
962
  Adds your design system's UI kit to the React app in this folder: the theme in its global stylesheet, the
913
963
  components and the libraries they import. Sets up Tailwind and the shadcn config when the app has none.
914
964
  Run it again to pull updates: it refreshes the theme and every component it added before.
965
+ With every component, a Next.js app (App Router) also gets /design-system, a Vite app /design-system.html:
966
+ your components, blocks and sample pages.
915
967
  names components to add, plus the kit files they import (default: what an earlier run added, else asked)
916
968
  --all every component, no question
917
969
  --yes no questions (also outside a terminal): all components on a first run, edited files kept
918
970
  --force replace component files add did not write, and edited ones
919
971
  --skip-install write the files, then print the install command instead of running it
972
+ --no-blocks the /design-system section without its blocks and their libraries (blocks already there stay)
920
973
  --token the project token (workbench \u2192 Project settings); or DS_SYNC_TOKEN
921
974
  --api API origin (default ${DEFAULT_API_ORIGIN})
922
975
  `;
@@ -983,9 +1036,9 @@ function parseApiOrigin(value, usage) {
983
1036
  if (!parsed || !parsed.host) throw new ArgsError(`Option --api needs a full origin such as http://localhost:3001 (got "${value}")`, usage);
984
1037
  return origin;
985
1038
  }
986
- var ADD_SWITCHES = { yes: "yes", all: "all", force: "force", "skip-install": "skipInstall" };
1039
+ var ADD_SWITCHES = { yes: "yes", all: "all", force: "force", "skip-install": "skipInstall", "no-blocks": "noBlocks" };
987
1040
  function parseAdd(argv, env) {
988
- const args = { components: [], api: DEFAULT_API_ORIGIN, yes: false, all: false, force: false, skipInstall: false };
1041
+ const args = { components: [], api: DEFAULT_API_ORIGIN, yes: false, all: false, force: false, skipInstall: false, noBlocks: false };
989
1042
  if (env.DS_SYNC_TOKEN) args.token = env.DS_SYNC_TOKEN;
990
1043
  for (let i = 0; i < argv.length; i++) {
991
1044
  const arg = argv[i];
@@ -1173,14 +1226,14 @@ function quoteArg(arg) {
1173
1226
  function childEnv(env) {
1174
1227
  return Object.fromEntries(Object.entries(env).filter(([name]) => name.toUpperCase() !== "DS_SYNC_TOKEN"));
1175
1228
  }
1176
- var spawnExec = (cmd, args, { cwd, timeoutMs, input, stdoutOnly }) => new Promise((resolve6) => {
1229
+ var spawnExec = (cmd, args, { cwd, timeoutMs, input, stdoutOnly }) => new Promise((resolve7) => {
1177
1230
  let output = "";
1178
1231
  let child;
1179
1232
  try {
1180
1233
  const shell = process.platform === "win32";
1181
1234
  child = spawn(cmd, shell ? args.map(quoteArg) : args, { cwd, env: childEnv(process.env), stdio: [input === void 0 ? "ignore" : "pipe", "pipe", "pipe"], shell });
1182
1235
  } catch (e) {
1183
- resolve6({ code: 127, output: e instanceof Error ? e.message : String(e) });
1236
+ resolve7({ code: 127, output: e instanceof Error ? e.message : String(e) });
1184
1237
  return;
1185
1238
  }
1186
1239
  let timedOut = false;
@@ -1190,7 +1243,7 @@ var spawnExec = (cmd, args, { cwd, timeoutMs, input, stdoutOnly }) => new Promis
1190
1243
  }, timeoutMs);
1191
1244
  const done = (result) => {
1192
1245
  if (timer) clearTimeout(timer);
1193
- resolve6(timedOut ? { code: result.code === 0 ? 124 : result.code, output: `${result.output.trimEnd()}
1246
+ resolve7(timedOut ? { code: result.code === 0 ? 124 : result.code, output: `${result.output.trimEnd()}
1194
1247
  timed out after ${timeoutMs / 1e3}s` } : result);
1195
1248
  };
1196
1249
  child.stdout?.on("data", (chunk) => {
@@ -1214,11 +1267,15 @@ import { posix as posix4 } from "node:path";
1214
1267
 
1215
1268
  // src/add/stamp.ts
1216
1269
  import { createHash } from "node:crypto";
1217
- var PREFIX = "// designsource: ";
1218
- var STAMP_LINE = /^\/\/ designsource: (\S+) ([0-9a-f]{12})\r?$/;
1270
+ var PREFIX = "designsource: ";
1271
+ var STAMP_LINE = /^(?:\/\/ designsource: (\S+) ([0-9a-f]{12})|\/\* designsource: (\S+) ([0-9a-f]{12}) \*\/|<!-- designsource: (\S+) ([0-9a-f]{12}) -->)\r?$/;
1219
1272
  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)}
1273
+ function stampContents(name, contents, comment = "line") {
1274
+ const stamp2 = `${PREFIX}${name} ${hashOf(contents)}`;
1275
+ if (comment === "html") return `<!-- ${stamp2} -->
1276
+ ${contents}`;
1277
+ return comment === "line" ? `// ${stamp2}
1278
+ ${contents}` : `/* ${stamp2} */
1222
1279
  ${contents}`;
1223
1280
  }
1224
1281
  function readStamp(text) {
@@ -1226,7 +1283,8 @@ function readStamp(text) {
1226
1283
  if (end === -1) return null;
1227
1284
  const match = STAMP_LINE.exec(text.slice(0, end));
1228
1285
  if (!match) return null;
1229
- const [, name, hash] = match;
1286
+ const name = match[1] ?? match[3] ?? match[5];
1287
+ const hash = match[2] ?? match[4] ?? match[6];
1230
1288
  return { name, hash, edited: hashOf(text.slice(end + 1)) !== hash };
1231
1289
  }
1232
1290
 
@@ -1251,7 +1309,7 @@ function stampedFiles(root, t) {
1251
1309
  const path = posix4.join(t.uiDir, entry.name);
1252
1310
  const text = readText2(resolveInside(root, path));
1253
1311
  const stamp2 = text === null ? null : readStamp(text);
1254
- if (stamp2) found.push({ path, name: stamp2.name });
1312
+ if (stamp2 && !stamp2.name.startsWith("section:")) found.push({ path, name: stamp2.name });
1255
1313
  }
1256
1314
  return found.sort((a, b) => a.path < b.path ? -1 : 1);
1257
1315
  }
@@ -1265,6 +1323,13 @@ function assertKitUtils(root, info, t) {
1265
1323
  if (text === null || EXPORTS_CN.test(text)) return;
1266
1324
  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
1325
  }
1326
+ function existingFileStatus(abs) {
1327
+ if (!existsSync5(abs)) return "none";
1328
+ const text = readText2(abs);
1329
+ const stamp2 = text === null ? null : readStamp(text);
1330
+ if (!stamp2) return "foreign";
1331
+ return stamp2.edited ? "edited" : "stamped";
1332
+ }
1268
1333
  function planFiles(root, t, components, manifest) {
1269
1334
  const byName = new Map(manifest.components.map((c) => [c.name, c]));
1270
1335
  const plan = { write: [], replaceForeign: [], edited: [], previouslyAdded: [], gone: [] };
@@ -1274,36 +1339,453 @@ function planFiles(root, t, components, manifest) {
1274
1339
  const path = t.uiDir ? `${t.uiDir}/${component.file}` : component.file;
1275
1340
  const abs = resolveInside(root, path);
1276
1341
  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);
1342
+ const status = existingFileStatus(abs);
1343
+ if (status === "foreign") plan.replaceForeign.push(path);
1344
+ else if (status === "edited") plan.edited.push(path);
1282
1345
  }
1283
1346
  const utilsAbs = resolveInside(root, t.utilsFile);
1284
1347
  if (!existsSync5(utilsAbs)) {
1285
1348
  plan.write.push({ path: t.utilsFile, contents: stampContents("utils", rewriteForApp(manifest.utils, t)), component: "utils" });
1286
1349
  }
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);
1350
+ const stamped2 = stampedFiles(root, t);
1351
+ plan.previouslyAdded = stamped2.map((f) => f.name).sort();
1352
+ plan.gone = stamped2.filter((f) => f.name !== "utils" && !byName.has(f.name)).map((f) => f.path);
1290
1353
  return plan;
1291
1354
  }
1292
1355
 
1293
- // src/add/run-add.ts
1294
- import { existsSync as existsSync7, readFileSync as readFileSync7, statSync as statSync2 } from "node:fs";
1356
+ // src/add/section.ts
1357
+ import { existsSync as existsSync6, readdirSync as readdirSync2, readFileSync as readFileSync6 } from "node:fs";
1295
1358
  import { join as join4 } from "node:path";
1359
+ var SECTION_NEEDS_FULL_KIT = "The /design-system section comes with the full kit: run designsource add --all.";
1360
+ var SECTION_NEEDS_FULL_KIT_FOR_AGENT = 'The /design-system section comes with the full kit: call add_ui_kit again with every component in "components" (list_components names them).';
1361
+ var NO_COMPONENTS_DIR = (alias) => `tsconfig.json does not resolve components.json's components alias "${alias}"; the /design-system section goes in that folder, so add a paths entry for it.`;
1362
+ var NO_LIB_ALIAS = (alias) => `components.json's utils alias "${alias}" has no folder; the /design-system section needs one, such as "@/lib/utils".`;
1363
+ var NO_APP_ROUTER = "This Next.js app uses the Pages Router; the /design-system section needs the App Router, so it was skipped.";
1364
+ var OWN_DESIGN_SYSTEM_ROUTE = (path) => `Skipped the /design-system section: this app already has its own /design-system route (${path}).`;
1365
+ function shownBlockGroups(groups, blocks, keptBlockIds = []) {
1366
+ if (blocks === "write") return groups;
1367
+ if (blocks === "skip") return [];
1368
+ const kept = new Set(keptBlockIds);
1369
+ return groups.map((g) => ({ ...g, blocks: g.blocks.filter((b) => kept.has(b.id)) })).filter((g) => g.blocks.length > 0);
1370
+ }
1371
+ function cliSectionConfig(config) {
1372
+ return `import type { SectionConfig } from './section-nav'
1373
+
1374
+ export const SECTION_CONFIG: SectionConfig = ${JSON.stringify(config, null, 2)}
1375
+ `;
1376
+ }
1377
+ var join22 = (dir, rest) => dir ? `${dir}/${rest}` : rest;
1378
+ var COMPONENT_FILES = /* @__PURE__ */ new Set(["preview-gallery.tsx", "custom-surface.tsx", "sample-surfaces.tsx"]);
1379
+ var LIB_FILES = /* @__PURE__ */ new Set(["surface-inference.ts", "mockup-schema.ts"]);
1380
+ var pointAtStub = (contents, alias) => contents.replace(/(['"])([^'"]*)\/blocks\/block-view\1/g, (whole, q, prefix) => prefix === alias ? `${q}./block-view${q}` : whole);
1381
+ var withoutExtension = (file) => file.replace(/\.(tsx?|json|css)$/, "");
1382
+ function placeManifestFile(key, componentsDir, t) {
1383
+ if (key.startsWith("section/")) {
1384
+ const file = key.slice("section/".length);
1385
+ return { path: join22(componentsDir, `design-system/${file}`), name: `section:${withoutExtension(file)}` };
1386
+ }
1387
+ if (key.startsWith("blocks/")) {
1388
+ const rest = key.slice("blocks/".length);
1389
+ return { path: join22(componentsDir, `blocks/${rest}`), name: `section:block:${withoutExtension(rest)}` };
1390
+ }
1391
+ if (COMPONENT_FILES.has(key)) return { path: join22(componentsDir, key), name: `section:${withoutExtension(key)}` };
1392
+ if (LIB_FILES.has(key)) return { path: join22(t.libDir, key), name: `section:${withoutExtension(key)}` };
1393
+ throw new CliError(UPDATE_MESSAGE);
1394
+ }
1395
+ function stamped(path, name, contents) {
1396
+ if (path.endsWith(".json")) return { path, name, contents };
1397
+ const comment = path.endsWith(".css") ? "block" : path.endsWith(".html") ? "html" : "line";
1398
+ return { path, name, contents: stampContents(name, contents, comment) };
1399
+ }
1400
+ function planSectionFiles(input) {
1401
+ const { targets: t, manifest, blocks } = input;
1402
+ const section = manifest.section;
1403
+ if (!section) throw new CliError(UPDATE_MESSAGE);
1404
+ const vite = input.framework === "vite";
1405
+ if (!vite && input.appDir === null) throw new CliError(NO_APP_ROUTER);
1406
+ const componentsDir = t.componentsDir;
1407
+ if (componentsDir === null) throw new CliError(NO_COMPONENTS_DIR(t.componentsAlias));
1408
+ if (!t.libAlias) throw new CliError(NO_LIB_ALIAS(t.utilsAlias));
1409
+ const ds = (file) => join22(componentsDir, `design-system/${file}`);
1410
+ const files = [];
1411
+ for (const f of section.files) {
1412
+ if (f.block && blocks !== "write") continue;
1413
+ const { path, name } = placeManifestFile(f.key, componentsDir, t);
1414
+ let contents = rewriteForApp(f.contents, t);
1415
+ if (f.key === "section/section-views.tsx" && blocks === "skip") contents = pointAtStub(contents, t.componentsAlias);
1416
+ files.push(stamped(path, name, contents));
1417
+ }
1418
+ if (blocks === "skip") files.push(stamped(ds("block-view.tsx"), "section:block-view", NO_BLOCKS_VIEW));
1419
+ const hasMockup = section.mockupSpec !== null;
1420
+ const darkMarker = vite ? { kind: "class", name: "dark" } : input.darkMarker;
1421
+ const config = {
1422
+ name: manifest.name,
1423
+ hasMockup,
1424
+ hasBlocks: blocks !== "skip",
1425
+ darkMarker,
1426
+ homeHref: "/",
1427
+ blockGroups: shownBlockGroups(section.blockGroups, blocks, input.keptBlockIds)
1428
+ };
1429
+ files.push(stamped(ds("section-config.ts"), "section:config", cliSectionConfig(config)));
1430
+ if (hasMockup) files.push(stamped(ds("page.json"), "section:page", `${JSON.stringify(section.mockupSpec, null, 2)}
1431
+ `));
1432
+ files.push(stamped(ds("section-routes.ts"), "section:routes", vite ? viteSectionRoutes(hasMockup, t) : sectionRoutes(hasMockup, t)));
1433
+ if (vite) {
1434
+ const entry = (file) => join22(input.srcDir, `design-system/${file}`);
1435
+ files.push(stamped("design-system.html", "section:page-html", vitePage(manifest.name, entry("main.tsx"))));
1436
+ files.push(stamped(entry("main.tsx"), "section:entry", viteEntry(t)));
1437
+ files.push(stamped(entry("section.css"), "section:stylesheet", viteStylesheet(manifest, section.themeCss)));
1438
+ return files;
1439
+ }
1440
+ files.push(stamped(ds("section-theme.css"), "section:theme", section.themeCss));
1441
+ files.push(stamped(ds("section-page.tsx"), "section:section-page", NEXT_SECTION_PAGE));
1442
+ files.push(stamped(`${input.appDir}/design-system/layout.tsx`, "section:route:layout", nextLayout(t)));
1443
+ files.push(stamped(`${input.appDir}/design-system/[[...path]]/page.tsx`, "section:route:page", nextPage(t)));
1444
+ return files;
1445
+ }
1446
+ var NO_BLOCKS_VIEW = `// This project was added without blocks (designsource add --no-blocks): the section has no Blocks views.
1447
+ export function BlockView({ id }: { id: string }) {
1448
+ return <p className="p-6 text-sm text-muted-foreground">No block named \u201C{id}\u201D.</p>
1449
+ }
1450
+ BlockView.displayName = 'BlockView'
1451
+ `;
1452
+ function mockupModule(hasMockup, t) {
1453
+ return hasMockup ? `import { mockupSpecShapeSchema, type StoredMockupSpec } from '${t.libAlias}/mockup-schema'
1454
+ import page from './page.json'
1455
+
1456
+ // The Custom page is page.json rendered by the design system's page renderer. designsource writes it on every run.
1457
+ export const MOCKUP_SPEC: StoredMockupSpec | null = mockupSpecShapeSchema.parse(page)
1458
+ ` : `import type { StoredMockupSpec } from '${t.libAlias}/mockup-schema'
1459
+
1460
+ /** This project had no generated page: no Custom view. */
1461
+ export const MOCKUP_SPEC: StoredMockupSpec | null = null
1462
+ `;
1463
+ }
1464
+ var ROUTES_IMPORTS = `import { SECTION_CONFIG } from './section-config'
1465
+ import { parseSectionPath, type SectionFeatures, type SectionRoute, sectionPath } from './section-nav'
1466
+ `;
1467
+ var FEATURES = `export const SECTION_FEATURES: SectionFeatures = {
1468
+ hasMockup: SECTION_CONFIG.hasMockup,
1469
+ hasBlocks: SECTION_CONFIG.hasBlocks,
1470
+ blockIds: SECTION_CONFIG.blockGroups.flatMap((group) => group.blocks.map((block) => block.id)),
1471
+ }
1472
+ `;
1473
+ function sectionRoutes(hasMockup, t) {
1474
+ return `${ROUTES_IMPORTS}${mockupModule(hasMockup, t)}
1475
+ /** Where the section lives. */
1476
+ export const SECTION_BASE = '/design-system'
1477
+
1478
+ ${FEATURES}
1479
+ /** A \`sectionPath()\` result as an href. */
1480
+ export const sectionHref = (path: string) => \`\${SECTION_BASE}\${path}\`
1481
+
1482
+ export const hrefFor = (route: SectionRoute) => sectionHref(sectionPath(route))
1483
+
1484
+ /** The route a pathname under /design-system names. */
1485
+ export const routeFor = (pathname: string) => parseSectionPath(pathname.slice(SECTION_BASE.length), SECTION_FEATURES)
1486
+ `;
1487
+ }
1488
+ function viteSectionRoutes(hasMockup, t) {
1489
+ return `${ROUTES_IMPORTS}${mockupModule(hasMockup, t)}
1490
+ ${FEATURES}
1491
+ /** A \`sectionPath()\` result as an href: the page's hash. */
1492
+ export const sectionHref = (path: string) => \`#\${path}\`
1493
+
1494
+ export const hrefFor = (route: SectionRoute) => sectionHref(sectionPath(route))
1495
+
1496
+ /** The route a \`location.hash\` names. */
1497
+ export const routeFor = (hash: string) => parseSectionPath(hash.replace(/^#/, ''), SECTION_FEATURES)
1498
+ `;
1499
+ }
1500
+ var escapeHtml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1501
+ function vitePage(name, entry) {
1502
+ return `<!doctype html>
1503
+ <html lang="en">
1504
+ <head>
1505
+ <meta charset="UTF-8" />
1506
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
1507
+ <title>${escapeHtml(`${name} \xB7 Design system`)}</title>
1508
+ </head>
1509
+ <body>
1510
+ <div id="ds-root"></div>
1511
+ <script type="module" src="/${entry}"></script>
1512
+ </body>
1513
+ </html>
1514
+ `;
1515
+ }
1516
+ function viteStylesheet(manifest, themeCss) {
1517
+ const fonts = manifest.theme.fontImports.length > 0 ? `${manifest.theme.fontImports.join("\n")}
1518
+ ` : "";
1519
+ return `${fonts}@import "tailwindcss";
1520
+ @import "tw-animate-css";
1521
+ @import "shadcn/tailwind.css";
1522
+
1523
+ @custom-variant dark (&:is(.dark *));
1524
+
1525
+ ${manifest.theme.css.trim()}
1526
+
1527
+ ${themeCss.trim()}
1528
+ `;
1529
+ }
1530
+ function viteEntry(t) {
1531
+ const c = t.componentsAlias;
1532
+ return `import { StrictMode, useEffect, useState } from 'react'
1533
+ import { createRoot } from 'react-dom/client'
1534
+ import { SECTION_CONFIG } from '${c}/design-system/section-config'
1535
+ import { SectionHeader } from '${c}/design-system/section-header'
1536
+ import { hrefFor, MOCKUP_SPEC, routeFor, SECTION_FEATURES } from '${c}/design-system/section-routes'
1537
+ import { SectionShell } from '${c}/design-system/section-shell'
1538
+ import { SectionView } from '${c}/design-system/section-views'
1539
+ import './section.css'
1540
+
1541
+ /** \`location.hash\`, kept current: Back and Forward change it too. */
1542
+ function useHash(): string {
1543
+ const [hash, setHash] = useState(() => window.location.hash)
1544
+ useEffect(() => {
1545
+ const onChange = () => setHash(window.location.hash)
1546
+ window.addEventListener('hashchange', onChange)
1547
+ return () => window.removeEventListener('hashchange', onChange)
1548
+ }, [])
1549
+ return hash
1550
+ }
1551
+
1552
+ // The design system, written by designsource: its own page, on its own stylesheet, with the project's theme scoped to
1553
+ // the shell and its own light and dark switch. The view is the hash: #/components, #/blocks/login-01.
1554
+ function DesignSystem() {
1555
+ const hash = useHash()
1556
+ const route = routeFor(hash)
1557
+ return (
1558
+ <SectionShell
1559
+ scoped
1560
+ cover={false}
1561
+ darkMarker={SECTION_CONFIG.darkMarker}
1562
+ header={({ dark, toggleDark }) => (
1563
+ <SectionHeader
1564
+ name={SECTION_CONFIG.name}
1565
+ route={route.view === 'missing' ? { view: 'components', blockId: null } : route}
1566
+ features={SECTION_FEATURES}
1567
+ blockGroups={SECTION_CONFIG.blockGroups}
1568
+ homeHref={SECTION_CONFIG.homeHref}
1569
+ hrefFor={hrefFor}
1570
+ dark={dark}
1571
+ onToggleDark={toggleDark}
1572
+ />
1573
+ )}
1574
+ >
1575
+ <SectionView route={route} mockupSpec={MOCKUP_SPEC} blockGroups={SECTION_CONFIG.blockGroups} hrefFor={hrefFor} />
1576
+ </SectionShell>
1577
+ )
1578
+ }
1579
+ DesignSystem.displayName = 'DesignSystem'
1580
+
1581
+ createRoot(document.getElementById('ds-root')!).render(
1582
+ <StrictMode>
1583
+ <DesignSystem />
1584
+ </StrictMode>,
1585
+ )
1586
+ `;
1587
+ }
1588
+ var NEXT_SECTION_PAGE = `'use client'
1589
+
1590
+ import Link from 'next/link'
1591
+ import { usePathname } from 'next/navigation'
1592
+ import { SECTION_CONFIG } from './section-config'
1593
+ import { hrefFor, MOCKUP_SPEC, routeFor } from './section-routes'
1594
+ import { SectionView } from './section-views'
1595
+
1596
+ /** What /design-system/... shows: the view the path names. A client component because the views take functions. */
1597
+ export function SectionPage() {
1598
+ return (
1599
+ <SectionView
1600
+ route={routeFor(usePathname())}
1601
+ mockupSpec={MOCKUP_SPEC}
1602
+ blockGroups={SECTION_CONFIG.blockGroups}
1603
+ hrefFor={hrefFor}
1604
+ LinkComponent={Link}
1605
+ />
1606
+ )
1607
+ }
1608
+ SectionPage.displayName = 'SectionPage'
1609
+ `;
1610
+ function nextLayout(t) {
1611
+ const c = t.componentsAlias;
1612
+ return `'use client'
1613
+
1614
+ import Link from 'next/link'
1615
+ import { usePathname } from 'next/navigation'
1616
+ import { Suspense, type ReactNode } from 'react'
1617
+ import { SECTION_CONFIG } from '${c}/design-system/section-config'
1618
+ import { SectionHeader } from '${c}/design-system/section-header'
1619
+ import { hrefFor, routeFor, SECTION_FEATURES } from '${c}/design-system/section-routes'
1620
+ import { SectionShell } from '${c}/design-system/section-shell'
1621
+ import '${c}/design-system/section-theme.css'
1622
+
1623
+ // The design system, written by designsource. It renders inside the app's root layout, so the shell covers the whole
1624
+ // window above it, with the project's own theme scoped to the shell and its own light and dark switch.
1625
+ // The Suspense boundary is for Next's Cache Components (the default of a new app): \`usePathname\` in a layout over a
1626
+ // dynamic segment is not known while the fallback shell prerenders, and a client render outside a boundary fails the build.
1627
+ export default function DesignSystemLayout({ children }: { children: ReactNode }) {
1628
+ return (
1629
+ <Suspense fallback={null}>
1630
+ <SectionLayout>{children}</SectionLayout>
1631
+ </Suspense>
1632
+ )
1633
+ }
1634
+ DesignSystemLayout.displayName = 'DesignSystemLayout'
1635
+
1636
+ function SectionLayout({ children }: { children: ReactNode }) {
1637
+ const route = routeFor(usePathname())
1638
+ return (
1639
+ <SectionShell
1640
+ scoped
1641
+ cover
1642
+ darkMarker={SECTION_CONFIG.darkMarker}
1643
+ header={({ dark, toggleDark }) => (
1644
+ <SectionHeader
1645
+ name={SECTION_CONFIG.name}
1646
+ route={route.view === 'missing' ? { view: 'components', blockId: null } : route}
1647
+ features={SECTION_FEATURES}
1648
+ blockGroups={SECTION_CONFIG.blockGroups}
1649
+ homeHref={SECTION_CONFIG.homeHref}
1650
+ hrefFor={hrefFor}
1651
+ LinkComponent={Link}
1652
+ dark={dark}
1653
+ onToggleDark={toggleDark}
1654
+ />
1655
+ )}
1656
+ >
1657
+ {children}
1658
+ </SectionShell>
1659
+ )
1660
+ }
1661
+ SectionLayout.displayName = 'SectionLayout'
1662
+ `;
1663
+ }
1664
+ function nextPage(t) {
1665
+ const c = t.componentsAlias;
1666
+ return `import { componentSlug, GALLERY_COMPONENTS } from '${c}/design-system/gallery-groups'
1667
+ import { NAV_ITEMS } from '${c}/design-system/section-nav'
1668
+ import { SectionPage } from '${c}/design-system/section-page'
1669
+ import { SECTION_FEATURES } from '${c}/design-system/section-routes'
1670
+
1671
+ export const metadata = { title: 'Design system' }
1672
+
1673
+ // Every route of the section is prerendered; anything else renders the section's own "not found" view.
1674
+ export function generateStaticParams() {
1675
+ const views: string[] = NAV_ITEMS(SECTION_FEATURES).map((item) => item.view)
1676
+ const routes = [
1677
+ '',
1678
+ ...views,
1679
+ ...GALLERY_COMPONENTS.map((title) => \`components/\${componentSlug(title)}\`),
1680
+ ...SECTION_FEATURES.blockIds.map((id) => \`blocks/\${id}\`),
1681
+ ]
1682
+ return routes.map((route) => ({ path: route === '' ? [] : route.split('/') }))
1683
+ }
1684
+
1685
+ export default function DesignSystemPage() {
1686
+ return <SectionPage />
1687
+ }
1688
+ `;
1689
+ }
1690
+ function nextAppDir(root) {
1691
+ for (const dir of ["app", "src/app"]) {
1692
+ if (["tsx", "jsx", "ts", "js"].some((ext) => existsSync6(join4(root, dir, `layout.${ext}`)))) return dir;
1693
+ }
1694
+ return null;
1695
+ }
1696
+ function entriesOf(abs) {
1697
+ try {
1698
+ return readdirSync2(abs, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : 1);
1699
+ } catch {
1700
+ return [];
1701
+ }
1702
+ }
1703
+ function firstForeignFile(root, rel) {
1704
+ for (const entry of entriesOf(join4(root, rel))) {
1705
+ const child = `${rel}/${entry.name}`;
1706
+ if (entry.isDirectory()) {
1707
+ const found = firstForeignFile(root, child);
1708
+ if (found) return found;
1709
+ continue;
1710
+ }
1711
+ let text = null;
1712
+ try {
1713
+ text = readFileSync6(join4(root, child), "utf8");
1714
+ } catch {
1715
+ }
1716
+ if (!(text !== null && readStamp(text)?.name.startsWith("section:"))) return child;
1717
+ }
1718
+ return null;
1719
+ }
1720
+ function groupedDesignSystem(root, rel) {
1721
+ for (const entry of entriesOf(join4(root, rel))) {
1722
+ if (!entry.isDirectory() || !/^\(.+\)$/.test(entry.name)) continue;
1723
+ const group = `${rel}/${entry.name}`;
1724
+ if (existsSync6(join4(root, group, "design-system"))) return `${group}/design-system`;
1725
+ const nested = groupedDesignSystem(root, group);
1726
+ if (nested) return nested;
1727
+ }
1728
+ return null;
1729
+ }
1730
+ function ownDesignSystemRoute(root, appDir) {
1731
+ return firstForeignFile(root, `${appDir}/design-system`) ?? groupedDesignSystem(root, appDir);
1732
+ }
1733
+ function stampNames(abs, recursive) {
1734
+ let entries;
1735
+ try {
1736
+ entries = readdirSync2(abs, { withFileTypes: true });
1737
+ } catch {
1738
+ return [];
1739
+ }
1740
+ const names = [];
1741
+ for (const entry of entries) {
1742
+ const child = join4(abs, entry.name);
1743
+ if (entry.isDirectory()) {
1744
+ if (recursive) names.push(...stampNames(child, true));
1745
+ continue;
1746
+ }
1747
+ if (!entry.isFile()) continue;
1748
+ let text;
1749
+ try {
1750
+ text = readFileSync6(child, "utf8");
1751
+ } catch {
1752
+ continue;
1753
+ }
1754
+ const stamp2 = readStamp(text);
1755
+ if (stamp2) names.push(stamp2.name);
1756
+ }
1757
+ return names;
1758
+ }
1759
+ function blockIdOfStamp(name) {
1760
+ const rest = name.startsWith("section:block:") ? name.slice("section:block:".length) : null;
1761
+ if (rest === null) return null;
1762
+ const chart = /^charts\/group-([a-z0-9-]+)$/.exec(rest);
1763
+ if (chart) return `charts-${chart[1]}`;
1764
+ const page = /^([a-z0-9-]+)\/page$/.exec(rest);
1765
+ return page ? page[1] : null;
1766
+ }
1767
+ function sectionPresent(root, t) {
1768
+ if (t.componentsDir === null) return { present: false, blocksOnDisk: false, blockIds: [] };
1769
+ const present = stampNames(resolveInside(root, join22(t.componentsDir, "design-system")), false).some((n) => n.startsWith("section:"));
1770
+ const blockStamps = stampNames(resolveInside(root, join22(t.componentsDir, "blocks")), true).filter((n) => n.startsWith("section:block:"));
1771
+ const blockIds = [...new Set(blockStamps.map(blockIdOfStamp).filter((id) => id !== null))];
1772
+ return { present, blocksOnDisk: blockStamps.length > 0, blockIds };
1773
+ }
1774
+
1775
+ // src/add/run-add.ts
1776
+ import { existsSync as existsSync8, readFileSync as readFileSync8, statSync as statSync2 } from "node:fs";
1777
+ import { join as join5 } from "node:path";
1296
1778
 
1297
1779
  // src/write.ts
1298
- import { existsSync as existsSync6, mkdirSync, readFileSync as readFileSync6, readdirSync as readdirSync2, rmSync, statSync, writeFileSync as writeFileSync2 } from "node:fs";
1780
+ import { existsSync as existsSync7, mkdirSync, readFileSync as readFileSync7, readdirSync as readdirSync3, rmSync, statSync, writeFileSync as writeFileSync2 } from "node:fs";
1299
1781
  import { dirname, relative, resolve as resolve2 } from "node:path";
1300
1782
  function planTarget(cwd, folder, framework, force) {
1301
1783
  const root = resolve2(cwd, folder);
1302
- if (!existsSync6(root)) return { root, created: true };
1784
+ if (!existsSync7(root)) return { root, created: true };
1303
1785
  if (!statSync(root).isDirectory()) throw new CliError(`${folder} exists and is not a folder.`);
1304
1786
  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) {
1787
+ if (readdirSync3(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.`);
1788
+ } else if (existsSync7(resolve2(root, "design-system")) && !force) {
1307
1789
  throw new CliError(`${folder}/design-system/ already exists. Remove it, or pass --force to overwrite the files the bundle writes.`);
1308
1790
  }
1309
1791
  return { root, created: false };
@@ -1311,7 +1793,7 @@ function planTarget(cwd, folder, framework, force) {
1311
1793
  function writeFiles(root, files, opts, writeFile = writeFileSync2) {
1312
1794
  const targets = files.map((f) => ({ file: f, abs: resolveInside(root, f.path) }));
1313
1795
  if (!opts.force) {
1314
- const clash = targets.find((t) => existsSync6(t.abs));
1796
+ const clash = targets.find((t) => existsSync7(t.abs));
1315
1797
  if (clash) throw new CliError(`${clash.file.path} already exists. Pass --force to overwrite the files the starter writes.`);
1316
1798
  }
1317
1799
  const written = [];
@@ -1321,7 +1803,7 @@ function writeFiles(root, files, opts, writeFile = writeFileSync2) {
1321
1803
  try {
1322
1804
  for (const { file, abs } of targets) {
1323
1805
  failingPath = file.path;
1324
- if (!previous.has(file.path)) previous.set(file.path, existsSync6(abs) ? readFileSync6(abs) : void 0);
1806
+ if (!previous.has(file.path)) previous.set(file.path, existsSync7(abs) ? readFileSync7(abs) : void 0);
1325
1807
  madeDirs.push(...missingDirs(root, dirname(abs)));
1326
1808
  mkdirSync(dirname(abs), { recursive: true });
1327
1809
  writeFile(abs, file.path === "package.json" && opts.packageManager ? withPackageManager(file.contents, opts.packageManager) : file.contents);
@@ -1338,7 +1820,7 @@ function writeFiles(root, files, opts, writeFile = writeFileSync2) {
1338
1820
  for (const [p, before] of previous) {
1339
1821
  const abs = resolveInside(root, p);
1340
1822
  if (before === void 0) {
1341
- if (existsSync6(abs) && statSync(abs).isFile()) {
1823
+ if (existsSync7(abs) && statSync(abs).isFile()) {
1342
1824
  rmSync(abs, { force: true });
1343
1825
  removed++;
1344
1826
  }
@@ -1355,7 +1837,7 @@ function writeFiles(root, files, opts, writeFile = writeFileSync2) {
1355
1837
  function missingDirs(root, dir) {
1356
1838
  const missing = [];
1357
1839
  let d = dir;
1358
- while (relative(root, d) !== "" && !relative(root, d).startsWith("..") && !existsSync6(d)) {
1840
+ while (relative(root, d) !== "" && !relative(root, d).startsWith("..") && !existsSync7(d)) {
1359
1841
  missing.unshift(d);
1360
1842
  d = dirname(d);
1361
1843
  }
@@ -1367,11 +1849,84 @@ function withPackageManager(contents, packageManager) {
1367
1849
  `;
1368
1850
  }
1369
1851
 
1852
+ // src/add/dark-marker.ts
1853
+ var UNKNOWN_DARK = (sel) => `This app marks dark mode as ${sel}; inside /design-system a few dark-only details follow its own switch.`;
1854
+ var DEFAULT_MARKER = { kind: "class", name: "dark" };
1855
+ var VARIANT = /@custom-variant\s+dark\s*([({])/;
1856
+ var CLASS = /\.(-?[_a-zA-Z][\w-]*)/g;
1857
+ var ATTR = /\[\s*([\w-]+)\s*(=?)\s*(?:"([^"]*)"|'([^']*)'|([\w-]*))\s*\]/g;
1858
+ function balanced(css, open) {
1859
+ let depth = 0;
1860
+ for (let i = open; i < css.length; i++) {
1861
+ if (css[i] === "(") depth++;
1862
+ else if (css[i] === ")" && --depth === 0) return css.slice(open + 1, i);
1863
+ }
1864
+ return null;
1865
+ }
1866
+ function variantSelector(css) {
1867
+ const match = VARIANT.exec(css);
1868
+ if (!match) return null;
1869
+ const open = match.index + match[0].length - 1;
1870
+ if (match[1] === "(") return (balanced(css, open) ?? css.slice(open + 1)).trim();
1871
+ const inner = css.indexOf("{", open + 1);
1872
+ return (inner === -1 ? css.slice(open + 1) : css.slice(open + 1, inner)).trim();
1873
+ }
1874
+ function readDarkMarker(css) {
1875
+ const selector = variantSelector(css.replace(/\/\*[\s\S]*?\*\//g, ""));
1876
+ if (selector === null) return { marker: DEFAULT_MARKER, known: true, selector };
1877
+ const classes = new Set([...selector.replace(/"[^"]*"|'[^']*'/g, "").matchAll(CLASS)].map((m) => m[1]));
1878
+ const attrs = [...selector.matchAll(ATTR)];
1879
+ const attrKeys = new Set(attrs.map((m) => `${m[1]}=${m[3] ?? m[4] ?? m[5]}`));
1880
+ if (classes.size === 1 && attrs.length === 0) return { marker: { kind: "class", name: [...classes][0] }, known: true, selector };
1881
+ const [first] = attrs;
1882
+ if (classes.size === 0 && first && attrKeys.size === 1 && first[2] === "=") {
1883
+ const value = first[3] ?? first[4] ?? first[5] ?? "";
1884
+ if (value) return { marker: { kind: "attr", name: first[1], value }, known: true, selector };
1885
+ }
1886
+ return { marker: DEFAULT_MARKER, known: false, selector };
1887
+ }
1888
+
1889
+ // src/http.ts
1890
+ var FETCH_TIMEOUT_MS = 3e4;
1891
+ var ApiError = class extends CliError {
1892
+ constructor(message, status) {
1893
+ super(message);
1894
+ Object.defineProperty(this, "status", { value: status, enumerable: false });
1895
+ }
1896
+ };
1897
+ async function getJson(opts, fetchImpl = fetch) {
1898
+ const url = new URL(opts.path, `${opts.api}/`);
1899
+ for (const [k, v] of Object.entries(opts.query ?? {})) url.searchParams.set(k, v);
1900
+ const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
1901
+ let res;
1902
+ try {
1903
+ res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" }, signal });
1904
+ } catch {
1905
+ throw new ApiError(UNREACHABLE(opts.api), null);
1906
+ }
1907
+ let body = null;
1908
+ try {
1909
+ body = await res.json();
1910
+ } catch {
1911
+ if (signal.aborted) throw new ApiError(UNREACHABLE(opts.api), null);
1912
+ }
1913
+ if (!res.ok) throw new ApiError(messageForResponse(res.status, body, opts.api), res.status);
1914
+ return body;
1915
+ }
1916
+
1370
1917
  // src/add/kit-manifest.ts
1371
1918
  var malformed = () => new CliError("Unexpected response from the API \u2014 not a kit manifest.");
1372
1919
  var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1373
1920
  var isStrings = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
1374
1921
  var isStringMap = (v) => isRecord(v) && Object.values(v).every((s) => typeof s === "string");
1922
+ var isSectionFile = (f) => isRecord(f) && typeof f.key === "string" && typeof f.contents === "string" && isStrings(f.kitImports) && isStrings(f.packages) && typeof f.block === "boolean";
1923
+ var isBlockGroup = (g) => isRecord(g) && typeof g.family === "string" && typeof g.label === "string" && Array.isArray(g.blocks) && g.blocks.every((b) => isRecord(b) && typeof b.id === "string" && typeof b.title === "string");
1924
+ function validateSection(s) {
1925
+ if (!isRecord(s) || !Array.isArray(s.files) || !s.files.every(isSectionFile)) throw malformed();
1926
+ if (typeof s.themeCss !== "string" || !Array.isArray(s.blockGroups) || !s.blockGroups.every(isBlockGroup)) throw malformed();
1927
+ if (!isStringMap(s.packages) || !isStringMap(s.blockPackages)) throw malformed();
1928
+ return { files: s.files, themeCss: s.themeCss, blockGroups: s.blockGroups, packages: s.packages, blockPackages: s.blockPackages, mockupSpec: s.mockupSpec ?? null };
1929
+ }
1375
1930
  function validateKitManifest(json) {
1376
1931
  if (!isRecord(json)) throw malformed();
1377
1932
  if (typeof json.version !== "number") throw malformed();
@@ -1387,6 +1942,7 @@ function validateKitManifest(json) {
1387
1942
  }
1388
1943
  if (!isStrings(json.utilsPackages)) throw malformed();
1389
1944
  if (!isStringMap(json.packages) || !isStringMap(json.devPackages)) throw malformed();
1945
+ const section = json.section === void 0 ? void 0 : validateSection(json.section);
1390
1946
  return {
1391
1947
  version: 1,
1392
1948
  kind: "kit",
@@ -1396,22 +1952,14 @@ function validateKitManifest(json) {
1396
1952
  utils: json.utils,
1397
1953
  utilsPackages: json.utilsPackages,
1398
1954
  packages: json.packages,
1399
- devPackages: json.devPackages
1955
+ devPackages: json.devPackages,
1956
+ ...section ? { section } : {}
1400
1957
  };
1401
1958
  }
1402
1959
 
1403
1960
  // src/add/fetch-kit.ts
1404
1961
  async function fetchKit(opts, fetchImpl = fetch) {
1405
- const url = new URL("/api/kit", `${opts.api}/`);
1406
- let res;
1407
- try {
1408
- res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" } });
1409
- } catch {
1410
- throw new CliError(UNREACHABLE(opts.api));
1411
- }
1412
- const body = await res.json().catch(() => null);
1413
- if (!res.ok) throw new CliError(messageForResponse(res.status, body, opts.api));
1414
- return validateKitManifest(body);
1962
+ return validateKitManifest(await getJson({ api: opts.api, token: opts.token, path: "/api/kit" }, fetchImpl));
1415
1963
  }
1416
1964
 
1417
1965
  // src/add/plan-packages.ts
@@ -1433,7 +1981,7 @@ function conflictBetween(pkg, have, need) {
1433
1981
  return { pkg, have, need };
1434
1982
  }
1435
1983
  var reasonFor = (c) => `this app uses ${c.pkg} ${majorOf(c.have)}, the kit needs ${majorOf(c.need)}`;
1436
- function planPackages(components, manifest, appDeps) {
1984
+ function planPackages(components, manifest, appDeps, extra = {}) {
1437
1985
  const byName = new Map(manifest.components.map((c) => [c.name, c]));
1438
1986
  const conflictOf = /* @__PURE__ */ new Map();
1439
1987
  for (const name of componentClosure(components, manifest)) {
@@ -1462,9 +2010,18 @@ function planPackages(components, manifest, appDeps) {
1462
2010
  const need = manifest.packages[pkg];
1463
2011
  if (need !== void 0 && appDeps[pkg] === void 0) install[pkg] = need;
1464
2012
  }
1465
- const reactIs = manifest.packages["react-is"];
2013
+ const extraConflicts = [];
2014
+ for (const [pkg, need] of Object.entries(extra)) {
2015
+ const have = appDeps[pkg];
2016
+ const conflict = have === void 0 ? null : conflictBetween(pkg, have, need);
2017
+ if (conflict) extraConflicts.push(conflict);
2018
+ }
2019
+ if (extraConflicts.length === 0) {
2020
+ for (const [pkg, need] of Object.entries(extra)) if (appDeps[pkg] === void 0 && !(pkg in install)) install[pkg] = need;
2021
+ }
2022
+ const reactIs = manifest.packages["react-is"] ?? extra["react-is"];
1466
2023
  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 };
2024
+ return { install, conflicts: [...conflictOf.values()], skipped, components: kept, extraConflicts };
1468
2025
  }
1469
2026
 
1470
2027
  // src/add/css-blocks.ts
@@ -1806,6 +2363,7 @@ var NO_SHADCN = "This app doesn't use shadcn yet. Setting it up: adds Tailwind a
1806
2363
  var REPLACE_DECLINED = "Nothing was changed. Run again and answer yes to replace them, or remove those files first.";
1807
2364
  var REPLACE_NEEDS_FORCE = (paths) => `These files exist and were not added by designsource: ${paths.join(", ")}. Pass --force to replace them.`;
1808
2365
  var UNKNOWN_COMPONENTS = (names) => `Unknown component(s): ${names.join(", ")}. Run without names to pick from the list.`;
2366
+ var SECTION_CONFLICT = (reason) => `Skipped the /design-system section: ${reason}.`;
1809
2367
  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
2368
  var INSTALL_FAILED = (command) => `Installing libraries failed. The files were written; run this to finish: ${command}`;
1811
2369
  var UnknownComponentsError = class extends CliError {
@@ -1837,9 +2395,19 @@ function nonInteractiveQuestions(args) {
1837
2395
  function defaultTargets(root, info) {
1838
2396
  const cssFile = findGlobalStylesheet(info);
1839
2397
  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 };
2398
+ const src = join5(root, "src");
2399
+ const prefix = existsSync8(src) && statSync2(src).isDirectory() ? "src/" : "";
2400
+ const utilsFile = `${prefix}lib/utils.ts`;
2401
+ return {
2402
+ uiDir: `${prefix}components/ui`,
2403
+ utilsFile,
2404
+ cssFile,
2405
+ uiAlias: ALIASES.ui,
2406
+ utilsAlias: ALIASES.utils,
2407
+ componentsDir: `${prefix}components`,
2408
+ componentsAlias: ALIASES.components,
2409
+ ...libOf(utilsFile, ALIASES.utils)
2410
+ };
1843
2411
  }
1844
2412
  function assertSameTargets(planned, actual) {
1845
2413
  for (const key of Object.keys(planned)) {
@@ -1847,7 +2415,7 @@ function assertSameTargets(planned, actual) {
1847
2415
  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
2416
  }
1849
2417
  }
1850
- async function chooseComponents(input, manifest, before, questions) {
2418
+ async function chooseComponents(input, manifest, before, sectionOnDisk, questions) {
1851
2419
  const known = new Set(manifest.components.map((c) => c.name));
1852
2420
  const offered = manifest.components.map((c) => c.name).filter((n) => n !== PORTAL);
1853
2421
  const checked = (names) => {
@@ -1856,11 +2424,45 @@ async function chooseComponents(input, manifest, before, questions) {
1856
2424
  return [...new Set(names)];
1857
2425
  };
1858
2426
  if (input.components.length > 0) return checked(input.components);
1859
- if (input.all) return offered;
2427
+ if (input.all || sectionOnDisk) return offered;
1860
2428
  const earlier = before.filter((n) => known.has(n));
1861
2429
  if (earlier.length > 0) return earlier;
1862
2430
  return checked(await questions.pickComponents(offered));
1863
2431
  }
2432
+ var SECTION_FRAMEWORKS = ["next", "vite"];
2433
+ function sectionDecision(input) {
2434
+ const none = (note) => ({ write: false, blocks: "skip", note });
2435
+ if (!SECTION_FRAMEWORKS.includes(input.framework)) return none(null);
2436
+ if (input.framework === "next" && input.appDir === null) return none(NO_APP_ROUTER);
2437
+ const chosen = new Set(input.chosen);
2438
+ if (!input.allComponents.every((n) => chosen.has(n))) return none(input.present ? null : SECTION_NEEDS_FULL_KIT);
2439
+ const blocks = !input.present ? input.blocksWanted ? "write" : "skip" : input.blocksOnDisk ? input.blocksWanted ? "write" : "keep" : "skip";
2440
+ return { write: true, blocks, note: null };
2441
+ }
2442
+ function planSection(root, input, info, t, manifest, chosen, onDisk) {
2443
+ const none = (note) => ({ decision: { write: false, blocks: "skip", note }, files: () => [], paths: [], packages: {}, blockCount: 0 });
2444
+ const section = manifest.section;
2445
+ if (!section) return none(null);
2446
+ const appDir = info.framework === "next" ? nextAppDir(root) : null;
2447
+ const own = appDir === null ? null : ownDesignSystemRoute(root, appDir);
2448
+ if (own) return none(OWN_DESIGN_SYSTEM_ROUTE(own));
2449
+ const { present, blocksOnDisk, blockIds } = onDisk;
2450
+ const allComponents = manifest.components.map((c) => c.name).filter((n) => n !== PORTAL);
2451
+ const decision = sectionDecision({ chosen, allComponents, present, blocksOnDisk, blocksWanted: input.blocks ?? true, framework: info.framework, appDir });
2452
+ if (!decision.write) return none(decision.note);
2453
+ if (t.componentsDir === null) return none(NO_COMPONENTS_DIR(t.componentsAlias));
2454
+ if (!t.libAlias) return none(NO_LIB_ALIAS(t.utilsAlias));
2455
+ const framework = info.framework === "vite" ? "vite" : "next";
2456
+ const srcDir = existsSync8(join5(root, "src")) ? "src" : "";
2457
+ const files = (darkMarker) => planSectionFiles({ framework, appDir, srcDir, targets: t, manifest, blocks: decision.blocks, keptBlockIds: blockIds, darkMarker });
2458
+ return {
2459
+ decision,
2460
+ files,
2461
+ paths: files({ kind: "class", name: "dark" }).map((f) => f.path),
2462
+ packages: { ...section.packages, ...decision.blocks === "write" ? section.blockPackages : {} },
2463
+ blockCount: shownBlockGroups(section.blockGroups, decision.blocks, blockIds).reduce((n, g) => n + g.blocks.length, 0)
2464
+ };
2465
+ }
1864
2466
  function installCommands(info, manifest, install) {
1865
2467
  const lacks = (pkg) => info.deps[pkg] === void 0;
1866
2468
  const runtime = { ...install };
@@ -1883,16 +2485,41 @@ async function runAdd(input, deps) {
1883
2485
  assertCanAdd(info);
1884
2486
  const planned = info.shadcn ? resolveTargets(root, info.shadcn) : defaultTargets(root, info);
1885
2487
  const cssAbs = resolveInside(root, planned.cssFile);
1886
- if (!existsSync7(cssAbs)) throw new CliError(NO_THEME_FILE(planned.cssFile));
2488
+ if (!existsSync8(cssAbs)) throw new CliError(NO_THEME_FILE(planned.cssFile));
1887
2489
  assertKitUtils(root, info, planned);
1888
2490
  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);
2491
+ const onDisk = sectionPresent(root, planned);
2492
+ const chosen = await chooseComponents(input, manifest, previouslyAdded(root, planned), onDisk.present, deps.questions);
2493
+ const section = planSection(root, input, info, planned, manifest, chosen, onDisk);
2494
+ let packages = planPackages(chosen, manifest, info.deps);
2495
+ let sectionNote = section.decision.note;
2496
+ let writeSection = section.decision.write;
2497
+ if (writeSection) {
2498
+ const withSection = planPackages(chosen, manifest, info.deps, section.packages);
2499
+ const blocking = packages.skipped[0]?.reason ?? (withSection.extraConflicts[0] ? reasonFor(withSection.extraConflicts[0]) : null);
2500
+ if (blocking) {
2501
+ writeSection = false;
2502
+ sectionNote = SECTION_CONFLICT(blocking);
2503
+ } else packages = withSection;
2504
+ }
1891
2505
  const plan = planFiles(root, planned, componentClosure(packages.components, manifest), manifest);
2506
+ const sectionStatus = (writeSection ? section.paths : []).filter((p) => !p.endsWith(".json")).map((p) => [p, existingFileStatus(resolveInside(root, p))]);
1892
2507
  const setup = planSetup(info, manifest, deps.exec);
1893
- if (plan.replaceForeign.length > 0 && !await deps.questions.confirmReplace(plan.replaceForeign)) throw new CliError(REPLACE_DECLINED);
2508
+ if (writeSection && info.framework === "vite") {
2509
+ try {
2510
+ const step = listViteInputStep(info);
2511
+ if (step) setup.steps.push(step);
2512
+ } catch (e) {
2513
+ if (!(e instanceof CliError)) throw e;
2514
+ sectionNote = VITE_INPUT_MANUAL;
2515
+ }
2516
+ }
2517
+ const replaceForeign = [...plan.replaceForeign, ...sectionStatus.filter(([, s]) => s === "foreign").map(([p]) => p)];
2518
+ if (replaceForeign.length > 0 && !await deps.questions.confirmReplace(replaceForeign)) throw new CliError(REPLACE_DECLINED);
1894
2519
  const kept = [];
1895
- for (const path of plan.edited) if (await deps.questions.keepEdits(path)) kept.push(path);
2520
+ for (const path of [...plan.edited, ...sectionStatus.filter(([, s]) => s === "edited").map(([p]) => p)]) {
2521
+ if (await deps.questions.keepEdits(path)) kept.push(path);
2522
+ }
1896
2523
  const writes = plan.write.filter((w) => !kept.includes(w.path));
1897
2524
  if (!info.shadcn) deps.progress(NO_SHADCN);
1898
2525
  for (const step of setup.steps) {
@@ -1904,11 +2531,18 @@ async function runAdd(input, deps) {
1904
2531
  if (!written) throw new CliError("Setup did not leave a components.json. Run this again.");
1905
2532
  assertSameTargets(planned, resolveTargets(root, written));
1906
2533
  }
1907
- const sheet = readFileSync7(cssAbs, "utf8");
2534
+ const sheet = readFileSync8(cssAbs, "utf8");
2535
+ const dark = readDarkMarker(sheet);
2536
+ if (writeSection && info.framework !== "vite" && !dark.known) sectionNote = UNKNOWN_DARK(dark.selector ?? "");
2537
+ const sectionWrites = writeSection ? section.files(dark.marker).filter((f) => !kept.includes(f.path)) : [];
1908
2538
  const removeScaffolding = info.shadcn !== null || hasThemeRegion(sheet);
1909
2539
  const themed = applyTheme(sheet, manifest.theme, { preflight: setup.preflight, removeScaffolding });
1910
2540
  try {
1911
- writeFiles(root, [{ path: planned.cssFile, contents: themed.css }, ...writes.map(({ path, contents }) => ({ path, contents }))], { force: true, created: false });
2541
+ writeFiles(
2542
+ root,
2543
+ [{ path: planned.cssFile, contents: themed.css }, ...[...writes, ...sectionWrites].map(({ path, contents }) => ({ path, contents }))],
2544
+ { force: true, created: false }
2545
+ );
1912
2546
  } catch (e) {
1913
2547
  if (!(e instanceof CliError) || setup.steps.length === 0) throw e;
1914
2548
  throw new CliError(`${e.message} Setup changes (${setup.steps.map((s) => s.line).join(", ")}) were kept; run this again to finish.`, e.exitCode);
@@ -1917,6 +2551,7 @@ async function runAdd(input, deps) {
1917
2551
  const added = writes.filter((w) => w.component !== "utils").map((w) => w.component);
1918
2552
  const shown = added.filter((n) => n !== PORTAL).length;
1919
2553
  if (shown > 0) deps.progress(`Adding ${shown} component${shown === 1 ? "" : "s"}\u2026 \u2713`);
2554
+ if (writeSection) deps.progress("Adding the /design-system section\u2026 \u2713");
1920
2555
  const commands = installCommands(info, manifest, packages.install);
1921
2556
  const installCommand = commands.map(printedCommand).join(" && ") || null;
1922
2557
  if (installCommand && input.skipInstall) deps.progress(`Skipped installing libraries. Run: ${installCommand}`);
@@ -1938,18 +2573,29 @@ async function runAdd(input, deps) {
1938
2573
  projectName: manifest.name,
1939
2574
  replacedTheme: themed.replacedShadcnTheme,
1940
2575
  collisions: themed.collisions,
1941
- uiAlias: planned.uiAlias
2576
+ uiAlias: planned.uiAlias,
2577
+ section: writeSection ? {
2578
+ path: info.framework === "vite" ? "/design-system.html" : "/design-system",
2579
+ blocks: section.blockCount,
2580
+ ...section.decision.blocks === "keep" ? { blocksLeftInPlace: true } : {}
2581
+ } : null,
2582
+ sectionNote
1942
2583
  };
1943
2584
  }
1944
2585
 
1945
2586
  // src/add/summary.ts
1946
- function summaryLines(r) {
2587
+ var leftBlocksLine = (n, reader) => `Left ${n} block${n === 1 ? "" : "s"} in place; ${reader === "agent" ? "no_blocks" : "--no-blocks"} does not remove ${n === 1 ? "it" : "them"}.`;
2588
+ var sectionNoteFor = (note, reader) => reader === "agent" && note === SECTION_NEEDS_FULL_KIT ? SECTION_NEEDS_FULL_KIT_FOR_AGENT : note;
2589
+ function summaryLines(r, reader = "cli") {
1947
2590
  return [
1948
2591
  ...r.replacedTheme ? [`Replaced the theme in ${r.themeFile}`] : [],
1949
2592
  ...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
2593
  ...r.skipped.map((s) => `Skipped ${s.name}: ${s.reason}`),
1951
2594
  ...r.kept.map((path) => `Kept your edits to ${path}`),
1952
2595
  ...r.gone.map((path) => `${path} is no longer in the kit; left it in place`),
2596
+ ...r.section?.blocksLeftInPlace ? [leftBlocksLine(r.section.blocks, reader)] : [],
2597
+ ...r.section ? [`Your design system: ${r.section.path}`] : [],
2598
+ ...r.sectionNote ? [sectionNoteFor(r.sectionNote, reader)] : [],
1953
2599
  `Done. Your components now use "${r.projectName}" from designsource.app.`,
1954
2600
  "Run it again any time to pull updates."
1955
2601
  ];
@@ -2002,10 +2648,10 @@ function nextLine() {
2002
2648
  if (line !== void 0) return Promise.resolve(line);
2003
2649
  if (closed) return Promise.reject(new CliError(EOF_MESSAGE));
2004
2650
  process.stdin.ref?.();
2005
- return new Promise((resolve6, reject) => waiting.push({
2651
+ return new Promise((resolve7, reject) => waiting.push({
2006
2652
  resolve: (line2) => {
2007
2653
  process.stdin.unref?.();
2008
- resolve6(line2);
2654
+ resolve7(line2);
2009
2655
  },
2010
2656
  reject: (err) => {
2011
2657
  process.stdin.unref?.();
@@ -2118,7 +2764,7 @@ function pickTty(question, options, start, stdin, stdout) {
2118
2764
  stdin.resume();
2119
2765
  stdout.write("\x1B[?25l");
2120
2766
  draw([question, ...rows()]);
2121
- return new Promise((resolve6, reject) => {
2767
+ return new Promise((resolve7, reject) => {
2122
2768
  const finish = (after) => {
2123
2769
  stdin.off("keypress", onKey);
2124
2770
  stdin.setRawMode(false);
@@ -2139,7 +2785,7 @@ function pickTty(question, options, start, stdin, stdout) {
2139
2785
  stdout.write(`\r\x1B[J${question} ${chosen.label}
2140
2786
  `);
2141
2787
  });
2142
- resolve6(chosen.value);
2788
+ resolve7(chosen.value);
2143
2789
  return;
2144
2790
  }
2145
2791
  if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
@@ -2171,7 +2817,7 @@ function pickManyTty(question, options, preselected, stdin, stdout) {
2171
2817
  stdin.resume();
2172
2818
  stdout.write("\x1B[?25l");
2173
2819
  draw([head, ...rows()]);
2174
- return new Promise((resolve6, reject) => {
2820
+ return new Promise((resolve7, reject) => {
2175
2821
  const finish = (after) => {
2176
2822
  stdin.off("keypress", onKey);
2177
2823
  stdin.setRawMode(false);
@@ -2192,7 +2838,7 @@ function pickManyTty(question, options, preselected, stdin, stdout) {
2192
2838
  stdout.write(`\r\x1B[J${question} ${chosen.length > 0 ? chosen.map((o) => o.label).join(", ") : "none"}
2193
2839
  `);
2194
2840
  });
2195
- resolve6(chosen.map((o) => o.value));
2841
+ resolve7(chosen.map((o) => o.value));
2196
2842
  return;
2197
2843
  }
2198
2844
  if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
@@ -2207,18 +2853,21 @@ function pickManyTty(question, options, preselected, stdin, stdout) {
2207
2853
  });
2208
2854
  }
2209
2855
 
2856
+ // src/commands/scaffold.ts
2857
+ import { resolve as resolve4 } from "node:path";
2858
+
2210
2859
  // src/connect/resolve-token.ts
2211
2860
  import { homedir } from "node:os";
2212
2861
 
2213
2862
  // src/connect/store.ts
2214
2863
  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";
2864
+ import { chmodSync, constants, copyFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync9, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
2865
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join6, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
2217
2866
  var WHERE = ["keychain", "secret-service", "dpapi", "file"];
2218
2867
  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");
2868
+ if (platform === "win32") return join6(env.APPDATA || join6(home, "AppData", "Roaming"), "designsource", "credentials.json");
2869
+ const config = env.XDG_CONFIG_HOME && isAbsolute2(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join6(home, ".config");
2870
+ return join6(config, "designsource", "credentials.json");
2222
2871
  }
2223
2872
  function isFileEntry(value) {
2224
2873
  if (typeof value !== "object" || value === null) return false;
@@ -2228,7 +2877,7 @@ function isFileEntry(value) {
2228
2877
  function readCredentials(path) {
2229
2878
  let text;
2230
2879
  try {
2231
- text = readFileSync8(path, "utf8");
2880
+ text = readFileSync9(path, "utf8");
2232
2881
  } catch {
2233
2882
  return { version: 1, projects: {} };
2234
2883
  }
@@ -2278,7 +2927,7 @@ function writeCredentials(path, data) {
2278
2927
  const dir = dirname2(path);
2279
2928
  mkdirSync2(dir, { recursive: true, mode: 448 });
2280
2929
  chmodSync(dir, 448);
2281
- const temp = join5(dir, `.credentials.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
2930
+ const temp = join6(dir, `.credentials.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
2282
2931
  try {
2283
2932
  writeFileSync3(temp, `${JSON.stringify(data, null, 2)}
2284
2933
  `, { mode: 384, flag: "wx" });
@@ -2412,18 +3061,8 @@ function validateManifest(json) {
2412
3061
 
2413
3062
  // src/fetch-manifest.ts
2414
3063
  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;
2419
- try {
2420
- res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" } });
2421
- } catch {
2422
- throw new CliError(UNREACHABLE(opts.api));
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);
3064
+ const query = { framework: opts.framework, ...opts.name ? { name: opts.name } : {} };
3065
+ return validateManifest(await getJson({ api: opts.api, token: opts.token, path: "/api/starter", query }, fetchImpl));
2427
3066
  }
2428
3067
 
2429
3068
  // src/package-name.ts
@@ -2444,12 +3083,12 @@ function detectRunner(userAgent) {
2444
3083
  }
2445
3084
  var INSTALL = { pnpm: "pnpm install", npm: "npm install", yarn: "yarn", bun: "bun install" };
2446
3085
  var DEV = { pnpm: "pnpm dev", npm: "npm run dev", yarn: "yarn dev", bun: "bun dev" };
2447
- function nextStepsText({ runner, framework, folder, created }) {
3086
+ function nextStepsText({ runner, framework, folder, here }) {
2448
3087
  const lines = ["Next steps:"];
2449
3088
  if (framework === "next") {
2450
- if (created) lines.push(` cd ${folder}`);
3089
+ if (!here) lines.push(` cd ${folder}`);
2451
3090
  lines.push(` ${INSTALL[runner]}`, ` ${DEV[runner]}`);
2452
- } else if (folder === ".") {
3091
+ } else if (here) {
2453
3092
  lines.push(" Open design-system/PROMPT.md and paste it into your coding agent.");
2454
3093
  } else {
2455
3094
  lines.push(` Open ${folder}/design-system/PROMPT.md and paste it into your coding agent, run from ${folder}.`);
@@ -2491,7 +3130,7 @@ async function scaffold(input, env, io) {
2491
3130
  ${written.map((p) => ` ${p}`).join("\n")}
2492
3131
 
2493
3132
  `);
2494
- io.stdout(nextStepsText({ runner, framework, folder, created }));
3133
+ io.stdout(nextStepsText({ runner, framework, folder, here: root === resolve4(io.cwd) }));
2495
3134
  }
2496
3135
 
2497
3136
  // src/commands/add.ts
@@ -2537,13 +3176,14 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
2537
3176
  assertKitUtils(root, info, targets);
2538
3177
  let mode;
2539
3178
  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);
3179
+ const first = previouslyAdded(root, targets).every((n) => n === "utils") && !sectionPresent(root, targets).present;
3180
+ if (first) mode = await pick(PICK_QUESTION, ADD_MODES, 0);
2541
3181
  }
2542
3182
  const { token, entry } = await requireSavedToken(args.token, { cwd: root, store, interactive: terminal });
2543
3183
  const questions = interactive ? ttyQuestions(args, mode, io) : nonInteractiveQuestions(args);
2544
3184
  try {
2545
3185
  const result = await runAdd(
2546
- { root, token, api: apiFor(args, entry), components: args.components, skipInstall: args.skipInstall, all: args.all },
3186
+ { root, token, api: apiFor(args, entry), components: args.components, skipInstall: args.skipInstall, all: args.all, blocks: !args.noBlocks },
2547
3187
  { fetchImpl: io.fetchImpl, exec, questions, progress: (line) => io.stdout(`${line}
2548
3188
  `) }
2549
3189
  );
@@ -2557,9 +3197,9 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
2557
3197
  }
2558
3198
 
2559
3199
  // src/commands/connect.ts
2560
- import { accessSync, constants as constants2, existsSync as existsSync9, statSync as statSync3 } from "node:fs";
3200
+ import { accessSync, constants as constants2, existsSync as existsSync10, statSync as statSync3 } from "node:fs";
2561
3201
  import { homedir as homedir2 } from "node:os";
2562
- import { join as join7 } from "node:path";
3202
+ import { join as join8 } from "node:path";
2563
3203
 
2564
3204
  // src/connect/fetch-project.ts
2565
3205
  var RejectedTokenError = class extends CliError {
@@ -2569,16 +3209,13 @@ var RejectedTokenError = class extends CliError {
2569
3209
  };
2570
3210
  var malformed3 = () => new CliError("Unexpected response from the API \u2014 not a project.");
2571
3211
  async function fetchProject(opts, fetchImpl = fetch) {
2572
- const url = new URL("/api/project", `${opts.api}/`);
2573
- let res;
3212
+ let body;
2574
3213
  try {
2575
- res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" } });
2576
- } catch {
2577
- throw new CliError(UNREACHABLE(opts.api));
3214
+ body = await getJson({ api: opts.api, token: opts.token, path: "/api/project" }, fetchImpl);
3215
+ } catch (e) {
3216
+ if (e instanceof ApiError && e.status === 401) throw new RejectedTokenError();
3217
+ throw e;
2578
3218
  }
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
3219
  if (typeof body !== "object" || body === null) throw malformed3();
2583
3220
  const { id, name } = body;
2584
3221
  if (typeof id !== "string" || typeof name !== "string") throw malformed3();
@@ -2587,14 +3224,14 @@ async function fetchProject(opts, fetchImpl = fetch) {
2587
3224
  }
2588
3225
 
2589
3226
  // 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);
3227
+ import { existsSync as existsSync9 } from "node:fs";
3228
+ import { dirname as dirname3, isAbsolute as isAbsolute3, join as join7, relative as relative3, resolve as resolve5, sep as sep3 } from "node:path";
3229
+ function projectRoot(cwd, exists = existsSync9) {
3230
+ let dir = resolve5(cwd);
2594
3231
  for (; ; ) {
2595
- if (exists(join6(dir, ".git"))) return dir;
3232
+ if (exists(join7(dir, ".git"))) return dir;
2596
3233
  const parent = dirname3(dir);
2597
- if (parent === dir) return resolve4(cwd);
3234
+ if (parent === dir) return resolve5(cwd);
2598
3235
  dir = parent;
2599
3236
  }
2600
3237
  }
@@ -2603,8 +3240,8 @@ function within2(folder, root) {
2603
3240
  return rel === "" || rel !== ".." && !rel.startsWith(`..${sep3}`) && !isAbsolute3(rel);
2604
3241
  }
2605
3242
  function homeFolderRefusal(root, home) {
2606
- const folder = resolve4(root);
2607
- const homeDir = resolve4(home);
3243
+ const folder = resolve5(root);
3244
+ const homeDir = resolve5(home);
2608
3245
  const tail = "and writing there would set up every project on this computer.";
2609
3246
  if (folder === homeDir) return `Run this in your project folder \u2014 ${folder} is your home folder, ${tail}`;
2610
3247
  if (dirname3(folder) === folder || within2(homeDir, folder)) return `Run this in your project folder \u2014 ${folder} is a system folder, ${tail}`;
@@ -2619,7 +3256,7 @@ function onPath(bin, env, platform) {
2619
3256
  const exts = windows ? ["", ...(env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""];
2620
3257
  return dirs.some(
2621
3258
  (dir) => exts.some((ext) => {
2622
- const file = join7(dir, bin + ext);
3259
+ const file = join8(dir, bin + ext);
2623
3260
  try {
2624
3261
  if (!statSync3(file).isFile()) return false;
2625
3262
  if (!windows) accessSync(file, constants2.X_OK);
@@ -2635,7 +3272,7 @@ function defaultConnectDeps(env) {
2635
3272
  const platform = process.platform;
2636
3273
  return {
2637
3274
  store: defaultStore(env),
2638
- detect: () => detectApps({ env, platform, home, exists: existsSync9, onPath: (bin) => onPath(bin, env, platform) }),
3275
+ detect: () => detectApps({ env, platform, home, exists: existsSync10, onPath: (bin) => onPath(bin, env, platform) }),
2639
3276
  credentialsPath: credentialsPath(env, platform, home)
2640
3277
  };
2641
3278
  }
@@ -2644,7 +3281,8 @@ var app = (id) => APPS.find((a) => a.id === id);
2644
3281
  var NO_APPS_FOUND = "No coding apps found. Pass --apps claude,cursor,vscode,codex,gemini.";
2645
3282
  var NO_APPS_PICKED = "No apps picked. Nothing was changed.";
2646
3283
  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) {
3284
+ function savedLine(name, where, file, reused) {
3285
+ if (reused) return `Using your saved token for "${name}" from ${whereFrom(where, file)} \u2713`;
2648
3286
  if (where === "keychain") return `Saved your token for "${name}" in the macOS keychain \u2713`;
2649
3287
  if (where === "secret-service") return `Saved your token for "${name}" in the system keyring \u2713`;
2650
3288
  if (where === "dpapi") return `Saved your token for "${name}" with Windows protection \u2713`;
@@ -2734,7 +3372,7 @@ async function runConnect(args, io, deps = defaultConnectDeps(process.env)) {
2734
3372
  }
2735
3373
  const changed = plans.filter(({ plan }) => plan.status === "create" || plan.status === "update").map(({ id }) => id);
2736
3374
  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)]);
3375
+ say([...backup, savedLine(project.name, entry.where, deps.credentialsPath, kept !== null), ...plans.flatMap(({ id, plan }) => appLines(id, plan)), ...closingLines(apps, changed)]);
2738
3376
  }
2739
3377
  function connectedApps(root, store) {
2740
3378
  const saved = store.byFolder(root);
@@ -2788,13 +3426,11 @@ async function runIntegrate(args, env, io, store) {
2788
3426
  await scaffold({ folder, framework, token, api: apiFor(args, saved?.entry), force: args.force }, env, io);
2789
3427
  }
2790
3428
 
2791
- // src/mcp/server.ts
2792
- import { createInterface as createInterface2 } from "node:readline";
2793
-
2794
3429
  // src/version.ts
2795
- var VERSION = true ? "0.5.0" : "0.0.0-dev";
3430
+ var VERSION = true ? "0.6.1" : "0.0.0-dev";
2796
3431
 
2797
3432
  // src/mcp/jsonrpc.ts
3433
+ import { StringDecoder } from "node:string_decoder";
2798
3434
  var PARSE_ERROR = -32700;
2799
3435
  var INVALID_REQUEST = -32600;
2800
3436
  var METHOD_NOT_FOUND = -32601;
@@ -2836,6 +3472,21 @@ function parseLine(line) {
2836
3472
  if (params !== void 0) message.params = params;
2837
3473
  return { kind: "notification", message };
2838
3474
  }
3475
+ async function* readLines(input) {
3476
+ const decoder = new StringDecoder("utf8");
3477
+ let buffered = "";
3478
+ for await (const chunk of input) {
3479
+ buffered += typeof chunk === "string" ? chunk : decoder.write(chunk);
3480
+ let end;
3481
+ while ((end = buffered.indexOf("\n")) !== -1) {
3482
+ const line = buffered.slice(0, end);
3483
+ buffered = buffered.slice(end + 1);
3484
+ yield line.endsWith("\r") ? line.slice(0, -1) : line;
3485
+ }
3486
+ }
3487
+ buffered += decoder.end();
3488
+ if (buffered) yield buffered.endsWith("\r") ? buffered.slice(0, -1) : buffered;
3489
+ }
2839
3490
 
2840
3491
  // src/mcp/prompts.ts
2841
3492
  var INTEGRATE_PROMPT_NAME = "integrate-design-system";
@@ -2849,7 +3500,7 @@ function getPrompt(name) {
2849
3500
  }
2850
3501
 
2851
3502
  // src/mcp/project-folder.ts
2852
- import { isAbsolute as isAbsolute4, relative as relative4, resolve as resolve5, sep as sep4 } from "node:path";
3503
+ import { isAbsolute as isAbsolute4, relative as relative4, resolve as resolve6, sep as sep4 } from "node:path";
2853
3504
  var NOT_SURE_WHICH_FOLDER = "Not sure which project folder to change: run npx designsource connect in it first.";
2854
3505
  function isWithin2(folder, root) {
2855
3506
  const rel = relative4(root, folder);
@@ -2857,10 +3508,10 @@ function isWithin2(folder, root) {
2857
3508
  }
2858
3509
  function resolveProjectFolder(cwd, entry) {
2859
3510
  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);
3511
+ const here = resolve6(cwd);
3512
+ const holding = entry.folders.map((f) => resolve6(f)).filter((f) => isWithin2(here, f)).sort((a, b) => b.length - a.length);
2862
3513
  if (holding[0]) return holding[0];
2863
- return entry.folders.length === 1 ? resolve5(entry.folders[0]) : null;
3514
+ return entry.folders.length === 1 ? resolve6(entry.folders[0]) : null;
2864
3515
  }
2865
3516
 
2866
3517
  // src/mcp/tools.ts
@@ -2894,11 +3545,12 @@ var MCP_EXEC_TIMEOUT_MS = 10 * 60 * 1e3;
2894
3545
  var UNKNOWN_FOR_AGENT = (names) => `Unknown component(s): ${names.join(", ")}. Call list_components for the names.`;
2895
3546
  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
3547
  async function addUiKit(args, ctx) {
2897
- const { components, replace_existing: replace } = args;
3548
+ const { components, replace_existing: replace, no_blocks: noBlocks } = args;
2898
3549
  if (components !== void 0 && !(Array.isArray(components) && components.every((c) => typeof c === "string"))) {
2899
3550
  return errorResult('"components" must be an array of component names.');
2900
3551
  }
2901
3552
  if (replace !== void 0 && typeof replace !== "boolean") return errorResult('"replace_existing" must be true or false.');
3553
+ if (noBlocks !== void 0 && typeof noBlocks !== "boolean") return errorResult('"no_blocks" must be true or false.');
2902
3554
  if (ctx.token === null) return errorResult(ctx.missingToken ?? MCP_TOKEN_REQUIRED);
2903
3555
  const root = resolveProjectFolder(ctx.cwd, ctx.projectFolders === null ? null : { folders: ctx.projectFolders });
2904
3556
  if (root === null) return errorResult(NOT_SURE_WHICH_FOLDER);
@@ -2914,14 +3566,14 @@ async function addUiKit(args, ctx) {
2914
3566
  const exec = (cmd, cmdArgs, opts) => ctx.exec(cmd, cmdArgs, { ...opts, timeoutMs: MCP_EXEC_TIMEOUT_MS });
2915
3567
  try {
2916
3568
  const result = await runAdd(
2917
- { root, token: ctx.token, api: ctx.api, components: components ?? [], skipInstall: false },
3569
+ { root, token: ctx.token, api: ctx.api, components: components ?? [], skipInstall: false, blocks: noBlocks !== true },
2918
3570
  { fetchImpl: ctx.fetchImpl, exec, questions, progress: (line) => progress.push(line) }
2919
3571
  );
2920
3572
  const written = result.added.filter((n) => n !== "preview-portal");
2921
3573
  return textResult(
2922
3574
  [
2923
3575
  ...progress,
2924
- ...summaryLines(result),
3576
+ ...summaryLines(result, "agent"),
2925
3577
  ...written.length > 0 ? [`Added: ${written.join(", ")}`] : [],
2926
3578
  `Next: import components from ${result.uiAlias} (for example: import { Button } from "${result.uiAlias}/button").`
2927
3579
  ].join("\n")
@@ -3053,12 +3705,13 @@ ${files.join("\n\n")}`);
3053
3705
  },
3054
3706
  {
3055
3707
  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.",
3708
+ 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. A full run (no components named) also writes the /design-system section, every component, block and sample page in the project's theme, with its blocks unless no_blocks is true. Changes files in the project, so your client will ask the user first. Never overwrites components the user edited.",
3057
3709
  inputSchema: {
3058
3710
  type: "object",
3059
3711
  properties: {
3060
3712
  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." }
3713
+ replace_existing: { type: "boolean", description: "Replace component files that exist but were not added by designsource. Ask the user first." },
3714
+ no_blocks: { type: "boolean", description: "Add the /design-system section without its blocks and their libraries. Blocks an earlier run wrote are left in place." }
3062
3715
  },
3063
3716
  additionalProperties: false
3064
3717
  },
@@ -3164,36 +3817,32 @@ function validateSnapshot(json) {
3164
3817
  if (blocks.header !== void 0 && typeof blocks.header !== "string") return { ...json, blocks: { ...blocks, header: void 0 } };
3165
3818
  return json;
3166
3819
  }
3167
- var FETCH_TIMEOUT_MS = 3e4;
3168
3820
  async function fetchSnapshot(opts, fetchImpl = fetch) {
3169
- const url = new URL("/api/snapshot", `${opts.api}/`);
3170
- let res;
3171
- try {
3172
- res = await fetchImpl(url.toString(), {
3173
- headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" },
3174
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
3175
- });
3176
- } catch {
3177
- throw new CliError(UNREACHABLE(opts.api));
3178
- }
3179
- const body = await res.json().catch(() => null);
3180
- if (!res.ok) throw new CliError(messageForResponse(res.status, body, opts.api));
3181
- return validateSnapshot(body);
3821
+ return validateSnapshot(await getJson({ api: opts.api, token: opts.token, path: "/api/snapshot" }, fetchImpl));
3182
3822
  }
3823
+ var STALE_RETRY_MS = 15e3;
3824
+ var servesStale = (e) => !(e instanceof ApiError) || e.status === null || e.status >= 500;
3183
3825
  function createSnapshotCache(fetcher, opts = {}) {
3184
3826
  const ttl = opts.ttlMs ?? 6e4;
3185
3827
  const now = opts.now ?? Date.now;
3828
+ const retry = opts.retryMs ?? STALE_RETRY_MS;
3186
3829
  let cached = null;
3187
3830
  let inflight = null;
3831
+ let retryAt = 0;
3188
3832
  return {
3189
3833
  get() {
3190
- if (cached && now() - cached.fetchedAt < ttl) return Promise.resolve(cached);
3834
+ if (cached && (now() - cached.fetchedAt < ttl || now() < retryAt)) return Promise.resolve(cached);
3191
3835
  if (inflight) return inflight;
3192
3836
  inflight = fetcher().then((snapshot) => {
3193
3837
  cached = { snapshot, fetchedAt: now() };
3838
+ retryAt = 0;
3194
3839
  return cached;
3195
3840
  }).catch((e) => {
3196
- if (!cached) throw e;
3841
+ if (!cached || !servesStale(e)) {
3842
+ cached = null;
3843
+ throw e;
3844
+ }
3845
+ retryAt = now() + retry;
3197
3846
  opts.warn?.(`Could not refresh the design system; serving the snapshot from ${new Date(cached.fetchedAt).toISOString()}: ${e instanceof Error ? e.message : String(e)}`);
3198
3847
  return cached;
3199
3848
  }).finally(() => {
@@ -3230,11 +3879,12 @@ async function runMcp(args, io, streams = { input: process.stdin, output: proces
3230
3879
  }
3231
3880
  }, { warn });
3232
3881
  const protocol = { version: VERSION, snapshot: () => cache.get(), warn, context: session };
3233
- const lines = createInterface2({ input: streams.input, crlfDelay: Infinity });
3882
+ let closed2 = false;
3234
3883
  streams.output.on("error", () => {
3235
- lines.close();
3884
+ closed2 = true;
3236
3885
  });
3237
- for await (const raw of lines) {
3886
+ for await (const raw of readLines(streams.input)) {
3887
+ if (closed2) break;
3238
3888
  const line = raw.trim();
3239
3889
  if (!line) continue;
3240
3890
  const response = await handle(parseLine(line), protocol);