designsource 0.13.0 → 0.15.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 (2) hide show
  1. package/dist/index.js +969 -522
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1008,6 +1008,7 @@ var INTEGRATE_DEFAULT_FOLDER = ".";
1008
1008
  var USAGE = `designsource <command> [options] (also installed as: dss)
1009
1009
 
1010
1010
  Commands
1011
+ setup set up a design system in this folder: sign in, pick or make one, add the kit, set up your coding apps
1011
1012
  add [names\u2026] add your design system's UI kit to this React app (theme, components, libraries)
1012
1013
  connect connect your coding apps (Claude Code, Cursor, VS Code, Codex, Gemini CLI) to this design system
1013
1014
  login sign in for coding agents, so your agent can create design systems from this folder
@@ -1016,7 +1017,7 @@ Commands
1016
1017
  create [folder] new Next.js project with the tokens, every component and your mockup page (default folder: ${CREATE_DEFAULT_FOLDER})
1017
1018
  mcp serve the design system to a coding agent over MCP (stdio) \u2014 for .mcp.json, not for a terminal
1018
1019
 
1019
- Run a command with --help for its options. In a terminal, no command shows a menu.
1020
+ Run a command with --help for its options. In a terminal, no command runs setup; --menu shows the list of commands.
1020
1021
  `;
1021
1022
  var TOKEN_LINE = " --token the project token (workbench \u2192 Project settings); or DS_SYNC_TOKEN";
1022
1023
  var API_LINE = ` --api API origin (default ${DEFAULT_API_ORIGIN})`;
@@ -1038,7 +1039,7 @@ ${TOKEN_LINE}
1038
1039
  ${API_LINE}
1039
1040
  --force overwrite files the bundle writes when design-system/ already exists
1040
1041
  `;
1041
- var ADD_USAGE = `designsource add [names\u2026] [--yes] [--all] [--force] [--skip-install] [--no-blocks] [--screen <name>|all|shell|site] [--token <project token>] [--api <origin>]
1042
+ var ADD_USAGE = `designsource add [names\u2026] [--yes] [--all] [--force] [--skip-install] [--blocks] [--no-blocks] [--screen <name>|all|shell|site] [--token <project token>] [--api <origin>]
1042
1043
 
1043
1044
  Adds your design system's UI kit to the React app in this folder: the theme in its global stylesheet, the
1044
1045
  components and the libraries they import. Sets up Tailwind and the shadcn config when the app has none.
@@ -1050,11 +1051,13 @@ your components, blocks and sample pages.
1050
1051
  --yes no questions (also outside a terminal): all components on a first run, edited files kept
1051
1052
  --force replace component files add did not write, and edited ones
1052
1053
  --skip-install write the files, then print the install command instead of running it
1054
+ --blocks add the blocks and their libraries to a /design-system section that has none
1053
1055
  --no-blocks the /design-system section without its blocks and their libraries (blocks already there stay)
1054
1056
  --screen screens and pages from DS source, by file name (repeatable, or comma-separated); all for every one;
1055
1057
  shell for a sidebar app shell listing the screens in the app; site for the menu and footer around
1056
1058
  the pages in the app
1057
- --token the project token (workbench \u2192 Project settings); or DS_SYNC_TOKEN
1059
+ --token the project token (workbench \u2192 Project settings); or DS_SYNC_TOKEN. Without one, the token saved by
1060
+ connect, else the sign-in from login when this folder is linked to a design system
1058
1061
  --api API origin (default ${DEFAULT_API_ORIGIN})
1059
1062
  `;
1060
1063
  var APP_IDS = APPS.map((a) => a.id);
@@ -1093,6 +1096,17 @@ settings here. The settings hold no token, so they are safe to commit. Run it on
1093
1096
  --yes no questions: the apps found on this computer (also outside a terminal)
1094
1097
  ${API_LINE}; outside a terminal only the default or a server on this computer
1095
1098
  `;
1099
+ var SETUP_USAGE = `designsource setup [--api <origin>]
1100
+ designsource --menu
1101
+
1102
+ Sets up a design system in this folder, asking only what it cannot tell: signs you in (a code to enter at
1103
+ ${DEFAULT_API_ORIGIN}/device, once per computer), picks or makes the design system, adds the UI kit and the
1104
+ /design-system section to a React app (a design-system/ folder for other stacks, a new Next.js app in an empty
1105
+ folder) and connects your coding apps. Needs a terminal; scripts use add, connect or login. Typing npx designsource
1106
+ with no command runs it.
1107
+ --menu the list of commands instead
1108
+ ${API_LINE}
1109
+ `;
1096
1110
  var LOGOUT_USAGE = `designsource logout [--api <origin>]
1097
1111
 
1098
1112
  Revokes this computer's sign-in on the server and removes it, with its trusted folders, from this computer.
@@ -1102,6 +1116,7 @@ ${API_LINE}
1102
1116
  function usageFor(verb) {
1103
1117
  if (verb === "login") return LOGIN_USAGE;
1104
1118
  if (verb === "logout") return LOGOUT_USAGE;
1119
+ if (verb === "setup") return SETUP_USAGE;
1105
1120
  return verb === "add" ? ADD_USAGE : verb === "connect" ? CONNECT_USAGE : verb === "create" ? CREATE_USAGE : verb === "integrate" ? INTEGRATE_USAGE : verb === "mcp" ? MCP_USAGE : USAGE;
1106
1121
  }
1107
1122
  var ArgsError = class extends Error {
@@ -1117,11 +1132,16 @@ function baseArgs(env) {
1117
1132
  return args;
1118
1133
  }
1119
1134
  var HELP = /* @__PURE__ */ new Set(["--help", "-h", "help"]);
1120
- var USE_VERBS = "Use add, connect, login, logout, integrate, create or mcp.";
1135
+ var USE_VERBS = "Use setup, add, connect, login, logout, integrate, create or mcp.";
1121
1136
  function parseArgs(argv, env) {
1122
1137
  const [first, ...rest] = argv;
1123
- if (first === void 0) return { kind: "menu" };
1138
+ if (first === void 0) return { kind: "setup", args: { api: DEFAULT_API_ORIGIN, apiGiven: false }, bare: true };
1139
+ if (first === "--menu") {
1140
+ if (rest.length > 0) throw new ArgsError("--menu takes nothing after it", USAGE);
1141
+ return { kind: "menu" };
1142
+ }
1124
1143
  if (HELP.has(first)) return { kind: "help", verb: void 0 };
1144
+ if (first === "setup") return parseSetup(rest);
1125
1145
  if (first === "create" || first === "integrate") return parseVerb(first, rest, env);
1126
1146
  if (first === "mcp") return parseMcp(rest, env);
1127
1147
  if (first === "add") return parseAdd(rest, env);
@@ -1173,7 +1193,8 @@ function switchOf(arg, usage) {
1173
1193
  return true;
1174
1194
  }
1175
1195
  var unknownOption = (arg, usage) => new ArgsError(`Unknown option ${arg.name}`, usage);
1176
- var ADD_SWITCHES = /* @__PURE__ */ new Map([["yes", "yes"], ["all", "all"], ["force", "force"], ["skip-install", "skipInstall"], ["no-blocks", "noBlocks"]]);
1196
+ var ADD_SWITCHES = /* @__PURE__ */ new Map([["yes", "yes"], ["all", "all"], ["force", "force"], ["skip-install", "skipInstall"], ["no-blocks", "noBlocks"], ["blocks", "blocks"]]);
1197
+ var BLOCKS_BOTH = "--blocks and --no-blocks cannot be used together.";
1177
1198
  var SCREEN_NAME_MESSAGE = "--screen takes screen names from DS source (letters, digits and dashes), or all.";
1178
1199
  function screensIn(values, usage) {
1179
1200
  const words = values.flatMap((v) => v.split(",").map((w) => w.trim()));
@@ -1187,7 +1208,7 @@ function screensIn(values, usage) {
1187
1208
  return { ...names.length > 0 ? { screens: [...new Set(names)] } : {}, ...shell };
1188
1209
  }
1189
1210
  function parseAdd(argv, env) {
1190
- const args = { components: [], api: DEFAULT_API_ORIGIN, yes: false, all: false, force: false, skipInstall: false, noBlocks: false };
1211
+ const args = { components: [], api: DEFAULT_API_ORIGIN, yes: false, all: false, force: false, skipInstall: false, noBlocks: false, blocks: false };
1191
1212
  if (env.DS_SYNC_TOKEN) args.token = env.DS_SYNC_TOKEN;
1192
1213
  const screenValues = [];
1193
1214
  for (const arg of scan(argv, ["token", "api", "screen"], [...ADD_SWITCHES.keys()])) {
@@ -1207,6 +1228,7 @@ function parseAdd(argv, env) {
1207
1228
  }
1208
1229
  }
1209
1230
  if (screenValues.length) Object.assign(args, screensIn(screenValues, ADD_USAGE));
1231
+ if (args.blocks && args.noBlocks) throw new ArgsError(BLOCKS_BOTH, ADD_USAGE);
1210
1232
  return { kind: "add", args };
1211
1233
  }
1212
1234
  function appsIn(value, usage = CONNECT_USAGE) {
@@ -1242,6 +1264,17 @@ function parseLogout(argv) {
1242
1264
  }
1243
1265
  return { kind: "logout", args };
1244
1266
  }
1267
+ function parseSetup(argv) {
1268
+ const args = { api: DEFAULT_API_ORIGIN, apiGiven: false };
1269
+ for (const arg of scan(argv, ["api"], [])) {
1270
+ if (arg.kind === "help") return { kind: "help", verb: "setup" };
1271
+ if (arg.kind === "positional") throw new ArgsError("setup takes no folder: run it in the app's folder", SETUP_USAGE);
1272
+ if (arg.known === null) throw unknownOption(arg, SETUP_USAGE);
1273
+ args.api = parseApiOrigin(valueOf(arg, SETUP_USAGE), SETUP_USAGE);
1274
+ args.apiGiven = true;
1275
+ }
1276
+ return { kind: "setup", args, bare: false };
1277
+ }
1245
1278
  function parseConnect(argv, env) {
1246
1279
  const args = { api: DEFAULT_API_ORIGIN, yes: false, forget: false };
1247
1280
  if (env.DS_SYNC_TOKEN) args.token = env.DS_SYNC_TOKEN;
@@ -3484,13 +3517,15 @@ function selectScreens(query, explicit, manifest, appDeps) {
3484
3517
  return selection;
3485
3518
  }
3486
3519
  var SECTION_FRAMEWORKS = ["next", "vite"];
3520
+ var BLOCKS_NOT_ADDED = "No blocks were added: they go into the /design-system section, which only a run with every component writes. Run designsource add --blocks with no component names.";
3521
+ var BLOCKS_NOT_ADDED_FOR_AGENT = "No blocks were added: they go into the /design-system section, which only a call with every component writes. Call add_ui_kit with blocks: true and no components.";
3487
3522
  function sectionDecision(input) {
3488
3523
  const none = (note) => ({ write: false, blocks: "skip", note });
3489
3524
  if (!SECTION_FRAMEWORKS.includes(input.framework)) return none(null);
3490
3525
  if (input.framework === "next" && input.appDir === null) return none(NO_APP_ROUTER);
3491
3526
  const chosen = new Set(input.chosen);
3492
3527
  if (!input.allComponents.every((n) => chosen.has(n))) return none(input.present ? null : SECTION_NEEDS_FULL_KIT);
3493
- const blocks = !input.present ? input.blocksWanted ? "write" : "skip" : input.blocksOnDisk ? input.blocksWanted ? "write" : "keep" : "skip";
3528
+ const blocks = !input.present ? input.blocksWanted ? "write" : "skip" : input.blocksOnDisk ? input.blocksWanted ? "write" : "keep" : input.addBlocks === true ? "write" : "skip";
3494
3529
  return { write: true, blocks, note: null };
3495
3530
  }
3496
3531
  function planSection(root, input, info, t, manifest, chosen, onDisk, screens, screenLinks) {
@@ -3502,7 +3537,7 @@ function planSection(root, input, info, t, manifest, chosen, onDisk, screens, sc
3502
3537
  if (own) return none(OWN_DESIGN_SYSTEM_ROUTE(own));
3503
3538
  const { present, blocksOnDisk, blockIds } = onDisk;
3504
3539
  const allComponents = manifest.components.map((c) => c.name).filter((n) => n !== PORTAL);
3505
- const decision = sectionDecision({ chosen, allComponents, present, blocksOnDisk, blocksWanted: input.blocks ?? true, framework: info.framework, appDir });
3540
+ const decision = sectionDecision({ chosen, allComponents, present, blocksOnDisk, blocksWanted: input.blocks ?? true, addBlocks: input.addBlocks, framework: info.framework, appDir });
3506
3541
  if (!decision.write) return none(decision.note);
3507
3542
  if (t.componentsDir === null) return none(NO_COMPONENTS_DIR(t.componentsAlias));
3508
3543
  if (!t.libAlias) return none(NO_LIB_ALIAS(t.utilsAlias));
@@ -3592,6 +3627,7 @@ async function runAdd(input, deps) {
3592
3627
  sectionNote = SECTION_CONFLICT(blocking);
3593
3628
  } else packages = withSection;
3594
3629
  }
3630
+ if (input.addBlocks && sectionNote === null && !(writeSection && section.decision.blocks === "write")) sectionNote = BLOCKS_NOT_ADDED;
3595
3631
  const shellBlocker = shellPlan === null ? null : SHELL_COMPONENTS.map(
3596
3632
  (name) => !manifest.components.some((c) => c.name === name) ? SHELL_NOT_IN_KIT(name) : packages.skipped.find((k) => k.name === name)?.reason ?? null
3597
3633
  ).find((r) => r !== null) ?? null;
@@ -3718,7 +3754,7 @@ async function runAdd(input, deps) {
3718
3754
 
3719
3755
  // src/add/summary.ts
3720
3756
  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"}.`;
3721
- var sectionNoteFor = (note, reader) => reader === "agent" && note === SECTION_NEEDS_FULL_KIT ? SECTION_NEEDS_FULL_KIT_FOR_AGENT : note;
3757
+ var sectionNoteFor = (note, reader) => reader !== "agent" ? note : note === SECTION_NEEDS_FULL_KIT ? SECTION_NEEDS_FULL_KIT_FOR_AGENT : note === BLOCKS_NOT_ADDED ? BLOCKS_NOT_ADDED_FOR_AGENT : note;
3722
3758
  var screenSkipLine = (s, reader) => screenSkipText(s.slug, reader === "agent" && s.agentReason ? s.agentReason : s.reason);
3723
3759
  var GET_SITE_SHELL = {
3724
3760
  cli: "Get <SiteShell> with npx designsource add --screen site.",
@@ -3761,398 +3797,108 @@ function summaryLines(r, reader = "cli") {
3761
3797
  ];
3762
3798
  }
3763
3799
 
3764
- // src/connect/api-for.ts
3765
- var SAVED_TOKEN_OTHER_SERVER = (name, saved, asked) => `The saved token for "${name}" was connected to ${saved}, so designsource will not send it to ${asked}. Pass --token for that server, or leave out --api.`;
3766
- var UNTRUSTED_SERVER = (asked) => `designsource will not send a token to ${asked}: that server was never connected on this computer. If you trust it, run npx designsource connect --api ${asked} in your project folder yourself.`;
3767
- function apiFor(args, saved) {
3768
- if (!saved) return args.api;
3769
- if (!args.apiGiven) return saved.api ?? args.api;
3770
- const origin = saved.api ?? DEFAULT_API_ORIGIN;
3771
- if (!sameApi(args.api, origin)) throw new CliError(SAVED_TOKEN_OTHER_SERVER(saved.name, origin, args.api));
3772
- return origin;
3773
- }
3774
- function givenTokenApi(args, entry) {
3775
- if (!args.apiGiven) return entry?.api ?? args.api;
3776
- const trusted = sameApi(args.api, DEFAULT_API_ORIGIN) || isLoopback(args.api) || entry?.api !== void 0 && sameApi(args.api, entry.api);
3777
- if (!trusted) throw new CliError(UNTRUSTED_SERVER(args.api));
3778
- return args.api;
3800
+ // src/connect/account-link.ts
3801
+ import { homedir } from "node:os";
3802
+
3803
+ // src/connect/account-store.ts
3804
+ import { createHash as createHash2 } from "node:crypto";
3805
+ import { readFileSync as readFileSync11, realpathSync as realpathSync2 } from "node:fs";
3806
+ import { dirname as dirname3, join as join7, parse, resolve as resolve4, sep as sep3 } from "node:path";
3807
+
3808
+ // src/connect/store.ts
3809
+ import { randomBytes } from "node:crypto";
3810
+ import { chmodSync, constants, copyFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync10, realpathSync, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
3811
+ import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join6, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
3812
+ var WHERE = ["keychain", "secret-service", "dpapi", "file"];
3813
+ function credentialsPath(env, platform, home) {
3814
+ if (platform === "win32") return join6(env.APPDATA || join6(home, "AppData", "Roaming"), "designsource", "credentials.json");
3815
+ const config = env.XDG_CONFIG_HOME && isAbsolute2(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join6(home, ".config");
3816
+ return join6(config, "designsource", "credentials.json");
3779
3817
  }
3780
- function sameApi(a, b) {
3781
- const key = (value) => {
3782
- try {
3783
- const url = new URL(value);
3784
- if (url.username || url.password) return null;
3785
- return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
3786
- } catch {
3787
- return null;
3788
- }
3789
- };
3790
- const ka = key(a);
3791
- return ka !== null && ka === key(b);
3818
+ function isFileEntry(value) {
3819
+ if (typeof value !== "object" || value === null) return false;
3820
+ const e = value;
3821
+ return typeof e.name === "string" && Array.isArray(e.folders) && e.folders.every((f) => typeof f === "string") && WHERE.includes(e.where) && (e.secret === void 0 || typeof e.secret === "string") && (e.api === void 0 || typeof e.api === "string");
3792
3822
  }
3793
- function isLoopback(value) {
3794
- let host;
3823
+ function readCredentials(path) {
3824
+ let text;
3795
3825
  try {
3796
- host = new URL(value).hostname;
3826
+ text = readFileSync10(path, "utf8");
3797
3827
  } catch {
3798
- return false;
3828
+ return { version: 1, projects: {} };
3799
3829
  }
3800
- return host === "localhost" || host.endsWith(".localhost") || /^127(?:\.\d{1,3}){3}$/.test(host) || host === "[::1]";
3801
- }
3802
-
3803
- // src/picker.ts
3804
- import { emitKeypressEvents } from "node:readline";
3805
-
3806
- // src/prompts.ts
3807
- import { createInterface } from "node:readline";
3808
- var shared;
3809
- var closed = false;
3810
- var queued = [];
3811
- var waiting = [];
3812
- var EOF_MESSAGE = "No more input. Pass the answer as a flag (for example --token or DS_SYNC_TOKEN) when running without a terminal.";
3813
- function iface() {
3814
- if (shared) return shared;
3815
- const r = createInterface({ input: process.stdin, output: process.stdout, terminal: process.stdin.isTTY === true });
3816
- r.on("line", (line) => {
3817
- const next = waiting.shift();
3818
- if (next) next.resolve(line);
3819
- else queued.push(line);
3820
- });
3821
- r.on("close", () => {
3822
- closed = true;
3823
- while (waiting.length) waiting.shift().reject(new CliError(EOF_MESSAGE));
3824
- });
3825
- if (process.stdin.isTTY === true) {
3826
- r.on("SIGINT", () => {
3827
- process.stdout.write("\n");
3828
- closed = true;
3829
- while (waiting.length) waiting.shift().reject(new CliError(CANCELLED, 130));
3830
- r.close();
3831
- });
3830
+ let parsed;
3831
+ try {
3832
+ parsed = JSON.parse(text);
3833
+ } catch {
3834
+ return { version: 1, projects: {}, unreadable: true };
3832
3835
  }
3833
- shared = r;
3834
- return r;
3836
+ const raw = parsed;
3837
+ if (typeof raw !== "object" || raw === null || raw.version !== 1 || typeof raw.projects !== "object" || raw.projects === null) return { version: 1, projects: {}, unreadable: true };
3838
+ const projects = {};
3839
+ for (const [id, entry] of Object.entries(raw.projects)) if (isFileEntry(entry)) projects[id] = entry;
3840
+ return { version: 1, projects };
3835
3841
  }
3836
- function hasInterface() {
3837
- return shared !== void 0;
3842
+ function stamp(d) {
3843
+ const p = (n) => String(n).padStart(2, "0");
3844
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
3838
3845
  }
3839
- function nextLine() {
3840
- iface();
3841
- const line = queued.shift();
3842
- if (line !== void 0) return Promise.resolve(line);
3843
- if (closed) return Promise.reject(new CliError(EOF_MESSAGE));
3844
- process.stdin.ref?.();
3845
- return new Promise((resolve10, reject) => waiting.push({
3846
- resolve: (line2) => {
3847
- process.stdin.unref?.();
3848
- resolve10(line2);
3849
- },
3850
- reject: (err) => {
3851
- process.stdin.unref?.();
3852
- reject(err);
3846
+ function backUp(path) {
3847
+ const base = `${path}.bak-${stamp(/* @__PURE__ */ new Date())}`;
3848
+ for (let n = 0; ; n++) {
3849
+ const target = n === 0 ? base : `${base}-${n}`;
3850
+ try {
3851
+ copyFileSync(path, target, constants.COPYFILE_EXCL);
3852
+ } catch (e) {
3853
+ if (e.code === "EEXIST") continue;
3854
+ throw e;
3853
3855
  }
3854
- }));
3855
- }
3856
- function promptLine(promptText, fallback) {
3857
- const r = iface();
3858
- r.setPrompt(promptText);
3859
- r.prompt();
3860
- return nextLine().then((a) => a.trim() || fallback);
3861
- }
3862
- function ask(question, fallback) {
3863
- return promptLine(`${question} (${fallback}) `, fallback);
3864
- }
3865
- async function confirm(question, defaultYes = false) {
3866
- const answer = await promptLine(`${question} ${defaultYes ? "(Y/n)" : "(y/N)"} `, "");
3867
- return /^y/i.test(answer) ? true : /^n/i.test(answer) ? false : defaultYes;
3868
- }
3869
- function askLine(question) {
3870
- return promptLine(`${question} `, "");
3871
- }
3872
- async function askChoice(question, options, defaultIndex) {
3873
- const list = options.map((o, i) => ` ${i + 1}) ${o}${i === defaultIndex ? " (default)" : ""}`).join("\n");
3874
- process.stdout.write(`${question}
3875
- ${list}
3876
- `);
3877
- for (; ; ) {
3878
- const answer = await ask("Choice", String(defaultIndex + 1));
3879
- const idx = Number(answer) - 1;
3880
- const byName = options.indexOf(answer);
3881
- if (byName !== -1) return options[byName];
3882
- if (Number.isInteger(idx) && options[idx] !== void 0) return options[idx];
3883
- process.stdout.write(`Pick 1-${options.length}.
3884
- `);
3856
+ chmodSync(target, 384);
3857
+ return target;
3885
3858
  }
3886
3859
  }
3887
- async function askHidden(question) {
3888
- const r = iface();
3889
- const original = typeof r._writeToOutput === "function" ? r._writeToOutput.bind(r) : void 0;
3890
- if (!original) {
3891
- throw new CliError("Cannot hide input on this terminal. Pass --token or set DS_SYNC_TOKEN instead.");
3860
+ function detach(data, keep, folder) {
3861
+ let changed = false;
3862
+ for (const [id, entry] of Object.entries(data.projects)) {
3863
+ if (id === keep) continue;
3864
+ const folders = entry.folders.filter((f) => !isWithin(resolve3(f), folder));
3865
+ if (folders.length !== entry.folders.length) {
3866
+ entry.folders = folders;
3867
+ changed = true;
3868
+ }
3892
3869
  }
3893
- let muted = false;
3894
- r._writeToOutput = (s) => {
3895
- if (!muted) original(s);
3896
- };
3897
- r.setPrompt(`${question} `);
3898
- r.prompt();
3899
- muted = true;
3870
+ return changed;
3871
+ }
3872
+ function writeCredentials(path, data) {
3873
+ writePrivateJson(path, data);
3874
+ }
3875
+ function writePrivateJson(path, data) {
3876
+ const dir = dirname2(path);
3877
+ mkdirSync2(dir, { recursive: true, mode: 448 });
3878
+ chmodSync(dir, 448);
3879
+ const temp = join6(dir, `.${basename(path, ".json")}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
3900
3880
  try {
3901
- const a = await nextLine();
3902
- return a.trim();
3903
- } finally {
3904
- muted = false;
3905
- original("\n");
3906
- r._writeToOutput = original;
3881
+ writeFileSync3(temp, `${JSON.stringify(data, null, 2)}
3882
+ `, { mode: 384, flag: "wx" });
3883
+ chmodSync(temp, 384);
3884
+ renameSync(temp, path);
3885
+ } catch (e) {
3886
+ rmSync2(temp, { force: true });
3887
+ throw e;
3907
3888
  }
3908
3889
  }
3909
-
3910
- // src/picker.ts
3911
- function pick(question, options, defaultIndex = 0) {
3912
- if (!rawTerminal()) return askChoice(question, options.map((o) => o.value), defaultIndex);
3913
- return pickTty(question, options, defaultIndex, process.stdin, process.stdout);
3914
- }
3915
- function rawTerminal() {
3916
- const { stdin, stdout } = process;
3917
- return stdin.isTTY === true && stdout.isTTY === true && typeof stdin.setRawMode === "function" && !hasInterface();
3890
+ function publicEntry(projectId, e) {
3891
+ return { projectId, name: e.name, folders: [...e.folders], where: e.where, ...e.api === void 0 ? {} : { api: e.api } };
3918
3892
  }
3919
- function pickMany(question, options, preselected) {
3920
- if (!rawTerminal()) return pickManyNumbered(question, options, preselected);
3921
- return pickManyTty(question, options, preselected, process.stdin, process.stdout);
3893
+ function isWithin(folder, root) {
3894
+ const rel = relative2(root, folder);
3895
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute2(rel);
3922
3896
  }
3923
- async function pickManyNumbered(question, options, preselected) {
3924
- const list = options.map((o, i) => ` ${i + 1}) ${o.label}${preselected.includes(o.value) ? " (picked)" : ""}`).join("\n");
3925
- process.stdout.write(`${question}
3926
- ${list}
3927
- `);
3928
- const defaults = options.flatMap((o, i) => preselected.includes(o.value) ? [String(i + 1)] : []);
3929
- const fallback = defaults.length > 0 ? defaults.join(",") : "none";
3930
- for (; ; ) {
3931
- const answer = await ask("Choices", fallback);
3932
- if (answer === "none") return [];
3933
- const indexes = answer.split(/[\s,]+/).filter(Boolean).map((part) => {
3934
- const byValue = options.findIndex((o) => o.value === part.toLowerCase());
3935
- if (byValue !== -1) return byValue;
3936
- const byNumber = /^\d+$/.test(part) ? Number(part) - 1 : -1;
3937
- return options[byNumber] !== void 0 ? byNumber : -1;
3938
- });
3939
- if (indexes.length > 0 && !indexes.includes(-1)) return options.filter((_, i) => indexes.includes(i)).map((o) => o.value);
3940
- process.stdout.write(`Pick from 1-${options.length}, separated by commas.
3941
- `);
3942
- }
3943
- }
3944
- function pickTty(question, options, start, stdin, stdout) {
3945
- const color = !process.env.NO_COLOR;
3946
- const bold = (s) => color ? `\x1B[1m${s}\x1B[22m` : s;
3947
- const dim = (s) => color ? `\x1B[2m${s}\x1B[22m` : s;
3948
- const n = options.length;
3949
- let index = start;
3950
- const rows = () => options.map((o, i) => {
3951
- const label = i === index ? bold(o.label) : o.label;
3952
- return `${i === index ? "\u276F" : " "} ${label}${o.hint ? ` ${dim(o.hint)}` : ""}`;
3953
- });
3954
- const draw = (lines) => stdout.write(lines.map((l) => `\r\x1B[2K${l}`).join("\n") + "\n");
3955
- const up = () => stdout.write(`\x1B[${n + 1}A`);
3956
- emitKeypressEvents(stdin);
3957
- stdin.setRawMode(true);
3958
- stdin.resume();
3959
- stdout.write("\x1B[?25l");
3960
- draw([question, ...rows()]);
3961
- return new Promise((resolve10, reject) => {
3962
- const finish = (after) => {
3963
- stdin.off("keypress", onKey);
3964
- stdin.setRawMode(false);
3965
- stdin.pause();
3966
- after();
3967
- stdout.write("\x1B[?25h");
3968
- };
3969
- const onKey = (str, key = {}) => {
3970
- if (key.ctrl && key.name === "c" || key.name === "escape") {
3971
- finish(() => stdout.write("\n"));
3972
- reject(new CliError(CANCELLED, 130));
3973
- return;
3974
- }
3975
- if (key.name === "return" || key.name === "enter") {
3976
- const chosen = options[index];
3977
- finish(() => {
3978
- up();
3979
- stdout.write(`\r\x1B[J${question} ${chosen.label}
3980
- `);
3981
- });
3982
- resolve10(chosen.value);
3983
- return;
3984
- }
3985
- if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
3986
- else if (key.name === "down" || str === "j") index = (index + 1) % n;
3987
- else if (str && /^[1-9]$/.test(str) && Number(str) <= n) index = Number(str) - 1;
3988
- else return;
3989
- up();
3990
- draw([question, ...rows()]);
3991
- };
3992
- stdin.on("keypress", onKey);
3993
- });
3994
- }
3995
- function pickManyTty(question, options, preselected, stdin, stdout) {
3996
- const color = !process.env.NO_COLOR;
3997
- const bold = (s) => color ? `\x1B[1m${s}\x1B[22m` : s;
3998
- const dim = (s) => color ? `\x1B[2m${s}\x1B[22m` : s;
3999
- const n = options.length;
4000
- const ticked = options.map((o) => preselected.includes(o.value));
4001
- let index = 0;
4002
- const rows = () => options.map((o, i) => {
4003
- const label = i === index ? bold(o.label) : o.label;
4004
- return `${i === index ? "\u276F" : " "} ${ticked[i] ? "\u25C9" : "\u25EF"} ${label}${o.hint ? ` ${dim(o.hint)}` : ""}`;
4005
- });
4006
- const head = `${question} ${dim("space toggles, a all, enter confirms")}`;
4007
- const draw = (lines) => stdout.write(lines.map((l) => `\r\x1B[2K${l}`).join("\n") + "\n");
4008
- const up = () => stdout.write(`\x1B[${n + 1}A`);
4009
- emitKeypressEvents(stdin);
4010
- stdin.setRawMode(true);
4011
- stdin.resume();
4012
- stdout.write("\x1B[?25l");
4013
- draw([head, ...rows()]);
4014
- return new Promise((resolve10, reject) => {
4015
- const finish = (after) => {
4016
- stdin.off("keypress", onKey);
4017
- stdin.setRawMode(false);
4018
- stdin.pause();
4019
- after();
4020
- stdout.write("\x1B[?25h");
4021
- };
4022
- const onKey = (str, key = {}) => {
4023
- if (key.ctrl && key.name === "c" || key.name === "escape") {
4024
- finish(() => stdout.write("\n"));
4025
- reject(new CliError(CANCELLED, 130));
4026
- return;
4027
- }
4028
- if (key.name === "return" || key.name === "enter") {
4029
- const chosen = options.filter((_, i) => ticked[i]);
4030
- finish(() => {
4031
- up();
4032
- stdout.write(`\r\x1B[J${question} ${chosen.length > 0 ? chosen.map((o) => o.label).join(", ") : "none"}
4033
- `);
4034
- });
4035
- resolve10(chosen.map((o) => o.value));
4036
- return;
4037
- }
4038
- if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
4039
- else if (key.name === "down" || str === "j") index = (index + 1) % n;
4040
- else if (key.name === "space" || str === " ") ticked[index] = !ticked[index];
4041
- else if (str === "a") ticked.fill(!ticked.every(Boolean));
4042
- else return;
4043
- up();
4044
- draw([head, ...rows()]);
4045
- };
4046
- stdin.on("keypress", onKey);
4047
- });
4048
- }
4049
-
4050
- // src/commands/scaffold.ts
4051
- import { resolve as resolve7 } from "node:path";
4052
-
4053
- // src/connect/resolve-token.ts
4054
- import { homedir } from "node:os";
4055
- import { join as join10, relative as relative4 } from "node:path";
4056
-
4057
- // src/connect/account-store.ts
4058
- import { createHash as createHash2 } from "node:crypto";
4059
- import { readFileSync as readFileSync11, realpathSync as realpathSync2 } from "node:fs";
4060
- import { dirname as dirname3, join as join7, parse, resolve as resolve4, sep as sep3 } from "node:path";
4061
-
4062
- // src/connect/store.ts
4063
- import { randomBytes } from "node:crypto";
4064
- import { chmodSync, constants, copyFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync10, realpathSync, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
4065
- import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join6, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
4066
- var WHERE = ["keychain", "secret-service", "dpapi", "file"];
4067
- function credentialsPath(env, platform, home) {
4068
- if (platform === "win32") return join6(env.APPDATA || join6(home, "AppData", "Roaming"), "designsource", "credentials.json");
4069
- const config = env.XDG_CONFIG_HOME && isAbsolute2(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join6(home, ".config");
4070
- return join6(config, "designsource", "credentials.json");
4071
- }
4072
- function isFileEntry(value) {
4073
- if (typeof value !== "object" || value === null) return false;
4074
- const e = value;
4075
- return typeof e.name === "string" && Array.isArray(e.folders) && e.folders.every((f) => typeof f === "string") && WHERE.includes(e.where) && (e.secret === void 0 || typeof e.secret === "string") && (e.api === void 0 || typeof e.api === "string");
4076
- }
4077
- function readCredentials(path) {
4078
- let text;
4079
- try {
4080
- text = readFileSync10(path, "utf8");
4081
- } catch {
4082
- return { version: 1, projects: {} };
4083
- }
4084
- let parsed;
4085
- try {
4086
- parsed = JSON.parse(text);
4087
- } catch {
4088
- return { version: 1, projects: {}, unreadable: true };
4089
- }
4090
- const raw = parsed;
4091
- if (typeof raw !== "object" || raw === null || raw.version !== 1 || typeof raw.projects !== "object" || raw.projects === null) return { version: 1, projects: {}, unreadable: true };
4092
- const projects = {};
4093
- for (const [id, entry] of Object.entries(raw.projects)) if (isFileEntry(entry)) projects[id] = entry;
4094
- return { version: 1, projects };
4095
- }
4096
- function stamp(d) {
4097
- const p = (n) => String(n).padStart(2, "0");
4098
- return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
4099
- }
4100
- function backUp(path) {
4101
- const base = `${path}.bak-${stamp(/* @__PURE__ */ new Date())}`;
4102
- for (let n = 0; ; n++) {
4103
- const target = n === 0 ? base : `${base}-${n}`;
4104
- try {
4105
- copyFileSync(path, target, constants.COPYFILE_EXCL);
4106
- } catch (e) {
4107
- if (e.code === "EEXIST") continue;
4108
- throw e;
4109
- }
4110
- chmodSync(target, 384);
4111
- return target;
4112
- }
4113
- }
4114
- function detach(data, keep, folder) {
4115
- let changed = false;
4116
- for (const [id, entry] of Object.entries(data.projects)) {
4117
- if (id === keep) continue;
4118
- const folders = entry.folders.filter((f) => !isWithin(resolve3(f), folder));
4119
- if (folders.length !== entry.folders.length) {
4120
- entry.folders = folders;
4121
- changed = true;
4122
- }
4123
- }
4124
- return changed;
4125
- }
4126
- function writeCredentials(path, data) {
4127
- writePrivateJson(path, data);
4128
- }
4129
- function writePrivateJson(path, data) {
4130
- const dir = dirname2(path);
4131
- mkdirSync2(dir, { recursive: true, mode: 448 });
4132
- chmodSync(dir, 448);
4133
- const temp = join6(dir, `.${basename(path, ".json")}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
4134
- try {
4135
- writeFileSync3(temp, `${JSON.stringify(data, null, 2)}
4136
- `, { mode: 384, flag: "wx" });
4137
- chmodSync(temp, 384);
4138
- renameSync(temp, path);
4139
- } catch (e) {
4140
- rmSync2(temp, { force: true });
4141
- throw e;
4142
- }
4143
- }
4144
- function publicEntry(projectId, e) {
4145
- return { projectId, name: e.name, folders: [...e.folders], where: e.where, ...e.api === void 0 ? {} : { api: e.api } };
4146
- }
4147
- function isWithin(folder, root) {
4148
- const rel = relative2(root, folder);
4149
- return rel === "" || rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute2(rel);
4150
- }
4151
- function real(path) {
4152
- try {
4153
- return realpathSync(path);
4154
- } catch {
4155
- return resolve3(path);
3897
+ function real(path) {
3898
+ try {
3899
+ return realpathSync(path);
3900
+ } catch {
3901
+ return resolve3(path);
4156
3902
  }
4157
3903
  }
4158
3904
  function savedHolds(folder, saved) {
@@ -4430,49 +4176,428 @@ function oneLine(text) {
4430
4176
  const line = lines[0].trim();
4431
4177
  return /[\u0000-\u001f\u007f]/.test(line) ? null : line;
4432
4178
  }
4433
- function mainRepoRoot(root, fs = realWorktreeFs) {
4434
- const dotGit = join9(root, ".git");
4435
- const pointer = fs.readSmall(dotGit);
4436
- if (pointer === null) return null;
4437
- const line = oneLine(pointer);
4438
- if (line === null || !line.startsWith("gitdir:")) return null;
4439
- const target = line.slice("gitdir:".length).trim();
4440
- if (target === "") return null;
4441
- const gitdir = fs.realpath(isAbsolute4(target) ? target : resolve6(root, target));
4442
- if (gitdir === null) return null;
4443
- const worktrees = dirname5(gitdir);
4444
- if (basename2(worktrees) !== "worktrees") return null;
4445
- const commonText = fs.readSmall(join9(gitdir, "commondir"));
4446
- const commonLine = commonText === null ? null : oneLine(commonText);
4447
- if (commonLine === null) return null;
4448
- const common = fs.realpath(isAbsolute4(commonLine) ? commonLine : resolve6(gitdir, commonLine));
4449
- if (common === null || common !== dirname5(worktrees)) return null;
4450
- if (basename2(common) !== ".git") return null;
4451
- const backText = fs.readSmall(join9(gitdir, "gitdir"));
4452
- const backLine = backText === null ? null : oneLine(backText);
4453
- if (backLine === null || !isAbsolute4(backLine)) return null;
4454
- const back = fs.realpath(backLine);
4455
- const here = fs.realpath(dotGit);
4456
- if (back === null || here === null || back !== here) return null;
4457
- const main2 = fs.realpath(dirname5(common));
4458
- return main2 !== null && main2 !== fs.realpath(root) ? main2 : null;
4179
+ function mainRepoRoot(root, fs = realWorktreeFs) {
4180
+ const dotGit = join9(root, ".git");
4181
+ const pointer = fs.readSmall(dotGit);
4182
+ if (pointer === null) return null;
4183
+ const line = oneLine(pointer);
4184
+ if (line === null || !line.startsWith("gitdir:")) return null;
4185
+ const target = line.slice("gitdir:".length).trim();
4186
+ if (target === "") return null;
4187
+ const gitdir = fs.realpath(isAbsolute4(target) ? target : resolve6(root, target));
4188
+ if (gitdir === null) return null;
4189
+ const worktrees = dirname5(gitdir);
4190
+ if (basename2(worktrees) !== "worktrees") return null;
4191
+ const commonText = fs.readSmall(join9(gitdir, "commondir"));
4192
+ const commonLine = commonText === null ? null : oneLine(commonText);
4193
+ if (commonLine === null) return null;
4194
+ const common = fs.realpath(isAbsolute4(commonLine) ? commonLine : resolve6(gitdir, commonLine));
4195
+ if (common === null || common !== dirname5(worktrees)) return null;
4196
+ if (basename2(common) !== ".git") return null;
4197
+ const backText = fs.readSmall(join9(gitdir, "gitdir"));
4198
+ const backLine = backText === null ? null : oneLine(backText);
4199
+ if (backLine === null || !isAbsolute4(backLine)) return null;
4200
+ const back = fs.realpath(backLine);
4201
+ const here = fs.realpath(dotGit);
4202
+ if (back === null || here === null || back !== here) return null;
4203
+ const main2 = fs.realpath(dirname5(common));
4204
+ return main2 !== null && main2 !== fs.realpath(root) ? main2 : null;
4205
+ }
4206
+
4207
+ // src/connect/account-paths.ts
4208
+ function originOf(api) {
4209
+ normaliseOrigin(api);
4210
+ return new URL(api).origin;
4211
+ }
4212
+ function projectFolders(cwd) {
4213
+ const work = normaliseFolder(projectRoot(normaliseFolder(cwd)));
4214
+ const main2 = mainRepoRoot(work);
4215
+ return main2 === null ? { work, trust: work, worktree: false } : { work, trust: normaliseFolder(main2), worktree: true };
4216
+ }
4217
+
4218
+ // src/mcp/account-session.ts
4219
+ var NOT_SIGNED_IN_FOR = (root) => `designsource is not signed in for ${printable(root)}. Ask the user to run npx designsource login in a terminal in that folder, then restart this app. A sign-in there also covers its git worktrees.`;
4220
+ var SEVERAL_ACCOUNTS = "More than one designsource account is signed in on this computer; pass --api.";
4221
+ var NO_LINK = "No design system is linked to this folder yet. Call list_design_systems, then use_design_system with one of its ids, or call create_design_system to make a new one.";
4222
+ var ACCOUNT_TOKEN3 = /^dsa_[A-Za-z0-9_-]{43}$/;
4223
+ var PROJECT_ID3 = /^[A-Za-z0-9_-]+$/;
4224
+ var refuse = (message) => ({ kind: "none", message });
4225
+ function trustedFolderOf(entry, roots) {
4226
+ const trusted = (f) => entry.folders.some((saved) => normaliseFolder(saved) === f);
4227
+ const folder = trusted(roots.work) ? roots.work : trusted(roots.trust) ? roots.trust : null;
4228
+ if (folder === null) return null;
4229
+ const linked = Object.entries(entry.links).find(([f]) => normaliseFolder(f) === folder)?.[1];
4230
+ return { folder, projectId: linked !== void 0 && PROJECT_ID3.test(linked) ? linked : null };
4231
+ }
4232
+ function chooseAccount(api, apiGiven, accounts, notSignedIn) {
4233
+ if (apiGiven) {
4234
+ let origin;
4235
+ try {
4236
+ origin = originOf(api);
4237
+ } catch {
4238
+ return refuse(notSignedIn);
4239
+ }
4240
+ return accounts.get(origin) ?? refuse(notSignedIn);
4241
+ }
4242
+ const all = accounts.all();
4243
+ if (all.length === 1) return all[0];
4244
+ const fallback = accounts.get(DEFAULT_API_ORIGIN);
4245
+ if (fallback) return fallback;
4246
+ return refuse(all.length > 1 ? SEVERAL_ACCOUNTS : notSignedIn);
4247
+ }
4248
+ async function resolveAccount(input) {
4249
+ const { api, apiGiven, cwd, home, accounts } = input;
4250
+ const { work, trust } = projectFolders(cwd);
4251
+ const notSignedIn = NOT_SIGNED_IN_FOR(trust);
4252
+ const chosen = chooseAccount(api, apiGiven, accounts, notSignedIn);
4253
+ if ("kind" in chosen) return chosen;
4254
+ const homeDir = normaliseFolder(home);
4255
+ if (homeFolderRefusal(trust, homeDir) !== null || homeFolderRefusal(work, homeDir) !== null) return refuse(notSignedIn);
4256
+ const found = trustedFolderOf(chosen, { work, trust });
4257
+ if (found === null) return refuse(notSignedIn);
4258
+ const { folder, projectId } = found;
4259
+ if (input.requireLink === true && projectId === null) return refuse(NO_LINK);
4260
+ let token;
4261
+ try {
4262
+ token = await accounts.token(chosen.origin);
4263
+ } catch {
4264
+ return refuse(notSignedIn);
4265
+ }
4266
+ if (token === null || !ACCOUNT_TOKEN3.test(token)) return refuse(notSignedIn);
4267
+ return { kind: "account", origin: chosen.origin, email: chosen.email, token, folder, workFolder: work, projectId };
4268
+ }
4269
+
4270
+ // src/connect/account-link.ts
4271
+ function defaultAccountStore(env = process.env) {
4272
+ return createAccountStore({ env, platform: process.platform, exec: spawnExec, home: homedir() });
4273
+ }
4274
+ var ACCOUNT_OTHER_SERVER = (saved, asked) => `This folder's designsource sign-in was saved for ${saved}, so designsource will not send it to ${asked}. Pass --token for that server, or leave out --api.`;
4275
+ var accountProjectRoute = (projectId, kind) => `/api/agent/projects/${encodeURIComponent(projectId)}/${kind}`;
4276
+ var LINKED_PROJECT_GONE_CLI = "The design system linked to this folder is gone (deleted, or no longer in your account). Ask your coding agent to link another one, or pass --token with a project token.";
4277
+ function cliAccountMessageForResponse(status, body, api) {
4278
+ if (status === 401) return ACCOUNT_TOKEN_MESSAGE;
4279
+ if (status === 404) return LINKED_PROJECT_GONE_CLI;
4280
+ return messageForResponse(status, body, api);
4281
+ }
4282
+ async function linkedAccount(input) {
4283
+ const { cwd, api, apiGiven, accounts } = input;
4284
+ const home = input.home ?? homedir();
4285
+ if (apiGiven) {
4286
+ const asked = await resolveAccount({ api, apiGiven: true, cwd, home, accounts, requireLink: true });
4287
+ if (asked.kind === "account" && asked.projectId !== null) return { token: asked.token, origin: asked.origin, projectId: asked.projectId, email: asked.email };
4288
+ const other = await resolveAccount({ api, apiGiven: false, cwd, home, accounts, requireLink: true });
4289
+ if (other.kind === "account" && other.projectId !== null && other.origin !== safeOrigin(api)) {
4290
+ throw new CliError(ACCOUNT_OTHER_SERVER(other.origin, api));
4291
+ }
4292
+ return null;
4293
+ }
4294
+ const found = await resolveAccount({ api, apiGiven: false, cwd, home, accounts, requireLink: true });
4295
+ if (found.kind !== "account" || found.projectId === null) return null;
4296
+ return { token: found.token, origin: found.origin, projectId: found.projectId, email: found.email };
4297
+ }
4298
+ var safeOrigin = (api) => {
4299
+ try {
4300
+ return originOf(api);
4301
+ } catch {
4302
+ return null;
4303
+ }
4304
+ };
4305
+
4306
+ // src/connect/api-for.ts
4307
+ var SAVED_TOKEN_OTHER_SERVER = (name, saved, asked) => `The saved token for "${name}" was connected to ${saved}, so designsource will not send it to ${asked}. Pass --token for that server, or leave out --api.`;
4308
+ var UNTRUSTED_SERVER = (asked) => `designsource will not send a token to ${asked}: that server was never connected on this computer. If you trust it, run npx designsource connect --api ${asked} in your project folder yourself.`;
4309
+ function apiFor(args, saved) {
4310
+ if (!saved) return args.api;
4311
+ if (!args.apiGiven) return saved.api ?? args.api;
4312
+ const origin = saved.api ?? DEFAULT_API_ORIGIN;
4313
+ if (!sameApi(args.api, origin)) throw new CliError(SAVED_TOKEN_OTHER_SERVER(saved.name, origin, args.api));
4314
+ return origin;
4315
+ }
4316
+ function givenTokenApi(args, entry) {
4317
+ if (!args.apiGiven) return entry?.api ?? args.api;
4318
+ const trusted = sameApi(args.api, DEFAULT_API_ORIGIN) || isLoopback(args.api) || entry?.api !== void 0 && sameApi(args.api, entry.api);
4319
+ if (!trusted) throw new CliError(UNTRUSTED_SERVER(args.api));
4320
+ return args.api;
4321
+ }
4322
+ function sameApi(a, b) {
4323
+ const key = (value) => {
4324
+ try {
4325
+ const url = new URL(value);
4326
+ if (url.username || url.password) return null;
4327
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
4328
+ } catch {
4329
+ return null;
4330
+ }
4331
+ };
4332
+ const ka = key(a);
4333
+ return ka !== null && ka === key(b);
4334
+ }
4335
+ function isLoopback(value) {
4336
+ let host;
4337
+ try {
4338
+ host = new URL(value).hostname;
4339
+ } catch {
4340
+ return false;
4341
+ }
4342
+ return host === "localhost" || host.endsWith(".localhost") || /^127(?:\.\d{1,3}){3}$/.test(host) || host === "[::1]";
4343
+ }
4344
+
4345
+ // src/picker.ts
4346
+ import { emitKeypressEvents } from "node:readline";
4347
+
4348
+ // src/prompts.ts
4349
+ import { createInterface } from "node:readline";
4350
+ var shared;
4351
+ var closed = false;
4352
+ var queued = [];
4353
+ var waiting = [];
4354
+ var EOF_MESSAGE = "No more input. Pass the answer as a flag (for example --token or DS_SYNC_TOKEN) when running without a terminal.";
4355
+ function iface() {
4356
+ if (shared) return shared;
4357
+ const r = createInterface({ input: process.stdin, output: process.stdout, terminal: process.stdin.isTTY === true });
4358
+ r.on("line", (line) => {
4359
+ const next = waiting.shift();
4360
+ if (next) next.resolve(line);
4361
+ else queued.push(line);
4362
+ });
4363
+ r.on("close", () => {
4364
+ closed = true;
4365
+ while (waiting.length) waiting.shift().reject(new CliError(EOF_MESSAGE));
4366
+ });
4367
+ if (process.stdin.isTTY === true) {
4368
+ r.on("SIGINT", () => {
4369
+ process.stdout.write("\n");
4370
+ closed = true;
4371
+ while (waiting.length) waiting.shift().reject(new CliError(CANCELLED, 130));
4372
+ r.close();
4373
+ });
4374
+ }
4375
+ shared = r;
4376
+ return r;
4377
+ }
4378
+ function hasInterface() {
4379
+ return shared !== void 0;
4380
+ }
4381
+ function nextLine() {
4382
+ iface();
4383
+ const line = queued.shift();
4384
+ if (line !== void 0) return Promise.resolve(line);
4385
+ if (closed) return Promise.reject(new CliError(EOF_MESSAGE));
4386
+ process.stdin.ref?.();
4387
+ return new Promise((resolve10, reject) => waiting.push({
4388
+ resolve: (line2) => {
4389
+ process.stdin.unref?.();
4390
+ resolve10(line2);
4391
+ },
4392
+ reject: (err) => {
4393
+ process.stdin.unref?.();
4394
+ reject(err);
4395
+ }
4396
+ }));
4397
+ }
4398
+ function promptLine(promptText, fallback) {
4399
+ const r = iface();
4400
+ r.setPrompt(promptText);
4401
+ r.prompt();
4402
+ return nextLine().then((a) => a.trim() || fallback);
4403
+ }
4404
+ function ask(question, fallback) {
4405
+ return promptLine(`${question} (${fallback}) `, fallback);
4406
+ }
4407
+ async function confirm(question, defaultYes = false) {
4408
+ const answer = await promptLine(`${question} ${defaultYes ? "(Y/n)" : "(y/N)"} `, "");
4409
+ return /^y/i.test(answer) ? true : /^n/i.test(answer) ? false : defaultYes;
4410
+ }
4411
+ function askLine(question) {
4412
+ return promptLine(`${question} `, "");
4413
+ }
4414
+ async function askChoice(question, options, defaultIndex) {
4415
+ const list = options.map((o, i) => ` ${i + 1}) ${o}${i === defaultIndex ? " (default)" : ""}`).join("\n");
4416
+ process.stdout.write(`${question}
4417
+ ${list}
4418
+ `);
4419
+ for (; ; ) {
4420
+ const answer = await ask("Choice", String(defaultIndex + 1));
4421
+ const idx = Number(answer) - 1;
4422
+ const byName = options.indexOf(answer);
4423
+ if (byName !== -1) return options[byName];
4424
+ if (Number.isInteger(idx) && options[idx] !== void 0) return options[idx];
4425
+ process.stdout.write(`Pick 1-${options.length}.
4426
+ `);
4427
+ }
4428
+ }
4429
+ async function askHidden(question) {
4430
+ const r = iface();
4431
+ const original = typeof r._writeToOutput === "function" ? r._writeToOutput.bind(r) : void 0;
4432
+ if (!original) {
4433
+ throw new CliError("Cannot hide input on this terminal. Pass --token or set DS_SYNC_TOKEN instead.");
4434
+ }
4435
+ let muted = false;
4436
+ r._writeToOutput = (s) => {
4437
+ if (!muted) original(s);
4438
+ };
4439
+ r.setPrompt(`${question} `);
4440
+ r.prompt();
4441
+ muted = true;
4442
+ try {
4443
+ const a = await nextLine();
4444
+ return a.trim();
4445
+ } finally {
4446
+ muted = false;
4447
+ original("\n");
4448
+ r._writeToOutput = original;
4449
+ }
4450
+ }
4451
+
4452
+ // src/picker.ts
4453
+ function pick(question, options, defaultIndex = 0) {
4454
+ if (!rawTerminal()) return askChoice(question, options.map((o) => o.value), defaultIndex);
4455
+ return pickTty(question, options, defaultIndex, process.stdin, process.stdout);
4456
+ }
4457
+ function rawTerminal() {
4458
+ const { stdin, stdout } = process;
4459
+ return stdin.isTTY === true && stdout.isTTY === true && typeof stdin.setRawMode === "function" && !hasInterface();
4460
+ }
4461
+ function pickMany(question, options, preselected) {
4462
+ if (!rawTerminal()) return pickManyNumbered(question, options, preselected);
4463
+ return pickManyTty(question, options, preselected, process.stdin, process.stdout);
4464
+ }
4465
+ async function pickManyNumbered(question, options, preselected) {
4466
+ const list = options.map((o, i) => ` ${i + 1}) ${o.label}${preselected.includes(o.value) ? " (picked)" : ""}`).join("\n");
4467
+ process.stdout.write(`${question}
4468
+ ${list}
4469
+ `);
4470
+ const defaults = options.flatMap((o, i) => preselected.includes(o.value) ? [String(i + 1)] : []);
4471
+ const fallback = defaults.length > 0 ? defaults.join(",") : "none";
4472
+ for (; ; ) {
4473
+ const answer = await ask("Choices", fallback);
4474
+ if (answer === "none") return [];
4475
+ const indexes = answer.split(/[\s,]+/).filter(Boolean).map((part) => {
4476
+ const byValue = options.findIndex((o) => o.value === part.toLowerCase());
4477
+ if (byValue !== -1) return byValue;
4478
+ const byNumber = /^\d+$/.test(part) ? Number(part) - 1 : -1;
4479
+ return options[byNumber] !== void 0 ? byNumber : -1;
4480
+ });
4481
+ if (indexes.length > 0 && !indexes.includes(-1)) return options.filter((_, i) => indexes.includes(i)).map((o) => o.value);
4482
+ process.stdout.write(`Pick from 1-${options.length}, separated by commas.
4483
+ `);
4484
+ }
4485
+ }
4486
+ function pickTty(question, options, start, stdin, stdout) {
4487
+ const color = !process.env.NO_COLOR;
4488
+ const bold = (s) => color ? `\x1B[1m${s}\x1B[22m` : s;
4489
+ const dim = (s) => color ? `\x1B[2m${s}\x1B[22m` : s;
4490
+ const n = options.length;
4491
+ let index = start;
4492
+ const rows = () => options.map((o, i) => {
4493
+ const label = i === index ? bold(o.label) : o.label;
4494
+ return `${i === index ? "\u276F" : " "} ${label}${o.hint ? ` ${dim(o.hint)}` : ""}`;
4495
+ });
4496
+ const draw = (lines) => stdout.write(lines.map((l) => `\r\x1B[2K${l}`).join("\n") + "\n");
4497
+ const up = () => stdout.write(`\x1B[${n + 1}A`);
4498
+ emitKeypressEvents(stdin);
4499
+ stdin.setRawMode(true);
4500
+ stdin.resume();
4501
+ stdout.write("\x1B[?25l");
4502
+ draw([question, ...rows()]);
4503
+ return new Promise((resolve10, reject) => {
4504
+ const finish = (after) => {
4505
+ stdin.off("keypress", onKey);
4506
+ stdin.setRawMode(false);
4507
+ stdin.pause();
4508
+ after();
4509
+ stdout.write("\x1B[?25h");
4510
+ };
4511
+ const onKey = (str, key = {}) => {
4512
+ if (key.ctrl && key.name === "c" || key.name === "escape") {
4513
+ finish(() => stdout.write("\n"));
4514
+ reject(new CliError(CANCELLED, 130));
4515
+ return;
4516
+ }
4517
+ if (key.name === "return" || key.name === "enter") {
4518
+ const chosen = options[index];
4519
+ finish(() => {
4520
+ up();
4521
+ stdout.write(`\r\x1B[J${question} ${chosen.label}
4522
+ `);
4523
+ });
4524
+ resolve10(chosen.value);
4525
+ return;
4526
+ }
4527
+ if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
4528
+ else if (key.name === "down" || str === "j") index = (index + 1) % n;
4529
+ else if (str && /^[1-9]$/.test(str) && Number(str) <= n) index = Number(str) - 1;
4530
+ else return;
4531
+ up();
4532
+ draw([question, ...rows()]);
4533
+ };
4534
+ stdin.on("keypress", onKey);
4535
+ });
4536
+ }
4537
+ function pickManyTty(question, options, preselected, stdin, stdout) {
4538
+ const color = !process.env.NO_COLOR;
4539
+ const bold = (s) => color ? `\x1B[1m${s}\x1B[22m` : s;
4540
+ const dim = (s) => color ? `\x1B[2m${s}\x1B[22m` : s;
4541
+ const n = options.length;
4542
+ const ticked = options.map((o) => preselected.includes(o.value));
4543
+ let index = 0;
4544
+ const rows = () => options.map((o, i) => {
4545
+ const label = i === index ? bold(o.label) : o.label;
4546
+ return `${i === index ? "\u276F" : " "} ${ticked[i] ? "\u25C9" : "\u25EF"} ${label}${o.hint ? ` ${dim(o.hint)}` : ""}`;
4547
+ });
4548
+ const head = `${question} ${dim("space toggles, a all, enter confirms")}`;
4549
+ const draw = (lines) => stdout.write(lines.map((l) => `\r\x1B[2K${l}`).join("\n") + "\n");
4550
+ const up = () => stdout.write(`\x1B[${n + 1}A`);
4551
+ emitKeypressEvents(stdin);
4552
+ stdin.setRawMode(true);
4553
+ stdin.resume();
4554
+ stdout.write("\x1B[?25l");
4555
+ draw([head, ...rows()]);
4556
+ return new Promise((resolve10, reject) => {
4557
+ const finish = (after) => {
4558
+ stdin.off("keypress", onKey);
4559
+ stdin.setRawMode(false);
4560
+ stdin.pause();
4561
+ after();
4562
+ stdout.write("\x1B[?25h");
4563
+ };
4564
+ const onKey = (str, key = {}) => {
4565
+ if (key.ctrl && key.name === "c" || key.name === "escape") {
4566
+ finish(() => stdout.write("\n"));
4567
+ reject(new CliError(CANCELLED, 130));
4568
+ return;
4569
+ }
4570
+ if (key.name === "return" || key.name === "enter") {
4571
+ const chosen = options.filter((_, i) => ticked[i]);
4572
+ finish(() => {
4573
+ up();
4574
+ stdout.write(`\r\x1B[J${question} ${chosen.length > 0 ? chosen.map((o) => o.label).join(", ") : "none"}
4575
+ `);
4576
+ });
4577
+ resolve10(chosen.map((o) => o.value));
4578
+ return;
4579
+ }
4580
+ if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
4581
+ else if (key.name === "down" || str === "j") index = (index + 1) % n;
4582
+ else if (key.name === "space" || str === " ") ticked[index] = !ticked[index];
4583
+ else if (str === "a") ticked.fill(!ticked.every(Boolean));
4584
+ else return;
4585
+ up();
4586
+ draw([head, ...rows()]);
4587
+ };
4588
+ stdin.on("keypress", onKey);
4589
+ });
4459
4590
  }
4460
4591
 
4461
- // src/connect/account-paths.ts
4462
- function originOf(api) {
4463
- normaliseOrigin(api);
4464
- return new URL(api).origin;
4465
- }
4466
- function projectFolders(cwd) {
4467
- const work = normaliseFolder(projectRoot(normaliseFolder(cwd)));
4468
- const main2 = mainRepoRoot(work);
4469
- return main2 === null ? { work, trust: work, worktree: false } : { work, trust: normaliseFolder(main2), worktree: true };
4470
- }
4592
+ // src/commands/scaffold.ts
4593
+ import { resolve as resolve7 } from "node:path";
4471
4594
 
4472
4595
  // src/connect/resolve-token.ts
4596
+ import { homedir as homedir2 } from "node:os";
4597
+ import { join as join10, relative as relative4 } from "node:path";
4473
4598
  var NO_TOKEN_FOR_PROJECT = (nameOrId) => `This computer has no token for the "${nameOrId}" design system. Run npx designsource connect in the project folder.`;
4474
4599
  function defaultStore(env = process.env) {
4475
- return createStore({ env, platform: process.platform, exec: spawnExec, home: homedir() });
4600
+ return createStore({ env, platform: process.platform, exec: spawnExec, home: homedir2() });
4476
4601
  }
4477
4602
  var TERMINAL = { askHidden, pick: (q, options) => pick(q, options, 0) };
4478
4603
  async function resolveToken(input, prompts = TERMINAL) {
@@ -4527,7 +4652,7 @@ function validateManifest(json) {
4527
4652
  // src/fetch-manifest.ts
4528
4653
  async function fetchManifest(opts, fetchImpl = fetch) {
4529
4654
  const query = { framework: opts.framework, ...opts.name ? { name: opts.name } : {}, ...opts.screens ? { screens: opts.screens, pages: "1" } : {} };
4530
- return validateManifest(await getJson({ api: opts.api, token: opts.token, path: "/api/starter", query }, fetchImpl));
4655
+ return validateManifest(await getJson({ api: opts.api, token: opts.token, path: opts.path ?? "/api/starter", query, ...opts.messages ? { messages: opts.messages } : {} }, fetchImpl));
4531
4656
  }
4532
4657
 
4533
4658
  // src/package-name.ts
@@ -4584,11 +4709,21 @@ async function requireSavedToken(given, opts) {
4584
4709
  async function savedToken(given, opts) {
4585
4710
  return resolveToken({ given, cwd: opts.cwd, store: opts.store ?? defaultStore(), interactive: opts.interactive ?? isTerminal(), prompt: false });
4586
4711
  }
4712
+ async function savedOrLinked(args, opts) {
4713
+ const saved = await savedToken(args.token, opts);
4714
+ if (saved) return { token: saved.token, api: apiFor(args, saved.entry), account: null };
4715
+ const link = await linkedAccount({ cwd: opts.cwd, api: args.api, apiGiven: args.apiGiven === true, accounts: opts.accounts ?? defaultAccountStore(), home: opts.home });
4716
+ return link ? { token: link.token, api: link.origin, account: link } : null;
4717
+ }
4718
+ var USING_LINK = (email, origin) => `Using the design system linked to this folder (signed in as ${email} on ${origin}).`;
4587
4719
  async function scaffold(input, env, io) {
4588
4720
  const { folder, framework, token, api, force } = input;
4589
4721
  const { root, created } = planTarget(io.cwd, folder, framework, force);
4590
4722
  const screens = input.screens === true && framework === "next" ? { screens: "all" } : {};
4591
- const manifest = await fetchManifest({ api, token, framework, name: packageNameFor(folder), ...screens }, io.fetchImpl);
4723
+ if (input.account) io.stdout(`${USING_LINK(printable(input.account.email), input.account.origin)}
4724
+ `);
4725
+ const account = input.account ? { path: accountProjectRoute(input.account.projectId, "starter"), messages: cliAccountMessageForResponse } : {};
4726
+ const manifest = await fetchManifest({ api, token, framework, name: packageNameFor(folder), ...screens, ...account }, io.fetchImpl);
4592
4727
  const { runner, version } = detectRunner(env.npm_config_user_agent);
4593
4728
  const packageManager = runner === "pnpm" && version ? `pnpm@${version}` : void 0;
4594
4729
  const { written } = writeFiles(root, manifest.files, { force, created, packageManager });
@@ -4632,7 +4767,7 @@ function ttyQuestions(args, mode, io) {
4632
4767
  }
4633
4768
  };
4634
4769
  }
4635
- async function runAddCommand(args, io, exec = spawnExec, store) {
4770
+ async function runAddCommand(args, io, exec = spawnExec, store, accounts) {
4636
4771
  const root = io.cwd;
4637
4772
  const terminal = process.stdin.isTTY === true && process.stdout.isTTY === true;
4638
4773
  const interactive = !args.yes && terminal;
@@ -4645,18 +4780,23 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
4645
4780
  const first = previouslyAdded(root, targets).every((n) => n === "utils") && !sectionPresent(root, targets).present;
4646
4781
  if (first) mode = await pick(PICK_QUESTION, ADD_MODES, 0);
4647
4782
  }
4648
- const { token, entry } = await requireSavedToken(args.token, { cwd: root, store, interactive: terminal });
4783
+ const access = await savedOrLinked(args, { cwd: root, store, accounts, interactive: terminal });
4784
+ const { token, api, account } = access ?? { token: await requireToken(void 0), api: apiFor(args, null), account: null };
4785
+ if (account) io.stdout(`${USING_LINK(printable(account.email), account.origin)}
4786
+ `);
4649
4787
  const questions = interactive ? ttyQuestions(args, mode, io) : nonInteractiveQuestions(args);
4650
4788
  try {
4651
4789
  const result = await runAdd(
4652
4790
  {
4653
4791
  root,
4654
4792
  token,
4655
- api: apiFor(args, entry),
4793
+ api,
4794
+ ...account ? { kitPath: accountProjectRoute(account.projectId, "kit"), messages: cliAccountMessageForResponse } : {},
4656
4795
  components: args.components,
4657
4796
  skipInstall: args.skipInstall,
4658
4797
  all: args.all,
4659
4798
  blocks: !args.noBlocks,
4799
+ addBlocks: args.blocks,
4660
4800
  screens: args.screens,
4661
4801
  shell: args.shell,
4662
4802
  site: args.site,
@@ -4677,7 +4817,7 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
4677
4817
 
4678
4818
  // src/commands/connect.ts
4679
4819
  import { accessSync, constants as constants2, existsSync as existsSync11, statSync as statSync3 } from "node:fs";
4680
- import { homedir as homedir2 } from "node:os";
4820
+ import { homedir as homedir3 } from "node:os";
4681
4821
  import { join as join11 } from "node:path";
4682
4822
 
4683
4823
  // src/connect/fetch-project.ts
@@ -4722,7 +4862,7 @@ function onPath(bin, env, platform) {
4722
4862
  );
4723
4863
  }
4724
4864
  function defaultConnectDeps(env) {
4725
- const home = homedir2();
4865
+ const home = homedir3();
4726
4866
  const platform = process.platform;
4727
4867
  return {
4728
4868
  store: defaultStore(env),
@@ -4787,7 +4927,7 @@ async function runConnect(args, io, deps = defaultConnectDeps(process.env)) {
4787
4927
  const say = (lines) => io.stdout(lines.map((l) => `${l}
4788
4928
  `).join(""));
4789
4929
  if (args.forget) return forget(args, root, saveFolder, store, interactive, prompts, deps.credentialsPath, say);
4790
- const refusal = homeFolderRefusal(root, deps.home ?? homedir2()) ?? (main2 ? homeFolderRefusal(main2, deps.home ?? homedir2()) : null);
4930
+ const refusal = homeFolderRefusal(root, deps.home ?? homedir3()) ?? (main2 ? homeFolderRefusal(main2, deps.home ?? homedir3()) : null);
4791
4931
  if (refusal) throw new CliError(refusal);
4792
4932
  say([`Connecting ${root}`, ...main2 ? [WORKTREE_NOTE(main2)] : []]);
4793
4933
  let apps;
@@ -4869,11 +5009,11 @@ function savedFor(store, root, saveFolder) {
4869
5009
  }
4870
5010
 
4871
5011
  // src/commands/create.ts
4872
- async function runCreate(args, env, io, store) {
4873
- const saved = await savedToken(args.token, { cwd: io.cwd, store });
5012
+ async function runCreate(args, env, io, store, accounts) {
5013
+ const access = await savedOrLinked(args, { cwd: io.cwd, store, accounts });
4874
5014
  const folder = args.folder ?? await askFolder(CREATE_DEFAULT_FOLDER);
4875
- const token = saved?.token ?? await requireToken(void 0);
4876
- await scaffold({ folder, framework: "next", token, api: apiFor(args, saved?.entry), force: args.force, screens: args.noScreens !== true }, env, io);
5015
+ const { token, api, account } = access ?? { token: await requireToken(void 0), api: apiFor(args, null), account: null };
5016
+ await scaffold({ folder, framework: "next", token, api, account, force: args.force, screens: args.noScreens !== true }, env, io);
4877
5017
  }
4878
5018
 
4879
5019
  // src/commands/integrate.ts
@@ -4883,20 +5023,20 @@ var INTEGRATE_OPTIONS = [
4883
5023
  { value: "angular", label: "Angular" },
4884
5024
  { value: "css", label: "Plain CSS", hint: "any other stack" }
4885
5025
  ];
4886
- async function runIntegrate(args, env, io, store) {
5026
+ async function runIntegrate(args, env, io, store, accounts) {
4887
5027
  const framework = args.framework ?? await pick("Framework", INTEGRATE_OPTIONS, 0);
4888
- const saved = await savedToken(args.token, { cwd: io.cwd, store });
5028
+ const access = await savedOrLinked(args, { cwd: io.cwd, store, accounts });
4889
5029
  const folder = args.folder ?? await askFolder(INTEGRATE_DEFAULT_FOLDER);
4890
- const token = saved?.token ?? await requireToken(void 0);
4891
- await scaffold({ folder, framework, token, api: apiFor(args, saved?.entry), force: args.force }, env, io);
5030
+ const { token, api, account } = access ?? { token: await requireToken(void 0), api: apiFor(args, null), account: null };
5031
+ await scaffold({ folder, framework, token, api, account, force: args.force }, env, io);
4892
5032
  }
4893
5033
 
4894
5034
  // src/commands/login.ts
4895
5035
  import { existsSync as existsSync12 } from "node:fs";
4896
5036
  import { join as join12 } from "node:path";
4897
- import { homedir as homedir3, hostname } from "node:os";
5037
+ import { homedir as homedir4, hostname } from "node:os";
4898
5038
  function defaultLoginDeps(env) {
4899
- const home = homedir3();
5039
+ const home = homedir4();
4900
5040
  const platform = process.platform;
4901
5041
  return {
4902
5042
  accounts: createAccountStore({ env, platform, exec: spawnExec, home }),
@@ -4938,7 +5078,7 @@ function closingLines2(apps, changed, usesAccount) {
4938
5078
  COMMIT_SETTINGS_NOTE
4939
5079
  ];
4940
5080
  }
4941
- var plansFor = (root, apps) => apps.map((id) => ({ id, plan: planAppFile(root, id, null) }));
5081
+ var plansFor = (root, apps, projectId = null) => apps.map((id) => ({ id, plan: planAppFile(root, id, projectId) }));
4942
5082
  var changes = (plan) => plan.contents !== null && (plan.status === "create" || plan.status === "update");
4943
5083
  async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
4944
5084
  const { accounts, terminal } = deps;
@@ -4964,6 +5104,21 @@ async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
4964
5104
  }
4965
5105
  plansFor(root, apps);
4966
5106
  say([`Signing in for ${trust}`, ...worktree ? [WORKTREE_NOTE(trust)] : []]);
5107
+ const { email, head } = await signInAccount({ api, trust, io, deps });
5108
+ const { plans, changed, usesAccount, kept } = writeAgentFiles(root, apps, "login");
5109
+ say([
5110
+ `Signed in as ${email} on this computer.`,
5111
+ ...head,
5112
+ ...plans.flatMap(({ id, plan }) => appLines(id, plan)),
5113
+ ...kept,
5114
+ ...closingLines2(apps, changed, usesAccount)
5115
+ ]);
5116
+ }
5117
+ async function signInAccount(a) {
5118
+ const { api, trust, io, deps } = a;
5119
+ const { accounts, terminal } = deps;
5120
+ const say = (lines) => io.stdout(lines.map((l) => `${l}
5121
+ `).join(""));
4967
5122
  const head = [];
4968
5123
  let email = null;
4969
5124
  const saved = accounts.get(api);
@@ -4997,24 +5152,21 @@ async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
4997
5152
  if (entry.backup) head.push(`Your old account file could not be read, so it was kept as ${entry.backup}.`);
4998
5153
  head.push(savedLine2(entry.where, deps.accountPath));
4999
5154
  }
5000
- const plans = plansFor(root, apps);
5155
+ return { email, head };
5156
+ }
5157
+ function writeAgentFiles(root, apps, verb, projectId = null) {
5158
+ const plans = plansFor(root, apps, projectId);
5001
5159
  const files = plans.flatMap(({ plan }) => changes(plan) ? [{ path: plan.path, contents: plan.contents }] : []);
5002
5160
  try {
5003
5161
  if (files.length > 0) writeFiles(root, files, { force: true, created: false });
5004
5162
  } catch (e) {
5005
- if (e instanceof CliError) throw new CliError(`${e.message} You are signed in; run npx designsource login again to write the settings.`, e.exitCode);
5163
+ if (e instanceof CliError) throw new CliError(`${e.message} You are signed in; run npx designsource ${verb} again to write the settings.`, e.exitCode);
5006
5164
  throw e;
5007
5165
  }
5008
5166
  const changed = plans.filter(({ plan }) => changes(plan)).map(({ id }) => id);
5009
5167
  const usesAccount = plans.some(({ plan }) => changes(plan) || plan.status === "unchanged" && !plan.keepsProject);
5010
5168
  const kept = plans.flatMap(({ id, plan }) => plan.status === "unchanged" && plan.keepsProject ? [KEEPS_PROJECT_ENTRY(id, plan.path)] : []);
5011
- say([
5012
- `Signed in as ${email} on this computer.`,
5013
- ...head,
5014
- ...plans.flatMap(({ id, plan }) => appLines(id, plan)),
5015
- ...kept,
5016
- ...closingLines2(apps, changed, usesAccount)
5017
- ]);
5169
+ return { plans, changed, usesAccount, kept };
5018
5170
  }
5019
5171
  async function lacksScope(api, token, fetchImpl) {
5020
5172
  try {
@@ -5062,61 +5214,10 @@ async function runLogout(args, io, deps = defaultLoginDeps(process.env)) {
5062
5214
  }
5063
5215
 
5064
5216
  // src/mcp/server.ts
5065
- import { homedir as homedir5 } from "node:os";
5217
+ import { homedir as homedir6 } from "node:os";
5066
5218
 
5067
5219
  // src/version.ts
5068
- var VERSION = true ? "0.13.0" : "0.0.0-dev";
5069
-
5070
- // src/mcp/account-session.ts
5071
- var NOT_SIGNED_IN_FOR = (root) => `designsource is not signed in for ${printable(root)}. Ask the user to run npx designsource login in a terminal in that folder, then restart this app. A sign-in there also covers its git worktrees.`;
5072
- var SEVERAL_ACCOUNTS = "More than one designsource account is signed in on this computer; pass --api.";
5073
- var NO_LINK = "No design system is linked to this folder yet. Call list_design_systems, then use_design_system with one of its ids, or call create_design_system to make a new one.";
5074
- var ACCOUNT_TOKEN3 = /^dsa_[A-Za-z0-9_-]{43}$/;
5075
- var PROJECT_ID3 = /^[A-Za-z0-9_-]+$/;
5076
- var refuse = (message) => ({ kind: "none", message });
5077
- function trustedFolderOf(entry, roots) {
5078
- const trusted = (f) => entry.folders.some((saved) => normaliseFolder(saved) === f);
5079
- const folder = trusted(roots.work) ? roots.work : trusted(roots.trust) ? roots.trust : null;
5080
- if (folder === null) return null;
5081
- const linked = Object.entries(entry.links).find(([f]) => normaliseFolder(f) === folder)?.[1];
5082
- return { folder, projectId: linked !== void 0 && PROJECT_ID3.test(linked) ? linked : null };
5083
- }
5084
- function chooseAccount(api, apiGiven, accounts, notSignedIn) {
5085
- if (apiGiven) {
5086
- let origin;
5087
- try {
5088
- origin = originOf(api);
5089
- } catch {
5090
- return refuse(notSignedIn);
5091
- }
5092
- return accounts.get(origin) ?? refuse(notSignedIn);
5093
- }
5094
- const all = accounts.all();
5095
- if (all.length === 1) return all[0];
5096
- const fallback = accounts.get(DEFAULT_API_ORIGIN);
5097
- if (fallback) return fallback;
5098
- return refuse(all.length > 1 ? SEVERAL_ACCOUNTS : notSignedIn);
5099
- }
5100
- async function resolveAccount(input) {
5101
- const { api, apiGiven, cwd, home, accounts } = input;
5102
- const { work, trust } = projectFolders(cwd);
5103
- const notSignedIn = NOT_SIGNED_IN_FOR(trust);
5104
- const chosen = chooseAccount(api, apiGiven, accounts, notSignedIn);
5105
- if ("kind" in chosen) return chosen;
5106
- const homeDir = normaliseFolder(home);
5107
- if (homeFolderRefusal(trust, homeDir) !== null || homeFolderRefusal(work, homeDir) !== null) return refuse(notSignedIn);
5108
- const found = trustedFolderOf(chosen, { work, trust });
5109
- if (found === null) return refuse(notSignedIn);
5110
- const { folder, projectId } = found;
5111
- let token;
5112
- try {
5113
- token = await accounts.token(chosen.origin);
5114
- } catch {
5115
- return refuse(notSignedIn);
5116
- }
5117
- if (token === null || !ACCOUNT_TOKEN3.test(token)) return refuse(notSignedIn);
5118
- return { kind: "account", origin: chosen.origin, email: chosen.email, token, folder, workFolder: work, projectId };
5119
- }
5220
+ var VERSION = true ? "0.15.0" : "0.0.0-dev";
5120
5221
 
5121
5222
  // src/mcp/jsonrpc.ts
5122
5223
  import { StringDecoder } from "node:string_decoder";
@@ -5190,7 +5291,7 @@ function getPrompt(name) {
5190
5291
 
5191
5292
  // src/mcp/tools.ts
5192
5293
  import { existsSync as existsSync14 } from "node:fs";
5193
- import { homedir as homedir4 } from "node:os";
5294
+ import { homedir as homedir5 } from "node:os";
5194
5295
  import { join as join15 } from "node:path";
5195
5296
 
5196
5297
  // src/mcp/account-tools.ts
@@ -5573,7 +5674,7 @@ function appCandidates(base, near, src, trusted = []) {
5573
5674
  }
5574
5675
 
5575
5676
  // src/mcp/tools.ts
5576
- var accountProjectPath = (projectId, kind) => `/api/agent/projects/${encodeURIComponent(projectId)}/${kind}`;
5677
+ var accountProjectPath = (projectId, kind) => accountProjectRoute(projectId, kind);
5577
5678
  var READ_ONLY = { readOnlyHint: true };
5578
5679
  var TIERS = ["design", "semantic", "component"];
5579
5680
  var CATEGORIES = ["color", "spacing", "radius", "typography", "shadow", "zIndex", "border", "gradient"];
@@ -5673,18 +5774,21 @@ function screensArg(v) {
5673
5774
  function targetSources(ctx, base) {
5674
5775
  return {
5675
5776
  base,
5676
- home: ctx.home ?? homedir4(),
5777
+ home: ctx.home ?? homedir5(),
5677
5778
  ...ctx.token === null && ctx.account ? { accountTrust: (roots) => ctx.account.trustOf?.(roots) ?? null } : {},
5678
5779
  ...ctx.token !== null ? { savedFolders: ctx.projectFolders } : {}
5679
5780
  };
5680
5781
  }
5782
+ var BLOCKS_BOTH_FOR_AGENT = '"blocks" and "no_blocks" cannot both be true.';
5681
5783
  async function addUiKit(args, ctx) {
5682
- const { components, replace_existing: replace, no_blocks: noBlocks } = args;
5784
+ const { components, replace_existing: replace, no_blocks: noBlocks, blocks: addBlocks } = args;
5683
5785
  if (components !== void 0 && !(Array.isArray(components) && components.every((c) => typeof c === "string"))) {
5684
5786
  return errorResult('"components" must be an array of component names.');
5685
5787
  }
5686
5788
  if (replace !== void 0 && typeof replace !== "boolean") return errorResult('"replace_existing" must be true or false.');
5687
5789
  if (noBlocks !== void 0 && typeof noBlocks !== "boolean") return errorResult('"no_blocks" must be true or false.');
5790
+ if (addBlocks !== void 0 && typeof addBlocks !== "boolean") return errorResult('"blocks" must be true or false.');
5791
+ if (addBlocks === true && noBlocks === true) return errorResult(BLOCKS_BOTH_FOR_AGENT);
5688
5792
  const screens = screensArg(args.screens);
5689
5793
  if (!screens.ok) return errorResult(SCREENS_ARG);
5690
5794
  if (ctx.token === null && !ctx.account) return errorResult(ctx.missingToken ?? MCP_TOKEN_REQUIRED);
@@ -5732,6 +5836,7 @@ async function addUiKit(args, ctx) {
5732
5836
  components: components ?? [],
5733
5837
  skipInstall: false,
5734
5838
  blocks: noBlocks !== true,
5839
+ addBlocks: addBlocks === true,
5735
5840
  ...screens.value !== void 0 ? { screens: screens.value } : {},
5736
5841
  ...screens.site ? { site: true } : {},
5737
5842
  // As a bare CLI rerun: a call naming neither components nor screens refreshes the screens an earlier run wrote.
@@ -5891,13 +5996,14 @@ ${files.join("\n\n")}`);
5891
5996
  },
5892
5997
  {
5893
5998
  name: "add_ui_kit",
5894
- 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 and no screens 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, and refreshes the screens an earlier run wrote. screens (names from list_screens, or ["all"]) writes those app screens and marketing pages with the parts and components they import; you mount each on a route. Add "site" to screens to write the site menu (header and footer) that pages mount inside, at least one page being pulled with it. When the app is not in the current folder (a monorepo, or a workspace holding the app as a repository of its own), pass folder; a repository of its own works once the user has run npx designsource login in it, and its linked design system is used. Changes files in the project, so your client will ask the user first. Never overwrites components or screens the user edited.`,
5999
+ 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 and no screens 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 (blocks: true adds them to a section written without), and refreshes the screens an earlier run wrote. screens (names from list_screens, or ["all"]) writes those app screens and marketing pages with the parts and components they import; you mount each on a route. Add "site" to screens to write the site menu (header and footer) that pages mount inside, at least one page being pulled with it. When the app is not in the current folder (a monorepo, or a workspace holding the app as a repository of its own), pass folder; a repository of its own works once the user has run npx designsource login in it, and its linked design system is used. Changes files in the project, so your client will ask the user first. Never overwrites components or screens the user edited.`,
5895
6000
  inputSchema: {
5896
6001
  type: "object",
5897
6002
  properties: {
5898
6003
  components: { type: "array", items: { type: "string" }, description: "Component names such as button or dialog. Omit to add everything (or refresh what was added before)." },
5899
6004
  replace_existing: { type: "boolean", description: "Replace component files that exist but were not added by designsource. Ask the user first." },
5900
6005
  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." },
6006
+ blocks: { type: "boolean", description: "Add the blocks and their libraries to a /design-system section that was written without them. Not with no_blocks." },
5901
6007
  screens: { type: "array", items: { type: "string" }, description: `Screen names from list_screens, or ["all"] for every screen; "site" adds the site menu for marketing pages. Each is written under the components folder's screens/ with the parts and kit components it imports.` },
5902
6008
  folder: { type: "string", description: "The app's folder when it is not the current one: a path inside this project (a monorepo's apps/web), or a repository of its own the user ran npx designsource login in. Omit for the current folder." }
5903
6009
  },
@@ -6090,7 +6196,7 @@ function toolAccountFor(session, accounts, onLink, onGone = () => {
6090
6196
  }
6091
6197
  async function runMcp(args, io, streams = { input: process.stdin, output: process.stdout }, deps = {}) {
6092
6198
  const cwd = deps.cwd ?? process.cwd();
6093
- const home = deps.home ?? homedir5();
6199
+ const home = deps.home ?? homedir6();
6094
6200
  const store = deps.store ?? defaultStore();
6095
6201
  const warn = (line) => io.stderr(`${line}
6096
6202
  `);
@@ -6111,7 +6217,7 @@ async function runMcp(args, io, streams = { input: process.stdin, output: proces
6111
6217
  let account = null;
6112
6218
  const accountSession = async () => {
6113
6219
  if (!account) {
6114
- accounts ??= (deps.accounts ?? (() => createAccountStore({ env: process.env, platform: process.platform, exec: spawnExec, home: homedir5() })))();
6220
+ accounts ??= (deps.accounts ?? (() => createAccountStore({ env: process.env, platform: process.platform, exec: spawnExec, home: homedir6() })))();
6115
6221
  const resolved = await resolveAccount({ api: args.api, apiGiven: args.apiGiven === true, cwd, home, accounts });
6116
6222
  if (resolved.kind === "none") {
6117
6223
  return {
@@ -6178,6 +6284,339 @@ async function runMcp(args, io, streams = { input: process.stdin, output: proces
6178
6284
  }
6179
6285
  }
6180
6286
 
6287
+ // src/setup/state.ts
6288
+ import { existsSync as existsSync15, readdirSync as readdirSync6, readFileSync as readFileSync13 } from "node:fs";
6289
+ import { join as join16 } from "node:path";
6290
+ function frameworkOf(deps) {
6291
+ if ("@angular/core" in deps) return "angular";
6292
+ if ("svelte" in deps || "@sveltejs/kit" in deps) return "svelte";
6293
+ if ("vue" in deps || "nuxt" in deps) return "vue";
6294
+ return "css";
6295
+ }
6296
+ var FRAMEWORK_LABELS = { vue: "Vue", svelte: "Svelte", angular: "Angular", css: "plain CSS" };
6297
+ var appLabel = (info) => info.framework === "next" ? "Next.js app" : info.framework === "vite" ? "Vite app" : "React app";
6298
+ function describeApp(info) {
6299
+ const parts = [
6300
+ ...info.reactMajor !== null && Number.isFinite(info.reactMajor) ? [`React ${info.reactMajor}`] : [],
6301
+ ...info.tailwindMajor !== null && Number.isFinite(info.tailwindMajor) ? [`Tailwind ${info.tailwindMajor}`] : [],
6302
+ ...info.shadcn ? ["shadcn"] : []
6303
+ ];
6304
+ return `${appLabel(info)}${parts.length > 0 ? ` (${parts.join(", ")})` : ""}.`;
6305
+ }
6306
+ function readDeps(root) {
6307
+ try {
6308
+ const pkg = JSON.parse(readFileSync13(join16(root, "package.json"), "utf8"));
6309
+ const pick2 = (v) => typeof v === "object" && v !== null ? Object.fromEntries(Object.entries(v).filter((e) => typeof e[1] === "string")) : {};
6310
+ return { ...pick2(pkg?.dependencies), ...pick2(pkg?.devDependencies) };
6311
+ } catch {
6312
+ return null;
6313
+ }
6314
+ }
6315
+ var WORKSPACE_ROOT = "This is a workspace root. Run npx designsource in the app's own folder (apps/web, say).";
6316
+ function hasWorkspaces(root) {
6317
+ try {
6318
+ return "workspaces" in JSON.parse(readFileSync13(join16(root, "package.json"), "utf8"));
6319
+ } catch {
6320
+ return false;
6321
+ }
6322
+ }
6323
+ function targetsOf(root, info) {
6324
+ try {
6325
+ return info.shadcn ? resolveTargets(root, info.shadcn) : defaultTargets(root, info);
6326
+ } catch {
6327
+ return null;
6328
+ }
6329
+ }
6330
+ function readSetupState(cwd, home) {
6331
+ const root = normaliseFolder(cwd);
6332
+ const homeDir = normaliseFolder(home);
6333
+ const { work, trust } = projectFolders(cwd);
6334
+ const refusal = homeFolderRefusal(root, homeDir) ?? homeFolderRefusal(work, homeDir) ?? homeFolderRefusal(trust, homeDir);
6335
+ if (refusal) return { kind: "refused", message: refusal };
6336
+ if (!existsSync15(join16(root, "package.json"))) {
6337
+ const names = readdirSync6(root);
6338
+ if (names.every((n) => n.startsWith("."))) {
6339
+ const onlyGit = names.length > 0 && names.every((n) => n === ".git" || n === ".DS_Store");
6340
+ return { kind: "empty", root, found: "Empty folder.", dotfiles: names.length > 0, onlyGit };
6341
+ }
6342
+ return { kind: "other-stack", root, found: "No package.json here, so this is treated as a plain CSS site.", framework: "css" };
6343
+ }
6344
+ const deps = readDeps(root);
6345
+ if (deps === null) throw new CliError("package.json is not valid JSON.");
6346
+ if (!("react" in deps) && (hasWorkspaces(root) || existsSync15(join16(root, "pnpm-workspace.yaml")))) return { kind: "refused", message: WORKSPACE_ROOT };
6347
+ if (!("react" in deps)) {
6348
+ const framework = frameworkOf(deps);
6349
+ return { kind: "other-stack", root, found: framework === "css" ? "No React here; the design system goes in as plain CSS." : `${FRAMEWORK_LABELS[framework]} app.`, framework };
6350
+ }
6351
+ const info = detectApp(root);
6352
+ let cannotAdd = null;
6353
+ try {
6354
+ assertCanAdd(info);
6355
+ } catch (e) {
6356
+ if (!(e instanceof CliError)) throw e;
6357
+ cannotAdd = e.message;
6358
+ }
6359
+ const targets = cannotAdd === null ? targetsOf(root, info) : null;
6360
+ if (targets) {
6361
+ const components = previouslyAdded(root, targets).filter((n) => n !== "utils" && n !== "preview-portal").length;
6362
+ const section = sectionPresent(root, targets).present;
6363
+ if (components > 0 || section) {
6364
+ const screens = screensOnDisk(root, targets).slugs.length;
6365
+ return { kind: "react-set-up", root, found: `${describeApp(info)} The design system is set up here.`, info, components, section, screens };
6366
+ }
6367
+ }
6368
+ return { kind: "react-fresh", root, found: `${describeApp(info)} No design system here yet.`, info, cannotAdd };
6369
+ }
6370
+
6371
+ // src/commands/setup.ts
6372
+ var SETUP_NEEDS_TERMINAL = "setup asks questions, so it needs a terminal. In a script, use add, connect or login.";
6373
+ var SETUP_NOT_A_PROJECT = "This folder is neither a repository nor an app. Run npx designsource in your app's folder.";
6374
+ var CANNOT_ADD_AGENT_ONLY = "The UI kit cannot go into this app, so setup connects your coding agent only; it can still create a design system and port it by hand.";
6375
+ var MAKE_NEW_WAIT = "Make your design system in the browser. This continues when it is saved.";
6376
+ var WAIT_TIMEOUT = "Still waiting? Run npx designsource again once your design system is saved.";
6377
+ var NO_APPS_HERE = "No coding apps found on this computer. Run npx designsource login --apps claude (or cursor, vscode, codex, gemini) to set one up.";
6378
+ var BLOCKS_HINT = "Want the ready-made blocks too? Run npx designsource add --blocks";
6379
+ var USING = (name) => `Using \u201C${name}\u201D.`;
6380
+ var AFTER_UPGRADE = "After upgrading, run npx designsource again.";
6381
+ var FREE_PLAN_LINES = (origin, what) => [
6382
+ `Your account is on the free plan, so ${what === "kit" ? "the kit was not added to this app" : what === "files" ? "the design system files were not added" : "the app was not created"}.`,
6383
+ `Exports need Pro: ${origin}/pricing`,
6384
+ AFTER_UPGRADE
6385
+ ];
6386
+ var SET_UP_STATUS = (name, components, section, screens) => `\u201C${name}\u201D is set up here (${[
6387
+ `${components} component${components === 1 ? "" : "s"}`,
6388
+ ...section ? ["the /design-system section"] : [],
6389
+ ...screens > 0 ? [`${screens} screen${screens === 1 ? "" : "s"}`] : []
6390
+ ].join(", ")}).`;
6391
+ var NEXT_STEP = (sentence) => ["Next: ask your coding agent", ` \u201C${sentence}\u201D`];
6392
+ var RESTYLE_SENTENCE = "Restyle this app's existing screens with the design system.";
6393
+ var APPLY_SENTENCE = "Apply the design system in design-system/ to this app.";
6394
+ var WAIT_MS = 30 * 6e4;
6395
+ var POLL_MS = 5e3;
6396
+ var PICKER_MAX = 20;
6397
+ var TERMINAL2 = { pick: (q, o, d) => pick(q, o, d ?? 0), pickMany };
6398
+ function defaultSetupDeps(env, menu) {
6399
+ const { prompts: _loginPrompts, ...login } = defaultLoginDeps(env);
6400
+ return { ...login, store: defaultStore(env), exec: spawnExec, menu };
6401
+ }
6402
+ var PROJECT_ID5 = /^[A-Za-z0-9_-]{1,64}$/;
6403
+ async function listProjects2(api, token, fetchImpl) {
6404
+ const res = await requestJson({ api, path: "/api/agent/projects", method: "GET", token }, fetchImpl);
6405
+ if (res.status === 401) throw new CliError(ACCOUNT_TOKEN_MESSAGE);
6406
+ if (res.status !== 200) throw new CliError(messageForResponse(res.status, res.body, api));
6407
+ const rows = typeof res.body === "object" && res.body !== null ? res.body.projects : null;
6408
+ if (!Array.isArray(rows)) throw new CliError("Unexpected response from the API \u2014 not a list of design systems.");
6409
+ return rows.flatMap((r) => {
6410
+ if (typeof r !== "object" || r === null) return [];
6411
+ const { id, name } = r;
6412
+ return typeof id === "string" && PROJECT_ID5.test(id) && typeof name === "string" ? [{ id, name: printable(name) || id }] : [];
6413
+ });
6414
+ }
6415
+ async function exportsAllowed(api, token, fetchImpl) {
6416
+ try {
6417
+ const res = await requestJson({ api, path: "/api/agent/token", method: "GET", token }, fetchImpl);
6418
+ const value = res.status === 200 && typeof res.body === "object" && res.body !== null ? res.body.exports : void 0;
6419
+ return typeof value === "boolean" ? value : null;
6420
+ } catch {
6421
+ return null;
6422
+ }
6423
+ }
6424
+ async function chooseApps(root, deps, prompts) {
6425
+ const withEntry = APPS.map((a) => a.id).filter((id) => planAppFile(root, id, null).status === "unchanged");
6426
+ if (withEntry.length > 0) return withEntry;
6427
+ const detected = deps.detect();
6428
+ if (detected.length <= 1) return detected;
6429
+ return prompts.pickMany("Set up which coding apps?", APP_OPTIONS, detected);
6430
+ }
6431
+ async function runSetup(args, io, deps) {
6432
+ if (!deps.terminal) throw new CliError(SETUP_NEEDS_TERMINAL);
6433
+ const prompts = deps.prompts ?? TERMINAL2;
6434
+ const say = (lines) => io.stdout(lines.map((l) => `${l}
6435
+ `).join(""));
6436
+ const state = readSetupState(io.cwd, deps.home);
6437
+ if (state.kind === "refused") throw new CliError(state.message);
6438
+ say([state.found]);
6439
+ if (state.kind === "react-fresh" && state.cannotAdd) say([state.cannotAdd, CANNOT_ADD_AGENT_ONLY]);
6440
+ if (state.kind === "empty") {
6441
+ const choice = await prompts.pick("What do you want to do?", [{ value: "create", label: "Create a new Next.js app here" }, { value: "other", label: "Something else\u2026" }]);
6442
+ if (choice === "other") return deps.menu();
6443
+ } else if (state.kind === "other-stack") {
6444
+ const choice = await prompts.pick("What do you want to do?", [{ value: "files", label: `Add the design system files for ${FRAMEWORK_LABELS[state.framework]}` }, { value: "other", label: "Something else\u2026" }]);
6445
+ if (choice === "other") return deps.menu();
6446
+ }
6447
+ const { work, trust, worktree } = projectFolders(io.cwd);
6448
+ if (state.kind !== "empty" && !isProjectFolder(work) && !isProjectFolder(state.root)) throw new CliError(SETUP_NOT_A_PROJECT);
6449
+ const api = loginApi(args, true);
6450
+ const apps = await chooseApps(work, deps, prompts);
6451
+ const saved = await resolveToken({ cwd: io.cwd, store: deps.store, interactive: true, prompt: false });
6452
+ let access;
6453
+ if (saved?.entry) {
6454
+ access = { kind: "project", token: saved.token, api: apiFor(args, saved.entry), name: printable(saved.entry.name), projectId: saved.entry.projectId };
6455
+ } else {
6456
+ say([`Signing in for ${trust}`, ...worktree ? [WORKTREE_NOTE(trust)] : []]);
6457
+ const signed = await signInAccount({ api, trust, io, deps });
6458
+ say([`Signed in as ${signed.email} on this computer.`, ...signed.head]);
6459
+ const token = await deps.accounts.token(api);
6460
+ if (token === null) throw new CliError(ACCOUNT_TOKEN_MESSAGE);
6461
+ const projects = await listProjects2(api, token, io.fetchImpl);
6462
+ const entry = deps.accounts.get(api);
6463
+ const linkedId = entry ? trustedFolderOf(entry, { work, trust })?.projectId ?? null : null;
6464
+ access = { kind: "account", token, api, email: signed.email, projects, linked: projects.find((p) => p.id === linkedId) ?? null };
6465
+ }
6466
+ let agent = null;
6467
+ const writeAgents = () => {
6468
+ if (apps.length > 0) agent = writeAgentFiles(work, apps, "setup", access.kind === "project" ? access.projectId : null);
6469
+ };
6470
+ if (state.kind !== "empty") writeAgents();
6471
+ let name;
6472
+ let projectId = null;
6473
+ if (access.kind === "project") {
6474
+ name = access.name;
6475
+ } else if (access.linked) {
6476
+ name = access.linked.name;
6477
+ projectId = access.linked.id;
6478
+ } else {
6479
+ const chosen = await chooseDesignSystem(access, deps, prompts, io, say);
6480
+ if (chosen === null) return say(agentLines());
6481
+ deps.accounts.link(access.api, trust, chosen.id);
6482
+ name = chosen.name;
6483
+ projectId = chosen.id;
6484
+ }
6485
+ const kitPath = () => projectId === null ? void 0 : accountProjectRoute(projectId, "kit");
6486
+ const kitLines = [];
6487
+ let planStopped = false;
6488
+ const freeLines = (...lines) => {
6489
+ planStopped = true;
6490
+ kitLines.push(...lines);
6491
+ };
6492
+ const pushKit = (r) => r.planStopped ? freeLines(...r.lines) : kitLines.push(...r.lines);
6493
+ const exports = access.kind === "account" ? await exportsAllowed(access.api, access.token, io.fetchImpl) : null;
6494
+ if (state.kind === "react-set-up") {
6495
+ say([SET_UP_STATUS(name, state.components, state.section, state.screens)]);
6496
+ const options = [
6497
+ { value: "update", label: `Update from \u201C${name}\u201D` },
6498
+ ...access.kind === "account" ? [{ value: "different", label: "Use a different design system" }] : [],
6499
+ { value: "other", label: "Something else\u2026" }
6500
+ ];
6501
+ const choice = await prompts.pick("What do you want to do?", options);
6502
+ if (choice === "other") return deps.menu();
6503
+ if (choice === "different" && access.kind === "account") {
6504
+ const chosen = await chooseDesignSystem({ ...access, linked: null }, deps, prompts, io, say);
6505
+ if (chosen === null) return say(agentLines());
6506
+ deps.accounts.link(access.api, trust, chosen.id);
6507
+ name = chosen.name;
6508
+ projectId = chosen.id;
6509
+ }
6510
+ say([USING(name)]);
6511
+ if (exports === false) freeLines(...FREE_PLAN_LINES(access.api, "kit"));
6512
+ else pushKit(await addKit(state, access, kitPath(), false, deps, io));
6513
+ } else {
6514
+ say([USING(name)]);
6515
+ if (state.kind === "react-fresh") {
6516
+ if (state.cannotAdd === null) {
6517
+ if (exports === false) freeLines(...FREE_PLAN_LINES(access.api, "kit"));
6518
+ else pushKit(await addKit(state, access, kitPath(), true, deps, io));
6519
+ }
6520
+ } else if (state.kind === "other-stack") {
6521
+ if (exports === false) freeLines(...FREE_PLAN_LINES(access.api, "files"));
6522
+ else await (deps.runIntegrate ?? runIntegrate)({ folder: ".", framework: state.framework, api: args.api, apiGiven: args.apiGiven, force: false }, process.env, io, deps.store, deps.accounts);
6523
+ } else if (state.kind === "empty") {
6524
+ if (exports === false) freeLines(...FREE_PLAN_LINES(access.api, "app"));
6525
+ else await (deps.runCreate ?? runCreate)({ folder: ".", api: args.api, apiGiven: args.apiGiven, force: state.onlyGit }, process.env, io, deps.store, deps.accounts);
6526
+ writeAgents();
6527
+ }
6528
+ }
6529
+ const noKit = planStopped || state.kind === "react-fresh" && state.cannotAdd !== null;
6530
+ const sentence = noKit ? null : state.kind === "other-stack" ? APPLY_SENTENCE : state.kind === "empty" ? null : RESTYLE_SENTENCE;
6531
+ say([...kitLines, ...agentLines(), ...sentence ? NEXT_STEP(sentence) : []]);
6532
+ function agentLines() {
6533
+ const done = agent;
6534
+ return [
6535
+ ...apps.length === 0 ? [NO_APPS_HERE] : [],
6536
+ ...done ? [...done.plans.flatMap(({ id, plan }) => appLines(id, plan)), ...done.kept, ...agentClosing(apps, done.changed)] : []
6537
+ ];
6538
+ }
6539
+ }
6540
+ var labelOf2 = (id) => APPS.find((a) => a.id === id).label;
6541
+ var listOf2 = (words) => words.length <= 1 ? words.join("") : `${words.slice(0, -1).join(", ")} and ${words.at(-1)}`;
6542
+ function agentClosing(apps, changed) {
6543
+ return [
6544
+ ...changed.length > 0 ? [`Restart ${listOf2(changed.map(labelOf2))} so ${changed.length === 1 ? "it loads" : "they load"} designsource.`] : [],
6545
+ ...apps.includes("claude") ? ["Claude Code asks once to allow the server."] : [],
6546
+ ...apps.includes("codex") ? [CODEX_TRUST_NOTE] : [],
6547
+ ...apps.includes("gemini") ? [GEMINI_TRUST_NOTE] : [],
6548
+ COMMIT_SETTINGS_NOTE
6549
+ ];
6550
+ }
6551
+ async function chooseDesignSystem(access, deps, prompts, io, say) {
6552
+ const { projects } = access;
6553
+ if (projects.length === 0) return makeNew(access, deps, prompts, io, say);
6554
+ const options = [
6555
+ { value: "new", label: "Make a new one" },
6556
+ ...projects.slice(0, PICKER_MAX).map((p) => ({ value: `p:${p.id}`, label: p.name })),
6557
+ ...projects.length > PICKER_MAX ? [{ value: "more", label: "More\u2026" }] : []
6558
+ ];
6559
+ let choice = await prompts.pick("Which design system?", options);
6560
+ if (choice === "more") choice = await prompts.pick("Which design system?", projects.map((p) => ({ value: `p:${p.id}`, label: p.name })));
6561
+ if (choice === "new") return makeNew(access, deps, prompts, io, say);
6562
+ return projects.find((p) => `p:${p.id}` === choice) ?? null;
6563
+ }
6564
+ async function makeNew(access, deps, prompts, io, say) {
6565
+ const url = `${access.api}/projects`;
6566
+ await (deps.open ?? ((u) => openBrowser(u, deps.platform)))(url);
6567
+ say([`Opening ${url}`, MAKE_NEW_WAIT]);
6568
+ const known = new Set(access.projects.map((p) => p.id));
6569
+ const now = deps.now ?? Date.now;
6570
+ const sleep = deps.sleep ?? ((ms) => new Promise((resolve10) => setTimeout(resolve10, ms)));
6571
+ const start = now();
6572
+ const waitMs = deps.waitMs ?? WAIT_MS;
6573
+ while (now() - start < waitMs) {
6574
+ await sleep(deps.pollMs ?? POLL_MS);
6575
+ let list;
6576
+ try {
6577
+ list = await listProjects2(access.api, access.token, io.fetchImpl);
6578
+ } catch (e) {
6579
+ if (e instanceof CliError && e.message === ACCOUNT_TOKEN_MESSAGE) throw e;
6580
+ continue;
6581
+ }
6582
+ const fresh = list.filter((p) => !known.has(p.id));
6583
+ if (fresh.length === 1) return fresh[0];
6584
+ if (fresh.length > 1) {
6585
+ const choice = await prompts.pick("Which new design system?", fresh.map((p) => ({ value: `p:${p.id}`, label: p.name })));
6586
+ return fresh.find((p) => `p:${p.id}` === choice) ?? null;
6587
+ }
6588
+ }
6589
+ say([WAIT_TIMEOUT]);
6590
+ return null;
6591
+ }
6592
+ async function addKit(state, access, kitPath, fresh, deps, io) {
6593
+ const addArgs = { components: [], api: access.api, yes: false, all: fresh, force: false, skipInstall: false, noBlocks: false, blocks: false };
6594
+ let result;
6595
+ try {
6596
+ result = await runAdd(
6597
+ {
6598
+ root: state.root,
6599
+ token: access.token,
6600
+ api: access.api,
6601
+ ...kitPath ? { kitPath, messages: cliAccountMessageForResponse } : {},
6602
+ components: [],
6603
+ skipInstall: false,
6604
+ all: fresh,
6605
+ blocks: !fresh,
6606
+ refreshScreens: true,
6607
+ force: false
6608
+ },
6609
+ { fetchImpl: io.fetchImpl, exec: deps.exec, questions: deps.addQuestions ?? ttyQuestions(addArgs, "all", io), progress: (line) => io.stdout(`${line}
6610
+ `) }
6611
+ );
6612
+ } catch (e) {
6613
+ if (e instanceof CliError && e.message === PLAN_MESSAGE) return { lines: FREE_PLAN_LINES(access.api, "kit"), planStopped: true };
6614
+ throw e;
6615
+ }
6616
+ const hint = result.section && result.section.blocks === 0 && !result.section.blocksLeftInPlace ? [BLOCKS_HINT] : [];
6617
+ return { lines: [...summaryLines(result), ...hint], planStopped: false };
6618
+ }
6619
+
6181
6620
  // src/index.ts
6182
6621
  var MENU = [
6183
6622
  { value: "add", label: "Add the UI kit to a React app", hint: "your components and theme, set up for you" },
@@ -6203,27 +6642,22 @@ ${e.usage}`);
6203
6642
  io.stdout(usageFor(command.verb));
6204
6643
  return 0;
6205
6644
  }
6645
+ const terminal = process.stdin.isTTY === true && process.stdout.isTTY === true;
6206
6646
  try {
6207
- if (command.kind === "menu") {
6208
- if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
6647
+ if (command.kind === "setup" && command.bare || command.kind === "menu") {
6648
+ if (!terminal) {
6209
6649
  io.stderr(`Missing command. ${USE_VERBS}
6210
6650
 
6211
6651
  ${USAGE}`);
6212
6652
  return 1;
6213
6653
  }
6214
- const verb = await pick("What do you want to do?", MENU, 0);
6215
- command = parseArgs([verb], env);
6216
6654
  }
6217
- if (command.kind === "mcp") {
6218
- await runMcp(command.args, io);
6655
+ if (command.kind === "menu") command = await menuCommand(env);
6656
+ if (command.kind === "setup") {
6657
+ await runSetup(command.args, io, defaultSetupDeps(env, async () => runCommand(await menuCommand(env), env, io)));
6219
6658
  return 0;
6220
6659
  }
6221
- if (command.kind === "add") await runAddCommand(command.args, io);
6222
- else if (command.kind === "connect") await runConnect(command.args, io, defaultConnectDeps(env));
6223
- else if (command.kind === "create") await runCreate(command.args, env, io);
6224
- else if (command.kind === "integrate") await runIntegrate(command.args, env, io);
6225
- else if (command.kind === "login") await runLogin(command.args, io, defaultLoginDeps(env));
6226
- else if (command.kind === "logout") await runLogout(command.args, io, defaultLoginDeps(env));
6660
+ await runCommand(command, env, io);
6227
6661
  return 0;
6228
6662
  } catch (e) {
6229
6663
  if (e instanceof CliError) {
@@ -6234,6 +6668,19 @@ ${USAGE}`);
6234
6668
  throw e;
6235
6669
  }
6236
6670
  }
6671
+ async function menuCommand(env) {
6672
+ const verb = await pick("What do you want to do?", MENU, 0);
6673
+ return parseArgs([verb], env);
6674
+ }
6675
+ async function runCommand(command, env, io) {
6676
+ if (command.kind === "mcp") await runMcp(command.args, io);
6677
+ else if (command.kind === "add") await runAddCommand(command.args, io);
6678
+ else if (command.kind === "connect") await runConnect(command.args, io, defaultConnectDeps(env));
6679
+ else if (command.kind === "create") await runCreate(command.args, env, io);
6680
+ else if (command.kind === "integrate") await runIntegrate(command.args, env, io);
6681
+ else if (command.kind === "login") await runLogin(command.args, io, defaultLoginDeps(env));
6682
+ else if (command.kind === "logout") await runLogout(command.args, io, defaultLoginDeps(env));
6683
+ }
6237
6684
  var code = await main(process.argv.slice(2), process.env, {
6238
6685
  stdout: (s) => process.stdout.write(s),
6239
6686
  stderr: (s) => process.stderr.write(s),