designsource 0.5.0 → 0.6.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 +12 -7
  2. package/dist/index.js +707 -76
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -6,10 +6,10 @@
6
6
 
7
7
  The command line for a [DS source](https://designsource.app) design system. Five things it does:
8
8
 
9
- - **`add`** — add the UI kit to the React app you already have: your theme in its global stylesheet, the 61 components and the libraries they import, with Tailwind v4, the `@/` alias and the shadcn config set up first when the app lacks them. Run it again to pull updates.
9
+ - **`add`** — add the UI kit to the React app you already have: your theme in its global stylesheet, the 61 components and the libraries they import, with Tailwind v4, the `@/` alias and the shadcn config set up first when the app lacks them, plus a `/design-system` section showing them. Run it again to pull updates.
10
10
  - **`connect`** — connect your coding apps to the design system: saves the project token once, privately, on this computer, and writes each app's MCP settings in the project with no token in them. Claude Code, Cursor, VS Code, Codex and Gemini CLI.
11
11
  - **`integrate`** — add the design system to the app you already have: a `design-system/` folder with your tokens as CSS variables, a prompt that tells your coding agent how to wire them in, and the component kit as reference. Vue, Svelte, Angular or plain CSS.
12
- - **`create`** — start a new Next.js project from it: tokens, all 61 components, the block pages (`/blocks`) and your mockup page, running after `pnpm install && pnpm dev`.
12
+ - **`create`** — start a new Next.js project from it: tokens, all 61 components, a front page on `/` and the design system under `/design-system` (components, blocks, sample pages and your mockup page), running after `pnpm install && pnpm dev`.
13
13
  - **`mcp`** — serve the design system to your coding agent over MCP: tokens, every component's source, your mockup page and a step-by-step integration guide, read on demand instead of pasted, and a tool that adds the UI kit to your app for you. Claude Code, Cursor, Codex — any client that speaks MCP over stdio.
14
14
 
15
15
  ```sh
@@ -39,7 +39,7 @@ Works the same with `pnpm dlx designsource …`, `yarn dlx designsource …` and
39
39
  ## `add` — the UI kit in the app you have
40
40
 
41
41
  ```sh
42
- npx designsource add [names…] [--all] [--yes] [--force] [--skip-install] [--token <project token>] [--api <origin>]
42
+ npx designsource add [names…] [--all] [--yes] [--force] [--skip-install] [--no-blocks] [--token <project token>] [--api <origin>]
43
43
  ```
44
44
 
45
45
  Run it in your React app's folder. It writes your theme into the app's global stylesheet, the kit's components under the app's `components/ui` and the `cn` helper in `lib/utils.ts`, then installs the libraries those components import with the package manager the app already uses (pnpm, npm, yarn or bun). Every setup step it takes is named in one line as it runs.
@@ -49,7 +49,9 @@ Run it in your React app's folder. It writes your theme into the app's global st
49
49
  Pick some…
50
50
  Adding theme… ✓
51
51
  Adding 61 components… ✓
52
+ Adding the /design-system section… ✓
52
53
  Installing libraries… ✓
54
+ Your design system: /design-system
53
55
  Done. Your components now use "my-system" from designsource.app.
54
56
  Run it again any time to pull updates.
55
57
  ```
@@ -62,6 +64,8 @@ Run it again any time to pull updates.
62
64
  - **Reruns** refresh the theme and every component `add` wrote before; `add <names…>` adds more, and `--all` adds everything. A component file carries a `// designsource: <name> <hash>` first line, which is how a rerun tells a file you edited from one it can update. Edited files are kept by default (Enter on "Keep your edits to …?") and named at the end; `--force` replaces them.
63
65
  - **Files designsource did not write**, such as stock shadcn components, are replaced only on a yes ("Replace N existing components with your design system's?") or with `--force`; a no changes nothing. Without a terminal, or with `--yes`, no question is asked: all components on a first run, your edits kept, and the run stops naming any such file unless `--force` is given.
64
66
  - **`--skip-install`** writes the files and prints the install command instead of running it. A failed install leaves the files in place and says which command finishes it.
67
+ - **The `/design-system` section** comes with the full kit: a first run answered All, `--all`, `--yes` or a run outside a terminal, or a bare rerun in an app that already has every component. It is your design system inside your app: the component gallery, the 34 blocks, the sample pages and your mockup page, each on its own route, with its own copy of your theme and its own light/dark switch, so your app's theme rules do not reach it. In a Next.js app (App Router) it is a route folder, `app/design-system/` (or `src/app/design-system/`), drawn over your app's own header and footer; its pieces go under `components/design-system/` and `components/blocks/`. In a Vite app it is its own page, `/design-system.html` beside `index.html`, with its own stylesheet, and `add` lists it among `vite.config`'s build inputs so `vite build` builds it (a config it cannot edit safely is left alone and the lines to add are printed; a custom `base` or `root` is not handled). `add <names…>` and Pick some write no section and say so in one line; in an app that already has it they leave it as it is. A Pages Router app gets one line and no section. When a library the section needs is in your app at another major, the section is skipped with a line saying why. Section files are stamped like components, so reruns refresh them and keep your edits; its JSON data is written fresh every run.
68
+ - **`--no-blocks`** writes the section without its blocks and installs none of the libraries only they need; the section then has no Blocks menu. After that, blocks follow what is on disk: a rerun does not add back blocks a `--no-blocks` run skipped, and `--no-blocks` on an app that has them leaves them as they are and says how many (`Left 34 blocks in place; --no-blocks does not remove them.`).
65
69
 
66
70
  ## `connect` — your coding apps, connected
67
71
 
@@ -129,7 +133,7 @@ Writes `design-system/` into the folder (default: the current one). For Vue, Sve
129
133
  npx designsource create [folder] [--token <project token>] [--api <origin>] [--force]
130
134
  ```
131
135
 
132
- Writes a runnable Next.js app into a new or empty folder (default `my-design-system`): Tailwind v4 with the shadcn theme CSS built from your tokens, 61 UI components under `components/ui`, your mockup page on `/`, a component gallery on `/components`, light and dark via `next-themes`. Next steps print in the dialect of the runner you used (`pnpm`, `npm`, `yarn` or `bun`); a pnpm run pins `packageManager`.
136
+ Writes a runnable Next.js app into a new or empty folder (default `my-design-system`): Tailwind v4 with the shadcn theme CSS built from your tokens, 61 UI components under `components/ui`, a front page on `/`, and the design system under `/design-system`: the component gallery (`/design-system/components`), the blocks (`/design-system/blocks`, one page each at `/design-system/blocks/<id>`), the sample pages and your mockup page (`/design-system/custom`); light and dark via `next-themes`. Next steps print in the dialect of the runner you used (`pnpm`, `npm`, `yarn` or `bun`); a pnpm run pins `packageManager`.
133
137
 
134
138
  <p align="center">
135
139
  <img src="https://designsource.app/designsource/starter-dark-home.png" alt="Generated Next.js starter, home page, dark" width="49%">
@@ -209,9 +213,9 @@ The workbench's Connect an agent dialog hands out the `connect` command and the
209
213
  | `get_integration_guide` | The steps: wire the tokens, bring in the components, migrate existing styles, document. |
210
214
  | `list_blocks` | The 34 ready-made page layouts (login, signup, sidebars, a dashboard, chart sets) with the components and files of each. |
211
215
  | `get_block_source` | Every file of one block, headed by the path it takes under `components/blocks/`. |
212
- | `add_ui_kit` | Adds the UI kit to the React app in the project folder: the theme, the components and their libraries, with the same setup as `add`. Optional `components` and `replace_existing` (for files designsource did not write). |
216
+ | `add_ui_kit` | Adds the UI kit to the React app in the project folder: the theme, the components and their libraries, with the same setup as `add`, and the `/design-system` section when it adds every component. Optional `components`, `replace_existing` (for files designsource did not write) and `no_blocks` (the section without its blocks, as `--no-blocks`). |
213
217
 
214
- New in 0.4.0: `list_blocks` and `get_block_source`, the page layouts built from the components. `create` now also writes them as `/blocks` pages, and `integrate` drops them under `design-system/reference/blocks/`. Against an older server the two tools answer that the server sent no blocks.
218
+ New in 0.4.0: `list_blocks` and `get_block_source`, the page layouts built from the components; `integrate` drops them under `design-system/reference/blocks/`. Against an older server the two tools answer that the server sent no blocks. New in 0.6.0: `add_ui_kit` writes the `/design-system` section as `add` does, and takes `no_blocks`.
215
219
 
216
220
  The tools read the design system, and `add_ui_kit` adds its UI kit to the React app in the project folder (with `--project`, the folder `connect` saved for it: the one the client started in or under, else the only saved one, and it refuses with a line telling the agent to run `connect` there when it cannot tell; with `--token` alone, the folder the client started in; it never overwrites a component you edited, only replaces other existing files when told to, and your client asks before running it; the install it runs keeps the project token out of its environment and its output off the protocol stream); nothing an agent does here changes the design system itself. The project is fetched on the first tool call and refreshed every 60 seconds, so a Save in the workbench shows on the next call. Like every export, it needs the project's account on Pro; on the free plan every tool answers with one line saying so.
217
221
 
@@ -227,6 +231,7 @@ The tools read the design system, and `add_ui_kit` adds its UI kit to the React
227
231
  | `--forget` | `connect` only. Remove this folder's saved token from this computer. |
228
232
  | `--project` | `mcp`: the saved project whose token to use. `connect --forget`: which project, when several are connected to the folder. |
229
233
  | `--skip-install` | `add` only. Write the files, print the install command. |
234
+ | `--no-blocks` | `add` only. The `/design-system` section without its blocks and their libraries; blocks already written stay. |
230
235
  | `--framework` | `integrate` only. Skip the picker: `vue`, `svelte`, `angular` or `css`. |
231
236
  | `--token` | The project token, or set `DS_SYNC_TOKEN` for scripts. Else the one `connect` saved for this folder; asked hidden when there is none. |
232
237
  | `--api` | API origin. Default `https://designsource.app`; point it at a self-hosted instance. |
@@ -266,7 +271,7 @@ By the maintainer, through GitHub Actions with npm trusted publishing: no npm to
266
271
  3. Tag the merge commit `designsource@<version>` and push the tag:
267
272
 
268
273
  ```sh
269
- git tag designsource@0.5.0 && git push origin designsource@0.5.0
274
+ git tag designsource@0.6.0 && git push origin designsource@0.6.0
270
275
  ```
271
276
 
272
277
  The workflow (`.github/workflows/release-designsource.yml`) refuses a tag that does not match `package.json`, runs the tests (which build `dist/` first), publishes, then installs the published version from npm and runs `--help` against it.
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];
@@ -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,56 @@ 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
+
1370
1889
  // src/add/kit-manifest.ts
1371
1890
  var malformed = () => new CliError("Unexpected response from the API \u2014 not a kit manifest.");
1372
1891
  var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1373
1892
  var isStrings = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
1374
1893
  var isStringMap = (v) => isRecord(v) && Object.values(v).every((s) => typeof s === "string");
1894
+ var isSectionFile = (f) => isRecord(f) && typeof f.key === "string" && typeof f.contents === "string" && isStrings(f.kitImports) && isStrings(f.packages) && typeof f.block === "boolean";
1895
+ 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");
1896
+ function validateSection(s) {
1897
+ if (!isRecord(s) || !Array.isArray(s.files) || !s.files.every(isSectionFile)) throw malformed();
1898
+ if (typeof s.themeCss !== "string" || !Array.isArray(s.blockGroups) || !s.blockGroups.every(isBlockGroup)) throw malformed();
1899
+ if (!isStringMap(s.packages) || !isStringMap(s.blockPackages)) throw malformed();
1900
+ return { files: s.files, themeCss: s.themeCss, blockGroups: s.blockGroups, packages: s.packages, blockPackages: s.blockPackages, mockupSpec: s.mockupSpec ?? null };
1901
+ }
1375
1902
  function validateKitManifest(json) {
1376
1903
  if (!isRecord(json)) throw malformed();
1377
1904
  if (typeof json.version !== "number") throw malformed();
@@ -1387,6 +1914,7 @@ function validateKitManifest(json) {
1387
1914
  }
1388
1915
  if (!isStrings(json.utilsPackages)) throw malformed();
1389
1916
  if (!isStringMap(json.packages) || !isStringMap(json.devPackages)) throw malformed();
1917
+ const section = json.section === void 0 ? void 0 : validateSection(json.section);
1390
1918
  return {
1391
1919
  version: 1,
1392
1920
  kind: "kit",
@@ -1396,7 +1924,8 @@ function validateKitManifest(json) {
1396
1924
  utils: json.utils,
1397
1925
  utilsPackages: json.utilsPackages,
1398
1926
  packages: json.packages,
1399
- devPackages: json.devPackages
1927
+ devPackages: json.devPackages,
1928
+ ...section ? { section } : {}
1400
1929
  };
1401
1930
  }
1402
1931
 
@@ -1433,7 +1962,7 @@ function conflictBetween(pkg, have, need) {
1433
1962
  return { pkg, have, need };
1434
1963
  }
1435
1964
  var reasonFor = (c) => `this app uses ${c.pkg} ${majorOf(c.have)}, the kit needs ${majorOf(c.need)}`;
1436
- function planPackages(components, manifest, appDeps) {
1965
+ function planPackages(components, manifest, appDeps, extra = {}) {
1437
1966
  const byName = new Map(manifest.components.map((c) => [c.name, c]));
1438
1967
  const conflictOf = /* @__PURE__ */ new Map();
1439
1968
  for (const name of componentClosure(components, manifest)) {
@@ -1462,9 +1991,18 @@ function planPackages(components, manifest, appDeps) {
1462
1991
  const need = manifest.packages[pkg];
1463
1992
  if (need !== void 0 && appDeps[pkg] === void 0) install[pkg] = need;
1464
1993
  }
1465
- const reactIs = manifest.packages["react-is"];
1994
+ const extraConflicts = [];
1995
+ for (const [pkg, need] of Object.entries(extra)) {
1996
+ const have = appDeps[pkg];
1997
+ const conflict = have === void 0 ? null : conflictBetween(pkg, have, need);
1998
+ if (conflict) extraConflicts.push(conflict);
1999
+ }
2000
+ if (extraConflicts.length === 0) {
2001
+ for (const [pkg, need] of Object.entries(extra)) if (appDeps[pkg] === void 0 && !(pkg in install)) install[pkg] = need;
2002
+ }
2003
+ const reactIs = manifest.packages["react-is"] ?? extra["react-is"];
1466
2004
  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 };
2005
+ return { install, conflicts: [...conflictOf.values()], skipped, components: kept, extraConflicts };
1468
2006
  }
1469
2007
 
1470
2008
  // src/add/css-blocks.ts
@@ -1806,6 +2344,7 @@ var NO_SHADCN = "This app doesn't use shadcn yet. Setting it up: adds Tailwind a
1806
2344
  var REPLACE_DECLINED = "Nothing was changed. Run again and answer yes to replace them, or remove those files first.";
1807
2345
  var REPLACE_NEEDS_FORCE = (paths) => `These files exist and were not added by designsource: ${paths.join(", ")}. Pass --force to replace them.`;
1808
2346
  var UNKNOWN_COMPONENTS = (names) => `Unknown component(s): ${names.join(", ")}. Run without names to pick from the list.`;
2347
+ var SECTION_CONFLICT = (reason) => `Skipped the /design-system section: ${reason}.`;
1809
2348
  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
2349
  var INSTALL_FAILED = (command) => `Installing libraries failed. The files were written; run this to finish: ${command}`;
1811
2350
  var UnknownComponentsError = class extends CliError {
@@ -1837,9 +2376,19 @@ function nonInteractiveQuestions(args) {
1837
2376
  function defaultTargets(root, info) {
1838
2377
  const cssFile = findGlobalStylesheet(info);
1839
2378
  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 };
2379
+ const src = join5(root, "src");
2380
+ const prefix = existsSync8(src) && statSync2(src).isDirectory() ? "src/" : "";
2381
+ const utilsFile = `${prefix}lib/utils.ts`;
2382
+ return {
2383
+ uiDir: `${prefix}components/ui`,
2384
+ utilsFile,
2385
+ cssFile,
2386
+ uiAlias: ALIASES.ui,
2387
+ utilsAlias: ALIASES.utils,
2388
+ componentsDir: `${prefix}components`,
2389
+ componentsAlias: ALIASES.components,
2390
+ ...libOf(utilsFile, ALIASES.utils)
2391
+ };
1843
2392
  }
1844
2393
  function assertSameTargets(planned, actual) {
1845
2394
  for (const key of Object.keys(planned)) {
@@ -1847,7 +2396,7 @@ function assertSameTargets(planned, actual) {
1847
2396
  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
2397
  }
1849
2398
  }
1850
- async function chooseComponents(input, manifest, before, questions) {
2399
+ async function chooseComponents(input, manifest, before, sectionOnDisk, questions) {
1851
2400
  const known = new Set(manifest.components.map((c) => c.name));
1852
2401
  const offered = manifest.components.map((c) => c.name).filter((n) => n !== PORTAL);
1853
2402
  const checked = (names) => {
@@ -1856,11 +2405,45 @@ async function chooseComponents(input, manifest, before, questions) {
1856
2405
  return [...new Set(names)];
1857
2406
  };
1858
2407
  if (input.components.length > 0) return checked(input.components);
1859
- if (input.all) return offered;
2408
+ if (input.all || sectionOnDisk) return offered;
1860
2409
  const earlier = before.filter((n) => known.has(n));
1861
2410
  if (earlier.length > 0) return earlier;
1862
2411
  return checked(await questions.pickComponents(offered));
1863
2412
  }
2413
+ var SECTION_FRAMEWORKS = ["next", "vite"];
2414
+ function sectionDecision(input) {
2415
+ const none = (note) => ({ write: false, blocks: "skip", note });
2416
+ if (!SECTION_FRAMEWORKS.includes(input.framework)) return none(null);
2417
+ if (input.framework === "next" && input.appDir === null) return none(NO_APP_ROUTER);
2418
+ const chosen = new Set(input.chosen);
2419
+ if (!input.allComponents.every((n) => chosen.has(n))) return none(input.present ? null : SECTION_NEEDS_FULL_KIT);
2420
+ const blocks = !input.present ? input.blocksWanted ? "write" : "skip" : input.blocksOnDisk ? input.blocksWanted ? "write" : "keep" : "skip";
2421
+ return { write: true, blocks, note: null };
2422
+ }
2423
+ function planSection(root, input, info, t, manifest, chosen, onDisk) {
2424
+ const none = (note) => ({ decision: { write: false, blocks: "skip", note }, files: () => [], paths: [], packages: {}, blockCount: 0 });
2425
+ const section = manifest.section;
2426
+ if (!section) return none(null);
2427
+ const appDir = info.framework === "next" ? nextAppDir(root) : null;
2428
+ const own = appDir === null ? null : ownDesignSystemRoute(root, appDir);
2429
+ if (own) return none(OWN_DESIGN_SYSTEM_ROUTE(own));
2430
+ const { present, blocksOnDisk, blockIds } = onDisk;
2431
+ const allComponents = manifest.components.map((c) => c.name).filter((n) => n !== PORTAL);
2432
+ const decision = sectionDecision({ chosen, allComponents, present, blocksOnDisk, blocksWanted: input.blocks ?? true, framework: info.framework, appDir });
2433
+ if (!decision.write) return none(decision.note);
2434
+ if (t.componentsDir === null) return none(NO_COMPONENTS_DIR(t.componentsAlias));
2435
+ if (!t.libAlias) return none(NO_LIB_ALIAS(t.utilsAlias));
2436
+ const framework = info.framework === "vite" ? "vite" : "next";
2437
+ const srcDir = existsSync8(join5(root, "src")) ? "src" : "";
2438
+ const files = (darkMarker) => planSectionFiles({ framework, appDir, srcDir, targets: t, manifest, blocks: decision.blocks, keptBlockIds: blockIds, darkMarker });
2439
+ return {
2440
+ decision,
2441
+ files,
2442
+ paths: files({ kind: "class", name: "dark" }).map((f) => f.path),
2443
+ packages: { ...section.packages, ...decision.blocks === "write" ? section.blockPackages : {} },
2444
+ blockCount: shownBlockGroups(section.blockGroups, decision.blocks, blockIds).reduce((n, g) => n + g.blocks.length, 0)
2445
+ };
2446
+ }
1864
2447
  function installCommands(info, manifest, install) {
1865
2448
  const lacks = (pkg) => info.deps[pkg] === void 0;
1866
2449
  const runtime = { ...install };
@@ -1883,16 +2466,41 @@ async function runAdd(input, deps) {
1883
2466
  assertCanAdd(info);
1884
2467
  const planned = info.shadcn ? resolveTargets(root, info.shadcn) : defaultTargets(root, info);
1885
2468
  const cssAbs = resolveInside(root, planned.cssFile);
1886
- if (!existsSync7(cssAbs)) throw new CliError(NO_THEME_FILE(planned.cssFile));
2469
+ if (!existsSync8(cssAbs)) throw new CliError(NO_THEME_FILE(planned.cssFile));
1887
2470
  assertKitUtils(root, info, planned);
1888
2471
  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);
2472
+ const onDisk = sectionPresent(root, planned);
2473
+ const chosen = await chooseComponents(input, manifest, previouslyAdded(root, planned), onDisk.present, deps.questions);
2474
+ const section = planSection(root, input, info, planned, manifest, chosen, onDisk);
2475
+ let packages = planPackages(chosen, manifest, info.deps);
2476
+ let sectionNote = section.decision.note;
2477
+ let writeSection = section.decision.write;
2478
+ if (writeSection) {
2479
+ const withSection = planPackages(chosen, manifest, info.deps, section.packages);
2480
+ const blocking = packages.skipped[0]?.reason ?? (withSection.extraConflicts[0] ? reasonFor(withSection.extraConflicts[0]) : null);
2481
+ if (blocking) {
2482
+ writeSection = false;
2483
+ sectionNote = SECTION_CONFLICT(blocking);
2484
+ } else packages = withSection;
2485
+ }
1891
2486
  const plan = planFiles(root, planned, componentClosure(packages.components, manifest), manifest);
2487
+ const sectionStatus = (writeSection ? section.paths : []).filter((p) => !p.endsWith(".json")).map((p) => [p, existingFileStatus(resolveInside(root, p))]);
1892
2488
  const setup = planSetup(info, manifest, deps.exec);
1893
- if (plan.replaceForeign.length > 0 && !await deps.questions.confirmReplace(plan.replaceForeign)) throw new CliError(REPLACE_DECLINED);
2489
+ if (writeSection && info.framework === "vite") {
2490
+ try {
2491
+ const step = listViteInputStep(info);
2492
+ if (step) setup.steps.push(step);
2493
+ } catch (e) {
2494
+ if (!(e instanceof CliError)) throw e;
2495
+ sectionNote = VITE_INPUT_MANUAL;
2496
+ }
2497
+ }
2498
+ const replaceForeign = [...plan.replaceForeign, ...sectionStatus.filter(([, s]) => s === "foreign").map(([p]) => p)];
2499
+ if (replaceForeign.length > 0 && !await deps.questions.confirmReplace(replaceForeign)) throw new CliError(REPLACE_DECLINED);
1894
2500
  const kept = [];
1895
- for (const path of plan.edited) if (await deps.questions.keepEdits(path)) kept.push(path);
2501
+ for (const path of [...plan.edited, ...sectionStatus.filter(([, s]) => s === "edited").map(([p]) => p)]) {
2502
+ if (await deps.questions.keepEdits(path)) kept.push(path);
2503
+ }
1896
2504
  const writes = plan.write.filter((w) => !kept.includes(w.path));
1897
2505
  if (!info.shadcn) deps.progress(NO_SHADCN);
1898
2506
  for (const step of setup.steps) {
@@ -1904,11 +2512,18 @@ async function runAdd(input, deps) {
1904
2512
  if (!written) throw new CliError("Setup did not leave a components.json. Run this again.");
1905
2513
  assertSameTargets(planned, resolveTargets(root, written));
1906
2514
  }
1907
- const sheet = readFileSync7(cssAbs, "utf8");
2515
+ const sheet = readFileSync8(cssAbs, "utf8");
2516
+ const dark = readDarkMarker(sheet);
2517
+ if (writeSection && info.framework !== "vite" && !dark.known) sectionNote = UNKNOWN_DARK(dark.selector ?? "");
2518
+ const sectionWrites = writeSection ? section.files(dark.marker).filter((f) => !kept.includes(f.path)) : [];
1908
2519
  const removeScaffolding = info.shadcn !== null || hasThemeRegion(sheet);
1909
2520
  const themed = applyTheme(sheet, manifest.theme, { preflight: setup.preflight, removeScaffolding });
1910
2521
  try {
1911
- writeFiles(root, [{ path: planned.cssFile, contents: themed.css }, ...writes.map(({ path, contents }) => ({ path, contents }))], { force: true, created: false });
2522
+ writeFiles(
2523
+ root,
2524
+ [{ path: planned.cssFile, contents: themed.css }, ...[...writes, ...sectionWrites].map(({ path, contents }) => ({ path, contents }))],
2525
+ { force: true, created: false }
2526
+ );
1912
2527
  } catch (e) {
1913
2528
  if (!(e instanceof CliError) || setup.steps.length === 0) throw e;
1914
2529
  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 +2532,7 @@ async function runAdd(input, deps) {
1917
2532
  const added = writes.filter((w) => w.component !== "utils").map((w) => w.component);
1918
2533
  const shown = added.filter((n) => n !== PORTAL).length;
1919
2534
  if (shown > 0) deps.progress(`Adding ${shown} component${shown === 1 ? "" : "s"}\u2026 \u2713`);
2535
+ if (writeSection) deps.progress("Adding the /design-system section\u2026 \u2713");
1920
2536
  const commands = installCommands(info, manifest, packages.install);
1921
2537
  const installCommand = commands.map(printedCommand).join(" && ") || null;
1922
2538
  if (installCommand && input.skipInstall) deps.progress(`Skipped installing libraries. Run: ${installCommand}`);
@@ -1938,18 +2554,29 @@ async function runAdd(input, deps) {
1938
2554
  projectName: manifest.name,
1939
2555
  replacedTheme: themed.replacedShadcnTheme,
1940
2556
  collisions: themed.collisions,
1941
- uiAlias: planned.uiAlias
2557
+ uiAlias: planned.uiAlias,
2558
+ section: writeSection ? {
2559
+ path: info.framework === "vite" ? "/design-system.html" : "/design-system",
2560
+ blocks: section.blockCount,
2561
+ ...section.decision.blocks === "keep" ? { blocksLeftInPlace: true } : {}
2562
+ } : null,
2563
+ sectionNote
1942
2564
  };
1943
2565
  }
1944
2566
 
1945
2567
  // src/add/summary.ts
1946
- function summaryLines(r) {
2568
+ 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"}.`;
2569
+ var sectionNoteFor = (note, reader) => reader === "agent" && note === SECTION_NEEDS_FULL_KIT ? SECTION_NEEDS_FULL_KIT_FOR_AGENT : note;
2570
+ function summaryLines(r, reader = "cli") {
1947
2571
  return [
1948
2572
  ...r.replacedTheme ? [`Replaced the theme in ${r.themeFile}`] : [],
1949
2573
  ...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
2574
  ...r.skipped.map((s) => `Skipped ${s.name}: ${s.reason}`),
1951
2575
  ...r.kept.map((path) => `Kept your edits to ${path}`),
1952
2576
  ...r.gone.map((path) => `${path} is no longer in the kit; left it in place`),
2577
+ ...r.section?.blocksLeftInPlace ? [leftBlocksLine(r.section.blocks, reader)] : [],
2578
+ ...r.section ? [`Your design system: ${r.section.path}`] : [],
2579
+ ...r.sectionNote ? [sectionNoteFor(r.sectionNote, reader)] : [],
1953
2580
  `Done. Your components now use "${r.projectName}" from designsource.app.`,
1954
2581
  "Run it again any time to pull updates."
1955
2582
  ];
@@ -2212,13 +2839,13 @@ import { homedir } from "node:os";
2212
2839
 
2213
2840
  // src/connect/store.ts
2214
2841
  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";
2842
+ import { chmodSync, constants, copyFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync9, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
2843
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join6, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
2217
2844
  var WHERE = ["keychain", "secret-service", "dpapi", "file"];
2218
2845
  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");
2846
+ if (platform === "win32") return join6(env.APPDATA || join6(home, "AppData", "Roaming"), "designsource", "credentials.json");
2847
+ const config = env.XDG_CONFIG_HOME && isAbsolute2(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join6(home, ".config");
2848
+ return join6(config, "designsource", "credentials.json");
2222
2849
  }
2223
2850
  function isFileEntry(value) {
2224
2851
  if (typeof value !== "object" || value === null) return false;
@@ -2228,7 +2855,7 @@ function isFileEntry(value) {
2228
2855
  function readCredentials(path) {
2229
2856
  let text;
2230
2857
  try {
2231
- text = readFileSync8(path, "utf8");
2858
+ text = readFileSync9(path, "utf8");
2232
2859
  } catch {
2233
2860
  return { version: 1, projects: {} };
2234
2861
  }
@@ -2278,7 +2905,7 @@ function writeCredentials(path, data) {
2278
2905
  const dir = dirname2(path);
2279
2906
  mkdirSync2(dir, { recursive: true, mode: 448 });
2280
2907
  chmodSync(dir, 448);
2281
- const temp = join5(dir, `.credentials.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
2908
+ const temp = join6(dir, `.credentials.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
2282
2909
  try {
2283
2910
  writeFileSync3(temp, `${JSON.stringify(data, null, 2)}
2284
2911
  `, { mode: 384, flag: "wx" });
@@ -2537,13 +3164,14 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
2537
3164
  assertKitUtils(root, info, targets);
2538
3165
  let mode;
2539
3166
  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);
3167
+ const first = previouslyAdded(root, targets).every((n) => n === "utils") && !sectionPresent(root, targets).present;
3168
+ if (first) mode = await pick(PICK_QUESTION, ADD_MODES, 0);
2541
3169
  }
2542
3170
  const { token, entry } = await requireSavedToken(args.token, { cwd: root, store, interactive: terminal });
2543
3171
  const questions = interactive ? ttyQuestions(args, mode, io) : nonInteractiveQuestions(args);
2544
3172
  try {
2545
3173
  const result = await runAdd(
2546
- { root, token, api: apiFor(args, entry), components: args.components, skipInstall: args.skipInstall, all: args.all },
3174
+ { root, token, api: apiFor(args, entry), components: args.components, skipInstall: args.skipInstall, all: args.all, blocks: !args.noBlocks },
2547
3175
  { fetchImpl: io.fetchImpl, exec, questions, progress: (line) => io.stdout(`${line}
2548
3176
  `) }
2549
3177
  );
@@ -2557,9 +3185,9 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
2557
3185
  }
2558
3186
 
2559
3187
  // src/commands/connect.ts
2560
- import { accessSync, constants as constants2, existsSync as existsSync9, statSync as statSync3 } from "node:fs";
3188
+ import { accessSync, constants as constants2, existsSync as existsSync10, statSync as statSync3 } from "node:fs";
2561
3189
  import { homedir as homedir2 } from "node:os";
2562
- import { join as join7 } from "node:path";
3190
+ import { join as join8 } from "node:path";
2563
3191
 
2564
3192
  // src/connect/fetch-project.ts
2565
3193
  var RejectedTokenError = class extends CliError {
@@ -2587,12 +3215,12 @@ async function fetchProject(opts, fetchImpl = fetch) {
2587
3215
  }
2588
3216
 
2589
3217
  // 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) {
3218
+ import { existsSync as existsSync9 } from "node:fs";
3219
+ import { dirname as dirname3, isAbsolute as isAbsolute3, join as join7, relative as relative3, resolve as resolve4, sep as sep3 } from "node:path";
3220
+ function projectRoot(cwd, exists = existsSync9) {
2593
3221
  let dir = resolve4(cwd);
2594
3222
  for (; ; ) {
2595
- if (exists(join6(dir, ".git"))) return dir;
3223
+ if (exists(join7(dir, ".git"))) return dir;
2596
3224
  const parent = dirname3(dir);
2597
3225
  if (parent === dir) return resolve4(cwd);
2598
3226
  dir = parent;
@@ -2619,7 +3247,7 @@ function onPath(bin, env, platform) {
2619
3247
  const exts = windows ? ["", ...(env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""];
2620
3248
  return dirs.some(
2621
3249
  (dir) => exts.some((ext) => {
2622
- const file = join7(dir, bin + ext);
3250
+ const file = join8(dir, bin + ext);
2623
3251
  try {
2624
3252
  if (!statSync3(file).isFile()) return false;
2625
3253
  if (!windows) accessSync(file, constants2.X_OK);
@@ -2635,7 +3263,7 @@ function defaultConnectDeps(env) {
2635
3263
  const platform = process.platform;
2636
3264
  return {
2637
3265
  store: defaultStore(env),
2638
- detect: () => detectApps({ env, platform, home, exists: existsSync9, onPath: (bin) => onPath(bin, env, platform) }),
3266
+ detect: () => detectApps({ env, platform, home, exists: existsSync10, onPath: (bin) => onPath(bin, env, platform) }),
2639
3267
  credentialsPath: credentialsPath(env, platform, home)
2640
3268
  };
2641
3269
  }
@@ -2644,7 +3272,8 @@ var app = (id) => APPS.find((a) => a.id === id);
2644
3272
  var NO_APPS_FOUND = "No coding apps found. Pass --apps claude,cursor,vscode,codex,gemini.";
2645
3273
  var NO_APPS_PICKED = "No apps picked. Nothing was changed.";
2646
3274
  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) {
3275
+ function savedLine(name, where, file, reused) {
3276
+ if (reused) return `Using your saved token for "${name}" from ${whereFrom(where, file)} \u2713`;
2648
3277
  if (where === "keychain") return `Saved your token for "${name}" in the macOS keychain \u2713`;
2649
3278
  if (where === "secret-service") return `Saved your token for "${name}" in the system keyring \u2713`;
2650
3279
  if (where === "dpapi") return `Saved your token for "${name}" with Windows protection \u2713`;
@@ -2734,7 +3363,7 @@ async function runConnect(args, io, deps = defaultConnectDeps(process.env)) {
2734
3363
  }
2735
3364
  const changed = plans.filter(({ plan }) => plan.status === "create" || plan.status === "update").map(({ id }) => id);
2736
3365
  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)]);
3366
+ say([...backup, savedLine(project.name, entry.where, deps.credentialsPath, kept !== null), ...plans.flatMap(({ id, plan }) => appLines(id, plan)), ...closingLines(apps, changed)]);
2738
3367
  }
2739
3368
  function connectedApps(root, store) {
2740
3369
  const saved = store.byFolder(root);
@@ -2792,7 +3421,7 @@ async function runIntegrate(args, env, io, store) {
2792
3421
  import { createInterface as createInterface2 } from "node:readline";
2793
3422
 
2794
3423
  // src/version.ts
2795
- var VERSION = true ? "0.5.0" : "0.0.0-dev";
3424
+ var VERSION = true ? "0.6.0" : "0.0.0-dev";
2796
3425
 
2797
3426
  // src/mcp/jsonrpc.ts
2798
3427
  var PARSE_ERROR = -32700;
@@ -2894,11 +3523,12 @@ var MCP_EXEC_TIMEOUT_MS = 10 * 60 * 1e3;
2894
3523
  var UNKNOWN_FOR_AGENT = (names) => `Unknown component(s): ${names.join(", ")}. Call list_components for the names.`;
2895
3524
  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
3525
  async function addUiKit(args, ctx) {
2897
- const { components, replace_existing: replace } = args;
3526
+ const { components, replace_existing: replace, no_blocks: noBlocks } = args;
2898
3527
  if (components !== void 0 && !(Array.isArray(components) && components.every((c) => typeof c === "string"))) {
2899
3528
  return errorResult('"components" must be an array of component names.');
2900
3529
  }
2901
3530
  if (replace !== void 0 && typeof replace !== "boolean") return errorResult('"replace_existing" must be true or false.');
3531
+ if (noBlocks !== void 0 && typeof noBlocks !== "boolean") return errorResult('"no_blocks" must be true or false.');
2902
3532
  if (ctx.token === null) return errorResult(ctx.missingToken ?? MCP_TOKEN_REQUIRED);
2903
3533
  const root = resolveProjectFolder(ctx.cwd, ctx.projectFolders === null ? null : { folders: ctx.projectFolders });
2904
3534
  if (root === null) return errorResult(NOT_SURE_WHICH_FOLDER);
@@ -2914,14 +3544,14 @@ async function addUiKit(args, ctx) {
2914
3544
  const exec = (cmd, cmdArgs, opts) => ctx.exec(cmd, cmdArgs, { ...opts, timeoutMs: MCP_EXEC_TIMEOUT_MS });
2915
3545
  try {
2916
3546
  const result = await runAdd(
2917
- { root, token: ctx.token, api: ctx.api, components: components ?? [], skipInstall: false },
3547
+ { root, token: ctx.token, api: ctx.api, components: components ?? [], skipInstall: false, blocks: noBlocks !== true },
2918
3548
  { fetchImpl: ctx.fetchImpl, exec, questions, progress: (line) => progress.push(line) }
2919
3549
  );
2920
3550
  const written = result.added.filter((n) => n !== "preview-portal");
2921
3551
  return textResult(
2922
3552
  [
2923
3553
  ...progress,
2924
- ...summaryLines(result),
3554
+ ...summaryLines(result, "agent"),
2925
3555
  ...written.length > 0 ? [`Added: ${written.join(", ")}`] : [],
2926
3556
  `Next: import components from ${result.uiAlias} (for example: import { Button } from "${result.uiAlias}/button").`
2927
3557
  ].join("\n")
@@ -3053,12 +3683,13 @@ ${files.join("\n\n")}`);
3053
3683
  },
3054
3684
  {
3055
3685
  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.",
3686
+ 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
3687
  inputSchema: {
3058
3688
  type: "object",
3059
3689
  properties: {
3060
3690
  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." }
3691
+ replace_existing: { type: "boolean", description: "Replace component files that exist but were not added by designsource. Ask the user first." },
3692
+ 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
3693
  },
3063
3694
  additionalProperties: false
3064
3695
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "designsource",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "The DS source CLI: add your design system's UI kit to a React app (add), add the design system to any other app (integrate), start a new Next.js project from it (create), or serve it to a coding agent over MCP (mcp) — tokens, every component and your mockup page.",
5
5
  "license": "MIT",
6
6
  "repository": {