designsource 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +55 -11
  2. package/dist/index.js +1122 -195
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,5 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ // src/args.ts
4
+ import { parseArgs as scanArgv } from "node:util";
5
+
3
6
  // src/connect/apps.ts
4
7
  import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
5
8
  import { posix as posix3, win32 } from "node:path";
@@ -29,6 +32,13 @@ function messageForResponse(status, body, api) {
29
32
  if (status === 400) return serverMessage ?? `${api} rejected the request (400).`;
30
33
  return `${api} answered ${status}.`;
31
34
  }
35
+ var ACCOUNT_TOKEN_MESSAGE = "This computer is no longer signed in to designsource (revoked or expired). Run npx designsource login in a terminal.";
36
+ var LINKED_PROJECT_GONE = "The linked design system is gone (deleted, or not in this account). Call list_design_systems, then use_design_system.";
37
+ function accountMessageForResponse(status, body, api) {
38
+ if (status === 401) return ACCOUNT_TOKEN_MESSAGE;
39
+ if (status === 404) return LINKED_PROJECT_GONE;
40
+ return messageForResponse(status, body, api);
41
+ }
32
42
 
33
43
  // src/paths.ts
34
44
  import { isAbsolute, resolve, sep } from "node:path";
@@ -575,6 +585,7 @@ var APPS = SPECS.map(({ id, label, file, format }) => ({
575
585
  key: format.kind === "json" ? format.key : "mcp_servers"
576
586
  }));
577
587
  function serverEntry(projectId) {
588
+ if (projectId === null) return { command: "npx", args: ["-y", "designsource@latest", "mcp"] };
578
589
  assertProjectId(projectId);
579
590
  return { command: "npx", args: ["-y", "designsource@latest", "mcp", "--project", projectId] };
580
591
  }
@@ -609,6 +620,38 @@ function planAppFile(root, app2, projectId) {
609
620
  function namesProject(words, projectId) {
610
621
  return words.some((w, i) => w === "--project" && words[i + 1] === projectId || w === `--project=${projectId}`);
611
622
  }
623
+ var isHttpUrl = (value) => {
624
+ try {
625
+ const { protocol } = new URL(value);
626
+ return protocol === "http:" || protocol === "https:";
627
+ } catch {
628
+ return false;
629
+ }
630
+ };
631
+ var JSON_ENTRY_KEYS = /* @__PURE__ */ new Set(["command", "args", "type", "env"]);
632
+ var TOML_ENTRY_KEYS = /* @__PURE__ */ new Set(["command", "args", "startup_timeout_sec"]);
633
+ function isOurJsonEntry(entry) {
634
+ if (!isObject(entry) || !Object.keys(entry).every((k) => JSON_ENTRY_KEYS.has(k))) return false;
635
+ if (entry.type !== void 0 && entry.type !== "stdio") return false;
636
+ if (entry.env !== void 0 && !(isObject(entry.env) && Object.keys(entry.env).length === 0)) return false;
637
+ return isOurEntry(entry.command, entry.args);
638
+ }
639
+ var namesAProject = (args) => Array.isArray(args) && args[serverEntry(null).args.length] === "--project";
640
+ function isOurEntry(command, args) {
641
+ if (command !== "npx" || !Array.isArray(args) || !args.every((a) => typeof a === "string")) return false;
642
+ const base = serverEntry(null).args;
643
+ if (!base.every((word, i) => args[i] === word)) return false;
644
+ let rest = args.slice(base.length);
645
+ if (rest[0] === "--project") {
646
+ if (rest.length < 2 || !/^[A-Za-z0-9_-]+$/.test(rest[1])) return false;
647
+ rest = rest.slice(2);
648
+ }
649
+ if (rest[0] === "--api") {
650
+ if (rest.length < 2 || !isHttpUrl(rest[1])) return false;
651
+ rest = rest.slice(2);
652
+ }
653
+ return rest.length === 0;
654
+ }
612
655
  function entryWords(entry) {
613
656
  if (!isObject(entry)) return [];
614
657
  const words = typeof entry.command === "string" ? entry.command.split(/\s+/) : [];
@@ -626,7 +669,7 @@ function carries(value) {
626
669
  function planJson(path, text, key, entry, projectId) {
627
670
  if (text === null || text.trim() === "") return { path, status: "create", contents: `${JSON.stringify({ [key]: { designsource: entry } }, null, 2)}
628
671
  ` };
629
- const manual = { path, status: "manual", contents: null, manualEntry: `"designsource": ${JSON.stringify(entry, null, 2)}` };
672
+ const manual = { path, status: "manual", contents: null, manualEntry: `"designsource": ${JSON.stringify(entry, null, 2)}`, manualReason: "unparseable" };
630
673
  const bom = text.startsWith("\uFEFF") ? "\uFEFF" : "";
631
674
  const body = text.slice(bom.length);
632
675
  if (maskComments(body) !== body) return manual;
@@ -640,9 +683,12 @@ function planJson(path, text, key, entry, projectId) {
640
683
  const servers = Object.hasOwn(parsed, key) ? parsed[key] : void 0;
641
684
  if (servers !== void 0 && !isObject(servers)) return manual;
642
685
  const existing = servers && Object.hasOwn(servers, "designsource") ? servers.designsource : void 0;
643
- if (existing !== void 0 && namesProject(entryWords(existing), projectId)) {
644
- return { path, status: "unchanged", contents: text, hasEnv: isObject(existing) && carries(existing.env) };
686
+ const kept = existing !== void 0 && (projectId === null ? isOurJsonEntry(existing) : namesProject(entryWords(existing), projectId));
687
+ if (kept) {
688
+ const keepsProject = projectId === null && isObject(existing) && namesAProject(existing.args);
689
+ return { path, status: "unchanged", contents: text, hasEnv: isObject(existing) && carries(existing.env), ...keepsProject ? { keepsProject } : {} };
645
690
  }
691
+ if (existing !== void 0 && projectId === null) return { ...manual, manualReason: "foreign-entry" };
646
692
  return { path, status: "update", contents: bom + insertJsonEntry(body, key, entry) };
647
693
  }
648
694
  var WS = " \n\r";
@@ -888,33 +934,42 @@ function planToml(path, text, projectId) {
888
934
  const full = key ? [...table, ...key.path] : [];
889
935
  return key !== null && (startsWithPath(full, OURS) || samePath(full, ["mcp_servers"]));
890
936
  });
891
- if (elsewhere) return { path, status: "manual", contents: null, manualEntry: codexTable(projectId, "\n").trimEnd() };
937
+ if (elsewhere) return { path, status: "manual", contents: null, manualEntry: codexTable(projectId, "\n").trimEnd(), manualReason: "foreign-entry" };
892
938
  const separator = text.trim() === "" ? null : /\r?\n\r?\n$/.test(text) ? "" : /\n$/.test(text) ? eol : eol + eol;
893
939
  return { path, status: "update", contents: separator === null ? codexTable(projectId, eol) : text + separator + codexTable(projectId, eol) };
894
940
  }
895
941
  const words = [];
942
+ const commands = [];
943
+ let args = null;
896
944
  let hasEnv = false;
945
+ let otherKey = false;
897
946
  for (let n = ours + 1; n < lines.length && !headers[n]; n++) {
898
947
  const line = lines[n];
899
948
  const key = line.free ? tomlKey(line.text) : null;
949
+ if (key && (key.path.length !== 1 || !TOML_ENTRY_KEYS.has(key.path[0]))) otherKey = true;
900
950
  if (key && key.path.length === 1 && (key.path[0] === "command" || key.path[0] === "args")) {
901
951
  const values = tomlStrings(text, line.start + key.valueAt);
902
952
  words.push(...key.path[0] === "command" ? values.flatMap((v) => v.split(/\s+/)) : values);
953
+ if (key.path[0] === "command") commands.push(...values);
954
+ else args = [...args ?? [], ...values];
903
955
  }
904
956
  if (key && key.path[0] === "env" && (key.path.length > 1 || !/^\s*\{\s*\}/.test(line.text.slice(key.valueAt)))) hasEnv = true;
905
957
  }
906
- if (namesProject(words, projectId)) {
958
+ const subTable = headers.some((h) => h !== null && h.path.length > OURS.length && startsWithPath(h.path, OURS));
959
+ const kept = projectId === null ? !otherKey && !subTable && commands.length === 1 && isOurEntry(commands[0], args) : namesProject(words, projectId);
960
+ if (!kept && projectId === null) return { path, status: "manual", contents: null, manualEntry: codexTable(projectId, "\n").trimEnd(), manualReason: "foreign-entry" };
961
+ if (kept) {
907
962
  for (let n = ours + 1; n < lines.length && !hasEnv; n++) {
908
963
  const header = headers[n];
909
964
  if (!header || header.array || !samePath(header.path, [...OURS, "env"])) continue;
910
965
  for (let m = n + 1; m < lines.length && !headers[m]; m++) if (lines[m].free && tomlKey(lines[m].text)) hasEnv = true;
911
966
  }
912
- return { path, status: "unchanged", contents: text, hasEnv };
967
+ return { path, status: "unchanged", contents: text, hasEnv, ...projectId === null && namesAProject(args) ? { keepsProject: true } : {} };
913
968
  }
914
969
  let next = ours + 1;
915
970
  while (next < lines.length && !(headers[next] && !startsWithPath(headers[next].path, OURS))) next++;
916
971
  const stray = headers.some((h, n) => h !== null && (n < ours || n >= next) && startsWithPath(h.path, OURS));
917
- if (stray) return { path, status: "manual", contents: null, manualEntry: codexTable(projectId, "\n").trimEnd() };
972
+ if (stray) return { path, status: "manual", contents: null, manualEntry: codexTable(projectId, "\n").trimEnd(), manualReason: "foreign-entry" };
918
973
  let last = next - 1;
919
974
  while (last > ours && lines[last].free && /^\s*(#.*)?$/.test(lines[last].text)) last--;
920
975
  const cut = Math.min(lines[last].end + 1, text.length);
@@ -924,6 +979,7 @@ function planToml(path, text, projectId) {
924
979
  // src/args.ts
925
980
  var FRAMEWORKS = ["next", "vue", "svelte", "angular", "css"];
926
981
  var INTEGRATE_FRAMEWORKS = ["vue", "svelte", "angular", "css"];
982
+ var isIntegrateFramework = (value) => INTEGRATE_FRAMEWORKS.includes(value);
927
983
  var DEFAULT_API_ORIGIN = "https://designsource.app";
928
984
  var CREATE_DEFAULT_FOLDER = "my-design-system";
929
985
  var INTEGRATE_DEFAULT_FOLDER = ".";
@@ -932,6 +988,8 @@ var USAGE = `designsource <command> [options] (also installed as: dss)
932
988
  Commands
933
989
  add [names\u2026] add your design system's UI kit to this React app (theme, components, libraries)
934
990
  connect connect your coding apps (Claude Code, Cursor, VS Code, Codex, Gemini CLI) to this design system
991
+ login sign in for coding agents, so your agent can create design systems from this folder
992
+ logout sign this computer out of the account login signed in to
935
993
  integrate [folder] add the design system to an existing app \u2014 writes design-system/ (default folder: .)
936
994
  create [folder] new Next.js project with the tokens, every component and your mockup page (default folder: ${CREATE_DEFAULT_FOLDER})
937
995
  mcp serve the design system to a coding agent over MCP (stdio) \u2014 for .mcp.json, not for a terminal
@@ -974,6 +1032,7 @@ your components, blocks and sample pages.
974
1032
  --api API origin (default ${DEFAULT_API_ORIGIN})
975
1033
  `;
976
1034
  var APP_IDS = APPS.map((a) => a.id);
1035
+ var isAppId = (id) => APP_IDS.includes(id);
977
1036
  var CONNECT_USAGE = `designsource connect [--apps ${APP_IDS.join(",")}] [--yes] [--token <project token>] [--api <origin>]
978
1037
  designsource connect --forget [--project <id>]
979
1038
 
@@ -996,9 +1055,27 @@ Tokens, component source, the mockup page, an integration guide, and add_ui_kit,
996
1055
  Options
997
1056
  --project the project id; the token comes from this computer's saved one (npx designsource connect)
998
1057
  --token the project token (workbench \u2192 Project settings); or DS_SYNC_TOKEN, which wins over a saved one
1058
+ ${API_LINE}; a token is sent only to the default, a localhost server, or the one connect saved
1059
+ `;
1060
+ var LOGIN_USAGE = `designsource login [--apps ${APP_IDS.join(",")}] [--yes] [--api <origin>]
1061
+
1062
+ Signs this computer in to your designsource account for coding agents, so your agent can create design systems
1063
+ and add the UI kit from this project folder (the nearest folder holding .git, else this one). Shows a code to enter
1064
+ at ${DEFAULT_API_ORIGIN}/device, saves the sign-in privately on this computer, and writes each app's MCP
1065
+ settings here. The settings hold no token, so they are safe to commit. Run it once in each project folder.
1066
+ --apps the apps to set up, comma-separated: ${APP_IDS.join(",")} (default: picked, the ones found ticked)
1067
+ --yes no questions: the apps found on this computer (also outside a terminal)
1068
+ ${API_LINE}; outside a terminal only the default or a server on this computer
1069
+ `;
1070
+ var LOGOUT_USAGE = `designsource logout [--api <origin>]
1071
+
1072
+ Revokes this computer's sign-in on the server and removes it, with its trusted folders, from this computer.
1073
+ Settings files are left as they are.
999
1074
  ${API_LINE}
1000
1075
  `;
1001
1076
  function usageFor(verb) {
1077
+ if (verb === "login") return LOGIN_USAGE;
1078
+ if (verb === "logout") return LOGOUT_USAGE;
1002
1079
  return verb === "add" ? ADD_USAGE : verb === "connect" ? CONNECT_USAGE : verb === "create" ? CREATE_USAGE : verb === "integrate" ? INTEGRATE_USAGE : verb === "mcp" ? MCP_USAGE : USAGE;
1003
1080
  }
1004
1081
  var ArgsError = class extends Error {
@@ -1014,7 +1091,7 @@ function baseArgs(env) {
1014
1091
  return args;
1015
1092
  }
1016
1093
  var HELP = /* @__PURE__ */ new Set(["--help", "-h", "help"]);
1017
- var USE_VERBS = "Use add, connect, integrate, create or mcp.";
1094
+ var USE_VERBS = "Use add, connect, login, logout, integrate, create or mcp.";
1018
1095
  function parseArgs(argv, env) {
1019
1096
  const [first, ...rest] = argv;
1020
1097
  if (first === void 0) return { kind: "menu" };
@@ -1023,6 +1100,8 @@ function parseArgs(argv, env) {
1023
1100
  if (first === "mcp") return parseMcp(rest, env);
1024
1101
  if (first === "add") return parseAdd(rest, env);
1025
1102
  if (first === "connect") return parseConnect(rest, env);
1103
+ if (first === "login") return parseLogin(rest);
1104
+ if (first === "logout") return parseLogout(rest);
1026
1105
  if (first.startsWith("-")) throw new ArgsError(`Missing command. ${USE_VERBS}`, USAGE);
1027
1106
  throw new ArgsError(`Unknown command "${first}". ${USE_VERBS}`, USAGE);
1028
1107
  }
@@ -1036,66 +1115,106 @@ function parseApiOrigin(value, usage) {
1036
1115
  if (!parsed || !parsed.host) throw new ArgsError(`Option --api needs a full origin such as http://localhost:3001 (got "${value}")`, usage);
1037
1116
  return origin;
1038
1117
  }
1039
- var ADD_SWITCHES = { yes: "yes", all: "all", force: "force", "skip-install": "skipInstall", "no-blocks": "noBlocks" };
1118
+ function scan(argv, strings, booleans) {
1119
+ const options = Object.fromEntries([
1120
+ ...strings.map((k) => [k, { type: "string" }]),
1121
+ ...booleans.map((k) => [k, { type: "boolean" }])
1122
+ ]);
1123
+ const { tokens } = scanArgv({ args: argv, options, strict: false, allowPositionals: true, tokens: true });
1124
+ const out = [];
1125
+ for (const t of tokens) {
1126
+ if (t.kind === "positional") {
1127
+ out.push({ kind: "positional", value: t.value });
1128
+ continue;
1129
+ }
1130
+ if (t.kind === "option-terminator") {
1131
+ out.push({ kind: "option", key: "", name: "--", value: void 0, inline: false, known: null });
1132
+ break;
1133
+ }
1134
+ if (t.rawName === "--help" || t.rawName === "-h") return [...out, { kind: "help" }];
1135
+ const name = t.rawName.startsWith("--") ? t.rawName : argv[t.index] ?? t.rawName;
1136
+ const known = strings.includes(t.name) ? "string" : booleans.includes(t.name) && t.rawName.startsWith("--") ? "boolean" : null;
1137
+ out.push({ kind: "option", key: t.name, name, value: t.value, inline: t.inlineValue === true, known });
1138
+ }
1139
+ return out;
1140
+ }
1141
+ function valueOf(arg, usage) {
1142
+ if (arg.value === void 0) throw new ArgsError(`Option --${arg.key} needs a value`, usage);
1143
+ return arg.value;
1144
+ }
1145
+ function switchOf(arg, usage) {
1146
+ if (arg.inline) throw new ArgsError(`Option --${arg.key} takes no value`, usage);
1147
+ return true;
1148
+ }
1149
+ var unknownOption = (arg, usage) => new ArgsError(`Unknown option ${arg.name}`, usage);
1150
+ var ADD_SWITCHES = /* @__PURE__ */ new Map([["yes", "yes"], ["all", "all"], ["force", "force"], ["skip-install", "skipInstall"], ["no-blocks", "noBlocks"]]);
1040
1151
  function parseAdd(argv, env) {
1041
1152
  const args = { components: [], api: DEFAULT_API_ORIGIN, yes: false, all: false, force: false, skipInstall: false, noBlocks: false };
1042
1153
  if (env.DS_SYNC_TOKEN) args.token = env.DS_SYNC_TOKEN;
1043
- for (let i = 0; i < argv.length; i++) {
1044
- const arg = argv[i];
1045
- if (arg === "--help" || arg === "-h") return { kind: "help", verb: "add" };
1046
- if (!arg.startsWith("-")) {
1047
- args.components.push(arg);
1048
- continue;
1049
- }
1050
- if (!arg.startsWith("--")) throw new ArgsError(`Unknown option ${arg}`, ADD_USAGE);
1051
- const eq = arg.indexOf("=");
1052
- const key = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
1053
- if (key in ADD_SWITCHES) {
1054
- if (eq !== -1) throw new ArgsError(`Option --${key} takes no value`, ADD_USAGE);
1055
- args[ADD_SWITCHES[key]] = true;
1154
+ for (const arg of scan(argv, ["token", "api"], [...ADD_SWITCHES.keys()])) {
1155
+ if (arg.kind === "help") return { kind: "help", verb: "add" };
1156
+ if (arg.kind === "positional") {
1157
+ args.components.push(arg.value);
1056
1158
  continue;
1057
1159
  }
1058
- if (key !== "token" && key !== "api") throw new ArgsError(`Unknown option --${key}`, ADD_USAGE);
1059
- const value = eq === -1 ? argv[++i] : arg.slice(eq + 1);
1060
- if (value === void 0) throw new ArgsError(`Option --${key} needs a value`, ADD_USAGE);
1061
- if (key === "token") args.token = value;
1160
+ const field = arg.known === "boolean" ? ADD_SWITCHES.get(arg.key) : void 0;
1161
+ if (field) args[field] = switchOf(arg, ADD_USAGE);
1162
+ else if (arg.known === null) throw unknownOption(arg, ADD_USAGE);
1163
+ else if (arg.key === "token") args.token = valueOf(arg, ADD_USAGE);
1062
1164
  else {
1063
- args.api = parseApiOrigin(value, ADD_USAGE);
1165
+ args.api = parseApiOrigin(valueOf(arg, ADD_USAGE), ADD_USAGE);
1064
1166
  args.apiGiven = true;
1065
1167
  }
1066
1168
  }
1067
1169
  return { kind: "add", args };
1068
1170
  }
1069
- function appsIn(value) {
1171
+ function appsIn(value, usage = CONNECT_USAGE) {
1070
1172
  const ids = [...new Set(value.split(/[\s,]+/).filter(Boolean))];
1071
- if (ids.length === 0) throw new ArgsError(`Option --apps needs one or more of ${APP_IDS.join(", ")}`, CONNECT_USAGE);
1072
- const unknown = ids.find((id) => !APP_IDS.includes(id));
1073
- if (unknown !== void 0) throw new ArgsError(`Unknown app "${unknown}". Use ${APP_IDS.slice(0, -1).join(", ")} or ${APP_IDS.at(-1)}.`, CONNECT_USAGE);
1074
- return ids;
1173
+ if (ids.length === 0) throw new ArgsError(`Option --apps needs one or more of ${APP_IDS.join(", ")}`, usage);
1174
+ const unknown = ids.find((id) => !isAppId(id));
1175
+ if (unknown !== void 0) throw new ArgsError(`Unknown app "${unknown}". Use ${APP_IDS.slice(0, -1).join(", ")} or ${APP_IDS.at(-1)}.`, usage);
1176
+ return ids.filter(isAppId);
1177
+ }
1178
+ function parseLogin(argv) {
1179
+ const args = { api: DEFAULT_API_ORIGIN, apiGiven: false, apps: null, yes: false };
1180
+ for (const arg of scan(argv, ["apps", "api"], ["yes"])) {
1181
+ if (arg.kind === "help") return { kind: "help", verb: "login" };
1182
+ if (arg.kind === "positional") throw new ArgsError("login takes no folder: run it in the project folder", LOGIN_USAGE);
1183
+ if (arg.known === null) throw unknownOption(arg, LOGIN_USAGE);
1184
+ if (arg.key === "yes") args.yes = switchOf(arg, LOGIN_USAGE);
1185
+ else if (arg.key === "apps") args.apps = appsIn(valueOf(arg, LOGIN_USAGE), LOGIN_USAGE);
1186
+ else {
1187
+ args.api = parseApiOrigin(valueOf(arg, LOGIN_USAGE), LOGIN_USAGE);
1188
+ args.apiGiven = true;
1189
+ }
1190
+ }
1191
+ return { kind: "login", args };
1192
+ }
1193
+ function parseLogout(argv) {
1194
+ const args = { api: DEFAULT_API_ORIGIN, apiGiven: false };
1195
+ for (const arg of scan(argv, ["api"], [])) {
1196
+ if (arg.kind === "help") return { kind: "help", verb: "logout" };
1197
+ if (arg.kind === "positional") throw new ArgsError("logout takes no folder", LOGOUT_USAGE);
1198
+ if (arg.known === null) throw unknownOption(arg, LOGOUT_USAGE);
1199
+ args.api = parseApiOrigin(valueOf(arg, LOGOUT_USAGE), LOGOUT_USAGE);
1200
+ args.apiGiven = true;
1201
+ }
1202
+ return { kind: "logout", args };
1075
1203
  }
1076
- var CONNECT_SWITCHES = { yes: "yes", forget: "forget" };
1077
1204
  function parseConnect(argv, env) {
1078
1205
  const args = { api: DEFAULT_API_ORIGIN, yes: false, forget: false };
1079
1206
  if (env.DS_SYNC_TOKEN) args.token = env.DS_SYNC_TOKEN;
1080
- for (let i = 0; i < argv.length; i++) {
1081
- const arg = argv[i];
1082
- if (arg === "--help" || arg === "-h") return { kind: "help", verb: "connect" };
1083
- if (!arg.startsWith("--")) throw new ArgsError(arg.startsWith("-") ? `Unknown option ${arg}` : "connect takes no folder: run it in the project folder", CONNECT_USAGE);
1084
- const eq = arg.indexOf("=");
1085
- const key = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
1086
- if (key in CONNECT_SWITCHES) {
1087
- if (eq !== -1) throw new ArgsError(`Option --${key} takes no value`, CONNECT_USAGE);
1088
- args[CONNECT_SWITCHES[key]] = true;
1089
- continue;
1090
- }
1091
- if (key !== "apps" && key !== "token" && key !== "api" && key !== "project") throw new ArgsError(`Unknown option --${key}`, CONNECT_USAGE);
1092
- const value = eq === -1 ? argv[++i] : arg.slice(eq + 1);
1093
- if (value === void 0) throw new ArgsError(`Option --${key} needs a value`, CONNECT_USAGE);
1094
- if (key === "apps") args.apps = appsIn(value);
1095
- else if (key === "token") args.token = value;
1096
- else if (key === "project") args.project = value;
1207
+ for (const arg of scan(argv, ["apps", "token", "api", "project"], ["yes", "forget"])) {
1208
+ if (arg.kind === "help") return { kind: "help", verb: "connect" };
1209
+ if (arg.kind === "positional") throw new ArgsError("connect takes no folder: run it in the project folder", CONNECT_USAGE);
1210
+ if (arg.known === null) throw unknownOption(arg, CONNECT_USAGE);
1211
+ if (arg.key === "yes") args.yes = switchOf(arg, CONNECT_USAGE);
1212
+ else if (arg.key === "forget") args.forget = switchOf(arg, CONNECT_USAGE);
1213
+ else if (arg.key === "apps") args.apps = appsIn(valueOf(arg, CONNECT_USAGE));
1214
+ else if (arg.key === "token") args.token = valueOf(arg, CONNECT_USAGE);
1215
+ else if (arg.key === "project") args.project = valueOf(arg, CONNECT_USAGE);
1097
1216
  else {
1098
- args.api = parseApiOrigin(value, CONNECT_USAGE);
1217
+ args.api = parseApiOrigin(valueOf(arg, CONNECT_USAGE), CONNECT_USAGE);
1099
1218
  args.apiGiven = true;
1100
1219
  }
1101
1220
  }
@@ -1105,17 +1224,13 @@ function parseConnect(argv, env) {
1105
1224
  function parseMcp(argv, env) {
1106
1225
  const args = { api: DEFAULT_API_ORIGIN };
1107
1226
  if (env.DS_SYNC_TOKEN) args.token = env.DS_SYNC_TOKEN;
1108
- for (let i = 0; i < argv.length; i++) {
1109
- const arg = argv[i];
1110
- if (arg === "--help" || arg === "-h") return { kind: "help", verb: "mcp" };
1111
- if (!arg.startsWith("--")) throw new ArgsError(arg.startsWith("-") ? `Unknown option ${arg}` : "mcp takes no folder", MCP_USAGE);
1112
- const eq = arg.indexOf("=");
1113
- const key = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
1114
- const value = eq === -1 ? argv[++i] : arg.slice(eq + 1);
1115
- if (key !== "token" && key !== "api" && key !== "project") throw new ArgsError(`Unknown option --${key}`, MCP_USAGE);
1116
- if (value === void 0) throw new ArgsError(`Option --${key} needs a value`, MCP_USAGE);
1117
- if (key === "token") args.token = value;
1118
- else if (key === "project") {
1227
+ for (const arg of scan(argv, ["token", "api", "project"], [])) {
1228
+ if (arg.kind === "help") return { kind: "help", verb: "mcp" };
1229
+ if (arg.kind === "positional") throw new ArgsError("mcp takes no folder", MCP_USAGE);
1230
+ if (arg.known === null) throw unknownOption(arg, MCP_USAGE);
1231
+ const value = valueOf(arg, MCP_USAGE);
1232
+ if (arg.key === "token") args.token = value;
1233
+ else if (arg.key === "project") {
1119
1234
  if (!/^[A-Za-z0-9_-]+$/.test(value)) throw new ArgsError("--project must be a project id from the workbench (letters, digits, - and _).", MCP_USAGE);
1120
1235
  args.project = value;
1121
1236
  } else {
@@ -1128,39 +1243,25 @@ function parseMcp(argv, env) {
1128
1243
  function parseVerb(verb, argv, env) {
1129
1244
  const usage = usageFor(verb);
1130
1245
  const args = baseArgs(env);
1131
- for (let i = 0; i < argv.length; i++) {
1132
- const arg = argv[i];
1133
- if (arg === "--help" || arg === "-h") return { kind: "help", verb };
1134
- if (arg === "--force") {
1135
- args.force = true;
1246
+ const strings = verb === "integrate" ? ["framework", "token", "api"] : ["token", "api"];
1247
+ for (const arg of scan(argv, strings, ["force"])) {
1248
+ if (arg.kind === "help") return { kind: "help", verb };
1249
+ if (arg.kind === "positional") {
1250
+ if (args.folder !== void 0) throw new ArgsError("Expected one folder argument", usage);
1251
+ args.folder = arg.value;
1136
1252
  continue;
1137
1253
  }
1138
- if (arg.startsWith("--")) {
1139
- const eq = arg.indexOf("=");
1140
- const key = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
1141
- const value = eq === -1 ? argv[++i] : arg.slice(eq + 1);
1142
- const needs = () => {
1143
- if (value === void 0) throw new ArgsError(`Option --${key} needs a value`, usage);
1144
- };
1145
- if (key === "framework" && verb === "integrate") {
1146
- needs();
1147
- if (!INTEGRATE_FRAMEWORKS.includes(value)) {
1148
- throw new ArgsError(`Unknown framework "${value}" \u2014 one of ${INTEGRATE_FRAMEWORKS.join(", ")}`, usage);
1149
- }
1150
- args.framework = value;
1151
- } else if (key === "token") {
1152
- needs();
1153
- args.token = value;
1154
- } else if (key === "api") {
1155
- needs();
1156
- args.api = parseApiOrigin(value, usage);
1157
- args.apiGiven = true;
1158
- } else throw new ArgsError(`Unknown option --${key}`, usage);
1159
- continue;
1254
+ if (arg.known === null) throw unknownOption(arg, usage);
1255
+ if (arg.key === "force") args.force = switchOf(arg, usage);
1256
+ else if (arg.key === "framework") {
1257
+ const value = valueOf(arg, usage);
1258
+ if (!isIntegrateFramework(value)) throw new ArgsError(`Unknown framework "${value}" \u2014 one of ${INTEGRATE_FRAMEWORKS.join(", ")}`, usage);
1259
+ args.framework = value;
1260
+ } else if (arg.key === "token") args.token = valueOf(arg, usage);
1261
+ else {
1262
+ args.api = parseApiOrigin(valueOf(arg, usage), usage);
1263
+ args.apiGiven = true;
1160
1264
  }
1161
- if (arg.startsWith("-")) throw new ArgsError(`Unknown option ${arg}`, usage);
1162
- if (args.folder !== void 0) throw new ArgsError("Expected one folder argument", usage);
1163
- args.folder = arg;
1164
1265
  }
1165
1266
  if (verb === "create") {
1166
1267
  const { framework: _drop, ...common } = args;
@@ -1226,14 +1327,14 @@ function quoteArg(arg) {
1226
1327
  function childEnv(env) {
1227
1328
  return Object.fromEntries(Object.entries(env).filter(([name]) => name.toUpperCase() !== "DS_SYNC_TOKEN"));
1228
1329
  }
1229
- var spawnExec = (cmd, args, { cwd, timeoutMs, input, stdoutOnly }) => new Promise((resolve6) => {
1330
+ var spawnExec = (cmd, args, { cwd, timeoutMs, input, stdoutOnly }) => new Promise((resolve8) => {
1230
1331
  let output = "";
1231
1332
  let child;
1232
1333
  try {
1233
1334
  const shell = process.platform === "win32";
1234
1335
  child = spawn(cmd, shell ? args.map(quoteArg) : args, { cwd, env: childEnv(process.env), stdio: [input === void 0 ? "ignore" : "pipe", "pipe", "pipe"], shell });
1235
1336
  } catch (e) {
1236
- resolve6({ code: 127, output: e instanceof Error ? e.message : String(e) });
1337
+ resolve8({ code: 127, output: e instanceof Error ? e.message : String(e) });
1237
1338
  return;
1238
1339
  }
1239
1340
  let timedOut = false;
@@ -1243,7 +1344,7 @@ var spawnExec = (cmd, args, { cwd, timeoutMs, input, stdoutOnly }) => new Promis
1243
1344
  }, timeoutMs);
1244
1345
  const done = (result) => {
1245
1346
  if (timer) clearTimeout(timer);
1246
- resolve6(timedOut ? { code: result.code === 0 ? 124 : result.code, output: `${result.output.trimEnd()}
1347
+ resolve8(timedOut ? { code: result.code === 0 ? 124 : result.code, output: `${result.output.trimEnd()}
1247
1348
  timed out after ${timeoutMs / 1e3}s` } : result);
1248
1349
  };
1249
1350
  child.stdout?.on("data", (chunk) => {
@@ -1886,6 +1987,58 @@ function readDarkMarker(css) {
1886
1987
  return { marker: DEFAULT_MARKER, known: false, selector };
1887
1988
  }
1888
1989
 
1990
+ // src/http.ts
1991
+ var FETCH_TIMEOUT_MS = 3e4;
1992
+ var ApiError = class extends CliError {
1993
+ constructor(message, status) {
1994
+ super(message);
1995
+ Object.defineProperty(this, "status", { value: status, enumerable: false });
1996
+ }
1997
+ };
1998
+ async function getJson(opts, fetchImpl = fetch) {
1999
+ const url = new URL(opts.path, `${opts.api}/`);
2000
+ for (const [k, v] of Object.entries(opts.query ?? {})) url.searchParams.set(k, v);
2001
+ const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
2002
+ let res;
2003
+ try {
2004
+ res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" }, signal });
2005
+ } catch {
2006
+ throw new ApiError(UNREACHABLE(opts.api), null);
2007
+ }
2008
+ let body = null;
2009
+ try {
2010
+ body = await res.json();
2011
+ } catch {
2012
+ if (signal.aborted) throw new ApiError(UNREACHABLE(opts.api), null);
2013
+ }
2014
+ if (!res.ok) throw new ApiError((opts.messages ?? messageForResponse)(res.status, body, opts.api), res.status);
2015
+ return body;
2016
+ }
2017
+ async function requestJson(opts, fetchImpl = fetch) {
2018
+ const url = new URL(opts.path, `${opts.api}/`);
2019
+ const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
2020
+ const headers = { Accept: "application/json" };
2021
+ if (opts.token !== void 0) headers.Authorization = `Bearer ${opts.token}`;
2022
+ const init = { method: opts.method, headers, signal };
2023
+ if (opts.body !== void 0) {
2024
+ headers["Content-Type"] = "application/json";
2025
+ init.body = JSON.stringify(opts.body);
2026
+ }
2027
+ let res;
2028
+ try {
2029
+ res = await fetchImpl(url.toString(), init);
2030
+ } catch {
2031
+ throw new ApiError(UNREACHABLE(opts.api), null);
2032
+ }
2033
+ let body = null;
2034
+ try {
2035
+ body = await res.json();
2036
+ } catch {
2037
+ if (signal.aborted) throw new ApiError(UNREACHABLE(opts.api), null);
2038
+ }
2039
+ return { status: res.status, body };
2040
+ }
2041
+
1889
2042
  // src/add/kit-manifest.ts
1890
2043
  var malformed = () => new CliError("Unexpected response from the API \u2014 not a kit manifest.");
1891
2044
  var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
@@ -1931,16 +2084,8 @@ function validateKitManifest(json) {
1931
2084
 
1932
2085
  // src/add/fetch-kit.ts
1933
2086
  async function fetchKit(opts, fetchImpl = fetch) {
1934
- const url = new URL("/api/kit", `${opts.api}/`);
1935
- let res;
1936
- try {
1937
- res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" } });
1938
- } catch {
1939
- throw new CliError(UNREACHABLE(opts.api));
1940
- }
1941
- const body = await res.json().catch(() => null);
1942
- if (!res.ok) throw new CliError(messageForResponse(res.status, body, opts.api));
1943
- return validateKitManifest(body);
2087
+ const { api, token, path = "/api/kit", messages } = opts;
2088
+ return validateKitManifest(await getJson({ api, token, path, ...messages ? { messages } : {} }, fetchImpl));
1944
2089
  }
1945
2090
 
1946
2091
  // src/add/plan-packages.ts
@@ -2468,7 +2613,7 @@ async function runAdd(input, deps) {
2468
2613
  const cssAbs = resolveInside(root, planned.cssFile);
2469
2614
  if (!existsSync8(cssAbs)) throw new CliError(NO_THEME_FILE(planned.cssFile));
2470
2615
  assertKitUtils(root, info, planned);
2471
- const manifest = await fetchKit({ api: input.api, token: input.token }, deps.fetchImpl);
2616
+ const manifest = await fetchKit({ api: input.api, token: input.token, path: input.kitPath, messages: input.messages }, deps.fetchImpl);
2472
2617
  const onDisk = sectionPresent(root, planned);
2473
2618
  const chosen = await chooseComponents(input, manifest, previouslyAdded(root, planned), onDisk.present, deps.questions);
2474
2619
  const section = planSection(root, input, info, planned, manifest, chosen, onDisk);
@@ -2583,8 +2728,42 @@ function summaryLines(r, reader = "cli") {
2583
2728
  }
2584
2729
 
2585
2730
  // src/connect/api-for.ts
2586
- function apiFor(args, entry) {
2587
- return args.apiGiven ? args.api : entry?.api ?? args.api;
2731
+ 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.`;
2732
+ 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.`;
2733
+ function apiFor(args, saved) {
2734
+ if (!saved) return args.api;
2735
+ if (!args.apiGiven) return saved.api ?? args.api;
2736
+ const origin = saved.api ?? DEFAULT_API_ORIGIN;
2737
+ if (!sameApi(args.api, origin)) throw new CliError(SAVED_TOKEN_OTHER_SERVER(saved.name, origin, args.api));
2738
+ return origin;
2739
+ }
2740
+ function givenTokenApi(args, entry) {
2741
+ if (!args.apiGiven) return entry?.api ?? args.api;
2742
+ const trusted = sameApi(args.api, DEFAULT_API_ORIGIN) || isLoopback(args.api) || entry?.api !== void 0 && sameApi(args.api, entry.api);
2743
+ if (!trusted) throw new CliError(UNTRUSTED_SERVER(args.api));
2744
+ return args.api;
2745
+ }
2746
+ function sameApi(a, b) {
2747
+ const key = (value) => {
2748
+ try {
2749
+ const url = new URL(value);
2750
+ if (url.username || url.password) return null;
2751
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
2752
+ } catch {
2753
+ return null;
2754
+ }
2755
+ };
2756
+ const ka = key(a);
2757
+ return ka !== null && ka === key(b);
2758
+ }
2759
+ function isLoopback(value) {
2760
+ let host;
2761
+ try {
2762
+ host = new URL(value).hostname;
2763
+ } catch {
2764
+ return false;
2765
+ }
2766
+ return host === "localhost" || host.endsWith(".localhost") || /^127(?:\.\d{1,3}){3}$/.test(host) || host === "[::1]";
2588
2767
  }
2589
2768
 
2590
2769
  // src/picker.ts
@@ -2629,10 +2808,10 @@ function nextLine() {
2629
2808
  if (line !== void 0) return Promise.resolve(line);
2630
2809
  if (closed) return Promise.reject(new CliError(EOF_MESSAGE));
2631
2810
  process.stdin.ref?.();
2632
- return new Promise((resolve6, reject) => waiting.push({
2811
+ return new Promise((resolve8, reject) => waiting.push({
2633
2812
  resolve: (line2) => {
2634
2813
  process.stdin.unref?.();
2635
- resolve6(line2);
2814
+ resolve8(line2);
2636
2815
  },
2637
2816
  reject: (err) => {
2638
2817
  process.stdin.unref?.();
@@ -2745,7 +2924,7 @@ function pickTty(question, options, start, stdin, stdout) {
2745
2924
  stdin.resume();
2746
2925
  stdout.write("\x1B[?25l");
2747
2926
  draw([question, ...rows()]);
2748
- return new Promise((resolve6, reject) => {
2927
+ return new Promise((resolve8, reject) => {
2749
2928
  const finish = (after) => {
2750
2929
  stdin.off("keypress", onKey);
2751
2930
  stdin.setRawMode(false);
@@ -2766,7 +2945,7 @@ function pickTty(question, options, start, stdin, stdout) {
2766
2945
  stdout.write(`\r\x1B[J${question} ${chosen.label}
2767
2946
  `);
2768
2947
  });
2769
- resolve6(chosen.value);
2948
+ resolve8(chosen.value);
2770
2949
  return;
2771
2950
  }
2772
2951
  if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
@@ -2798,7 +2977,7 @@ function pickManyTty(question, options, preselected, stdin, stdout) {
2798
2977
  stdin.resume();
2799
2978
  stdout.write("\x1B[?25l");
2800
2979
  draw([head, ...rows()]);
2801
- return new Promise((resolve6, reject) => {
2980
+ return new Promise((resolve8, reject) => {
2802
2981
  const finish = (after) => {
2803
2982
  stdin.off("keypress", onKey);
2804
2983
  stdin.setRawMode(false);
@@ -2819,7 +2998,7 @@ function pickManyTty(question, options, preselected, stdin, stdout) {
2819
2998
  stdout.write(`\r\x1B[J${question} ${chosen.length > 0 ? chosen.map((o) => o.label).join(", ") : "none"}
2820
2999
  `);
2821
3000
  });
2822
- resolve6(chosen.map((o) => o.value));
3001
+ resolve8(chosen.map((o) => o.value));
2823
3002
  return;
2824
3003
  }
2825
3004
  if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
@@ -2834,13 +3013,16 @@ function pickManyTty(question, options, preselected, stdin, stdout) {
2834
3013
  });
2835
3014
  }
2836
3015
 
3016
+ // src/commands/scaffold.ts
3017
+ import { resolve as resolve4 } from "node:path";
3018
+
2837
3019
  // src/connect/resolve-token.ts
2838
3020
  import { homedir } from "node:os";
2839
3021
 
2840
3022
  // src/connect/store.ts
2841
3023
  import { randomBytes } from "node:crypto";
2842
3024
  import { chmodSync, constants, copyFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync9, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
2843
- import { dirname as dirname2, isAbsolute as isAbsolute2, join as join6, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
3025
+ import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join6, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
2844
3026
  var WHERE = ["keychain", "secret-service", "dpapi", "file"];
2845
3027
  function credentialsPath(env, platform, home) {
2846
3028
  if (platform === "win32") return join6(env.APPDATA || join6(home, "AppData", "Roaming"), "designsource", "credentials.json");
@@ -2902,10 +3084,13 @@ function detach(data, keep, folder) {
2902
3084
  return changed;
2903
3085
  }
2904
3086
  function writeCredentials(path, data) {
3087
+ writePrivateJson(path, data);
3088
+ }
3089
+ function writePrivateJson(path, data) {
2905
3090
  const dir = dirname2(path);
2906
3091
  mkdirSync2(dir, { recursive: true, mode: 448 });
2907
3092
  chmodSync(dir, 448);
2908
- const temp = join6(dir, `.credentials.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
3093
+ const temp = join6(dir, `.${basename(path, ".json")}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
2909
3094
  try {
2910
3095
  writeFileSync3(temp, `${JSON.stringify(data, null, 2)}
2911
3096
  `, { mode: 384, flag: "wx" });
@@ -3039,18 +3224,8 @@ function validateManifest(json) {
3039
3224
 
3040
3225
  // src/fetch-manifest.ts
3041
3226
  async function fetchManifest(opts, fetchImpl = fetch) {
3042
- const url = new URL("/api/starter", `${opts.api}/`);
3043
- url.searchParams.set("framework", opts.framework);
3044
- if (opts.name) url.searchParams.set("name", opts.name);
3045
- let res;
3046
- try {
3047
- res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" } });
3048
- } catch {
3049
- throw new CliError(UNREACHABLE(opts.api));
3050
- }
3051
- const body = await res.json().catch(() => null);
3052
- if (!res.ok) throw new CliError(messageForResponse(res.status, body, opts.api));
3053
- return validateManifest(body);
3227
+ const query = { framework: opts.framework, ...opts.name ? { name: opts.name } : {} };
3228
+ return validateManifest(await getJson({ api: opts.api, token: opts.token, path: "/api/starter", query }, fetchImpl));
3054
3229
  }
3055
3230
 
3056
3231
  // src/package-name.ts
@@ -3071,12 +3246,12 @@ function detectRunner(userAgent) {
3071
3246
  }
3072
3247
  var INSTALL = { pnpm: "pnpm install", npm: "npm install", yarn: "yarn", bun: "bun install" };
3073
3248
  var DEV = { pnpm: "pnpm dev", npm: "npm run dev", yarn: "yarn dev", bun: "bun dev" };
3074
- function nextStepsText({ runner, framework, folder, created }) {
3249
+ function nextStepsText({ runner, framework, folder, here }) {
3075
3250
  const lines = ["Next steps:"];
3076
3251
  if (framework === "next") {
3077
- if (created) lines.push(` cd ${folder}`);
3252
+ if (!here) lines.push(` cd ${folder}`);
3078
3253
  lines.push(` ${INSTALL[runner]}`, ` ${DEV[runner]}`);
3079
- } else if (folder === ".") {
3254
+ } else if (here) {
3080
3255
  lines.push(" Open design-system/PROMPT.md and paste it into your coding agent.");
3081
3256
  } else {
3082
3257
  lines.push(` Open ${folder}/design-system/PROMPT.md and paste it into your coding agent, run from ${folder}.`);
@@ -3118,7 +3293,7 @@ async function scaffold(input, env, io) {
3118
3293
  ${written.map((p) => ` ${p}`).join("\n")}
3119
3294
 
3120
3295
  `);
3121
- io.stdout(nextStepsText({ runner, framework, folder, created }));
3296
+ io.stdout(nextStepsText({ runner, framework, folder, here: root === resolve4(io.cwd) }));
3122
3297
  }
3123
3298
 
3124
3299
  // src/commands/add.ts
@@ -3197,16 +3372,13 @@ var RejectedTokenError = class extends CliError {
3197
3372
  };
3198
3373
  var malformed3 = () => new CliError("Unexpected response from the API \u2014 not a project.");
3199
3374
  async function fetchProject(opts, fetchImpl = fetch) {
3200
- const url = new URL("/api/project", `${opts.api}/`);
3201
- let res;
3375
+ let body;
3202
3376
  try {
3203
- res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" } });
3204
- } catch {
3205
- throw new CliError(UNREACHABLE(opts.api));
3377
+ body = await getJson({ api: opts.api, token: opts.token, path: "/api/project" }, fetchImpl);
3378
+ } catch (e) {
3379
+ if (e instanceof ApiError && e.status === 401) throw new RejectedTokenError();
3380
+ throw e;
3206
3381
  }
3207
- const body = await res.json().catch(() => null);
3208
- if (res.status === 401) throw new RejectedTokenError();
3209
- if (!res.ok) throw new CliError(messageForResponse(res.status, body, opts.api));
3210
3382
  if (typeof body !== "object" || body === null) throw malformed3();
3211
3383
  const { id, name } = body;
3212
3384
  if (typeof id !== "string" || typeof name !== "string") throw malformed3();
@@ -3216,13 +3388,13 @@ async function fetchProject(opts, fetchImpl = fetch) {
3216
3388
 
3217
3389
  // src/connect/project-root.ts
3218
3390
  import { existsSync as existsSync9 } from "node:fs";
3219
- import { dirname as dirname3, isAbsolute as isAbsolute3, join as join7, relative as relative3, resolve as resolve4, sep as sep3 } from "node:path";
3391
+ import { dirname as dirname3, isAbsolute as isAbsolute3, join as join7, relative as relative3, resolve as resolve5, sep as sep3 } from "node:path";
3220
3392
  function projectRoot(cwd, exists = existsSync9) {
3221
- let dir = resolve4(cwd);
3393
+ let dir = resolve5(cwd);
3222
3394
  for (; ; ) {
3223
3395
  if (exists(join7(dir, ".git"))) return dir;
3224
3396
  const parent = dirname3(dir);
3225
- if (parent === dir) return resolve4(cwd);
3397
+ if (parent === dir) return resolve5(cwd);
3226
3398
  dir = parent;
3227
3399
  }
3228
3400
  }
@@ -3231,8 +3403,8 @@ function within2(folder, root) {
3231
3403
  return rel === "" || rel !== ".." && !rel.startsWith(`..${sep3}`) && !isAbsolute3(rel);
3232
3404
  }
3233
3405
  function homeFolderRefusal(root, home) {
3234
- const folder = resolve4(root);
3235
- const homeDir = resolve4(home);
3406
+ const folder = resolve5(root);
3407
+ const homeDir = resolve5(home);
3236
3408
  const tail = "and writing there would set up every project on this computer.";
3237
3409
  if (folder === homeDir) return `Run this in your project folder \u2014 ${folder} is your home folder, ${tail}`;
3238
3410
  if (dirname3(folder) === folder || within2(homeDir, folder)) return `Run this in your project folder \u2014 ${folder} is a system folder, ${tail}`;
@@ -3292,7 +3464,7 @@ function appLines(id, plan) {
3292
3464
  return lines;
3293
3465
  }
3294
3466
  const entry = (plan.manualEntry ?? "").split("\n").map((l) => ` ${l}`);
3295
- const why = format === "toml" ? `${head}: it defines designsource another way, so it was not changed. Put this table in its place:` : `${head}: it has comments or is not plain JSON, so it was not changed. Add this entry under "${key}":`;
3467
+ const why = format === "toml" ? `${head}: it defines designsource another way, so it was not changed. Put this table in its place:` : plan.manualReason === "foreign-entry" ? `${head}: it defines designsource another way, so it was not changed. Put this entry in its place under "${key}":` : `${head}: it has comments or is not plain JSON, so it was not changed. Add this entry under "${key}":`;
3296
3468
  return [why, ...entry];
3297
3469
  }
3298
3470
  function closingLines(apps, changed) {
@@ -3417,13 +3589,485 @@ async function runIntegrate(args, env, io, store) {
3417
3589
  await scaffold({ folder, framework, token, api: apiFor(args, saved?.entry), force: args.force }, env, io);
3418
3590
  }
3419
3591
 
3592
+ // src/commands/login.ts
3593
+ import { existsSync as existsSync11 } from "node:fs";
3594
+ import { join as join10 } from "node:path";
3595
+ import { homedir as homedir3, hostname } from "node:os";
3596
+
3597
+ // src/connect/account-store.ts
3598
+ import { createHash as createHash2 } from "node:crypto";
3599
+ import { readFileSync as readFileSync10, realpathSync } from "node:fs";
3600
+ import { dirname as dirname4, join as join9, parse, resolve as resolve6, sep as sep4 } from "node:path";
3601
+ var WHERE2 = ["keychain", "secret-service", "dpapi", "file"];
3602
+ var ACCOUNT_TOKEN = /^dsa_[A-Za-z0-9_-]{43}$/;
3603
+ var PROJECT_ID2 = /^[A-Za-z0-9_-]+$/;
3604
+ var LABEL = "account";
3605
+ function normaliseOrigin(origin) {
3606
+ let url;
3607
+ try {
3608
+ url = new URL(origin);
3609
+ } catch {
3610
+ throw new CliError(`Not a server address: ${JSON.stringify(origin)}.`);
3611
+ }
3612
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new CliError("A server address must start with http:// or https://.");
3613
+ if (url.username || url.password) throw new CliError("A server address must not carry a user name or password.");
3614
+ return `${url.origin.toLowerCase()}${url.pathname.replace(/\/+$/, "")}`;
3615
+ }
3616
+ function accountSecretId(origin) {
3617
+ const id = `account-${createHash2("sha256").update(normaliseOrigin(origin)).digest("hex").slice(0, 16)}`;
3618
+ assertProjectId(id);
3619
+ return id;
3620
+ }
3621
+ function accountPath(env, platform, home) {
3622
+ return join9(dirname4(credentialsPath(env, platform, home)), "account.json");
3623
+ }
3624
+ function normaliseFolder(folder) {
3625
+ let path = resolve6(folder);
3626
+ try {
3627
+ path = realpathSync(path);
3628
+ } catch {
3629
+ }
3630
+ const root = parse(path).root;
3631
+ while (path.length > root.length && (path.endsWith(sep4) || path.endsWith("/"))) path = path.slice(0, -1);
3632
+ return path;
3633
+ }
3634
+ function isRecord2(value) {
3635
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3636
+ }
3637
+ function readAccount(value) {
3638
+ if (!isRecord2(value)) return null;
3639
+ const { email, where, folders, links, secret } = value;
3640
+ if (typeof email !== "string" || !WHERE2.includes(where)) return null;
3641
+ if (!Array.isArray(folders) || !folders.every((f) => typeof f === "string")) return null;
3642
+ if (!isRecord2(links) || !Object.values(links).every((id) => typeof id === "string" && PROJECT_ID2.test(id))) return null;
3643
+ if (secret !== void 0 && typeof secret !== "string") return null;
3644
+ const entry = { email, where, folders: [...folders], links: Object.assign(/* @__PURE__ */ Object.create(null), links) };
3645
+ if (secret !== void 0) entry.secret = secret;
3646
+ return entry;
3647
+ }
3648
+ function readAccounts(path) {
3649
+ const accounts = /* @__PURE__ */ Object.create(null);
3650
+ let text;
3651
+ try {
3652
+ text = readFileSync10(path, "utf8");
3653
+ } catch {
3654
+ return { version: 1, accounts };
3655
+ }
3656
+ let parsed;
3657
+ try {
3658
+ parsed = JSON.parse(text);
3659
+ } catch {
3660
+ return { version: 1, accounts, unreadable: true };
3661
+ }
3662
+ if (!isRecord2(parsed) || parsed.version !== 1 || !isRecord2(parsed.accounts)) return { version: 1, accounts, unreadable: true };
3663
+ for (const [origin, value] of Object.entries(parsed.accounts)) {
3664
+ const entry = readAccount(value);
3665
+ if (entry) accounts[origin] = entry;
3666
+ }
3667
+ return { version: 1, accounts };
3668
+ }
3669
+ function publicEntry2(origin, e) {
3670
+ return { origin, email: e.email, where: e.where, folders: [...e.folders], links: { ...e.links } };
3671
+ }
3672
+ function createAccountStore(opts) {
3673
+ const { env, platform, exec, home } = opts;
3674
+ const path = accountPath(env, platform, home);
3675
+ const forceFile = env.DESIGNSOURCE_STORE === "file";
3676
+ const osBackend = (where) => where === "file" ? null : backendFor(where, exec, home);
3677
+ const update = (origin, change) => {
3678
+ const key = normaliseOrigin(origin);
3679
+ const data = readAccounts(path);
3680
+ const entry = Object.hasOwn(data.accounts, key) ? data.accounts[key] : null;
3681
+ if (!entry) return null;
3682
+ if (change(entry)) writePrivateJson(path, data);
3683
+ return publicEntry2(key, entry);
3684
+ };
3685
+ return {
3686
+ all() {
3687
+ return Object.entries(readAccounts(path).accounts).map(([origin, e]) => publicEntry2(origin, e));
3688
+ },
3689
+ get(origin) {
3690
+ const key = normaliseOrigin(origin);
3691
+ const { accounts } = readAccounts(path);
3692
+ return Object.hasOwn(accounts, key) ? publicEntry2(key, accounts[key]) : null;
3693
+ },
3694
+ async token(origin) {
3695
+ const key = normaliseOrigin(origin);
3696
+ const { accounts } = readAccounts(path);
3697
+ if (!Object.hasOwn(accounts, key)) return null;
3698
+ const entry = accounts[key];
3699
+ const value = entry.where === "file" ? entry.secret ?? null : await osBackend(entry.where).get(accountSecretId(key), entry.secret);
3700
+ return value !== null && ACCOUNT_TOKEN.test(value) ? value : null;
3701
+ },
3702
+ async save({ origin, email, token, folder }) {
3703
+ const key = normaliseOrigin(origin);
3704
+ if (!ACCOUNT_TOKEN.test(token)) throw new CliError("Unexpected account token from the API.");
3705
+ const id = accountSecretId(key);
3706
+ const { unreadable, ...data } = readAccounts(path);
3707
+ const previous = Object.hasOwn(data.accounts, key) ? data.accounts[key] : void 0;
3708
+ const folders = [.../* @__PURE__ */ new Set([...previous?.folders ?? [], normaliseFolder(folder)])];
3709
+ const links = Object.assign(/* @__PURE__ */ Object.create(null), previous?.links);
3710
+ let entry = { email, where: "file", folders, links, secret: token };
3711
+ const backend = forceFile ? null : await chooseBackend({ platform, exec, cwd: home, token });
3712
+ if (backend) {
3713
+ const kept = await backend.put(id, LABEL, token);
3714
+ if (kept) entry = { email, where: backend.where, folders, links, ...kept.secret === void 0 ? {} : { secret: kept.secret } };
3715
+ }
3716
+ data.accounts[key] = entry;
3717
+ const backup = unreadable ? backUp(path) : void 0;
3718
+ writePrivateJson(path, data);
3719
+ if (previous && previous.where !== entry.where) await osBackend(previous.where)?.remove(id);
3720
+ return { ...publicEntry2(key, entry), ...backup === void 0 ? {} : { backup } };
3721
+ },
3722
+ trust(origin, folder) {
3723
+ const target = normaliseFolder(folder);
3724
+ return update(origin, (entry) => {
3725
+ if (entry.folders.includes(target)) return false;
3726
+ entry.folders = [...entry.folders, target];
3727
+ return true;
3728
+ });
3729
+ },
3730
+ link(origin, folder, projectId) {
3731
+ assertProjectId(projectId);
3732
+ const target = normaliseFolder(folder);
3733
+ return update(origin, (entry) => {
3734
+ if (entry.links[target] === projectId) return false;
3735
+ entry.links[target] = projectId;
3736
+ return true;
3737
+ });
3738
+ },
3739
+ async forget(origin) {
3740
+ const key = normaliseOrigin(origin);
3741
+ const data = readAccounts(path);
3742
+ if (!Object.hasOwn(data.accounts, key)) return null;
3743
+ const entry = data.accounts[key];
3744
+ try {
3745
+ await osBackend(entry.where)?.remove(accountSecretId(key));
3746
+ } catch {
3747
+ }
3748
+ delete data.accounts[key];
3749
+ writePrivateJson(path, data);
3750
+ return publicEntry2(key, entry);
3751
+ }
3752
+ };
3753
+ }
3754
+
3755
+ // src/connect/account-paths.ts
3756
+ function originOf(api) {
3757
+ normaliseOrigin(api);
3758
+ return new URL(api).origin;
3759
+ }
3760
+ function trustedRootFor(cwd) {
3761
+ return normaliseFolder(projectRoot(normaliseFolder(cwd)));
3762
+ }
3763
+
3764
+ // src/connect/open-browser.ts
3765
+ import { spawn as spawn2 } from "node:child_process";
3766
+ var launchDetached = (cmd, args) => new Promise((resolve8) => {
3767
+ try {
3768
+ const child = spawn2(cmd, args, {
3769
+ shell: false,
3770
+ stdio: "ignore",
3771
+ detached: true,
3772
+ windowsHide: true
3773
+ });
3774
+ child.once("error", () => resolve8(false));
3775
+ child.once("spawn", () => {
3776
+ child.unref();
3777
+ resolve8(true);
3778
+ });
3779
+ } catch {
3780
+ resolve8(false);
3781
+ }
3782
+ });
3783
+ function deviceUrl(api) {
3784
+ return new URL("/device", api).toString();
3785
+ }
3786
+ async function openBrowser(url, platform, launch = launchDetached) {
3787
+ let protocol;
3788
+ try {
3789
+ protocol = new URL(url).protocol;
3790
+ } catch {
3791
+ return false;
3792
+ }
3793
+ if (protocol !== "http:" && protocol !== "https:") return false;
3794
+ if (platform === "darwin") return launch("open", [url]);
3795
+ if (platform === "win32") return launch("rundll32", ["url.dll,FileProtocolHandler", url]);
3796
+ return launch("xdg-open", [url]);
3797
+ }
3798
+
3799
+ // src/connect/device-login.ts
3800
+ var DENIED_MESSAGE = "Sign-in was denied in the browser.";
3801
+ var EXPIRED_MESSAGE = "The code expired. Run npx designsource login again.";
3802
+ var UNEXPECTED = "Unexpected answer from the API. Run npx designsource login again.";
3803
+ var DEVICE_MAX_WAIT_MS = 6e5;
3804
+ var SLOW_DOWN_MS = 5e3;
3805
+ var DEFAULT_INTERVAL_MS = 5e3;
3806
+ var MIN_INTERVAL_MS = 1e3;
3807
+ var MAX_INTERVAL_MS = 6e4;
3808
+ var ACCOUNT_TOKEN2 = /^dsa_[A-Za-z0-9_-]{43}$/;
3809
+ var USER_CODE = /^[BCDFGHJKLMNPQRSTVWXZ23456789]{4}-[BCDFGHJKLMNPQRSTVWXZ23456789]{4}$/;
3810
+ var DEVICE_CODE = /^[A-Za-z0-9_-]{20,128}$/;
3811
+ var CLIENT_NAME_MAX = 60;
3812
+ var EMAIL_MAX = 254;
3813
+ function printable(text) {
3814
+ return text.replace(/[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u202a-\u202e\u2028\u2029\u2060-\u2069\ufeff]/g, "");
3815
+ }
3816
+ function clientName(hostname2) {
3817
+ const host = hostname2.replace(/[^A-Za-z0-9 '._-]/g, "-") || "this computer";
3818
+ return `designsource on ${host}`.slice(0, CLIENT_NAME_MAX).trimEnd();
3819
+ }
3820
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3821
+ var errorCode = (body) => isRecord3(body) && typeof body.error === "string" ? body.error : null;
3822
+ function seconds(value, fallback, min, max) {
3823
+ const ms = typeof value === "number" && Number.isFinite(value) ? value * 1e3 : fallback;
3824
+ return Math.min(max, Math.max(min, ms));
3825
+ }
3826
+ async function deviceLogin(opts) {
3827
+ const { api, fetchImpl, sleep, now, show, open } = opts;
3828
+ const started = now();
3829
+ const code2 = await requestJson({ api, path: "/api/device/code", method: "POST", body: { clientName: opts.clientName } }, fetchImpl);
3830
+ if (code2.status === 429) throw new CliError("Too many sign-in attempts from this network. Wait a while and run npx designsource login again.");
3831
+ if (code2.status !== 200) throw new CliError(`${api} answered ${code2.status}.`);
3832
+ const body = code2.body;
3833
+ if (!isRecord3(body) || typeof body.deviceCode !== "string" || !DEVICE_CODE.test(body.deviceCode) || typeof body.userCode !== "string" || !USER_CODE.test(body.userCode)) {
3834
+ throw new CliError(UNEXPECTED);
3835
+ }
3836
+ const deviceCode = body.deviceCode;
3837
+ let interval = seconds(body.interval, DEFAULT_INTERVAL_MS, MIN_INTERVAL_MS, MAX_INTERVAL_MS);
3838
+ const deadline = started + seconds(body.expiresIn, DEVICE_MAX_WAIT_MS, 0, DEVICE_MAX_WAIT_MS);
3839
+ const page = deviceUrl(api);
3840
+ show(`Open ${page} and enter ${body.userCode}`);
3841
+ await open(page);
3842
+ show("Waiting for you to approve it in the browser\u2026 (Ctrl+C to stop)");
3843
+ for (; ; ) {
3844
+ if (now() + interval > deadline) throw new CliError(EXPIRED_MESSAGE);
3845
+ await sleep(interval);
3846
+ const poll = await requestJson({ api, path: "/api/device/token", method: "POST", body: { deviceCode } }, fetchImpl);
3847
+ if (poll.status === 200) return accepted(poll.body);
3848
+ const error = poll.status === 400 ? errorCode(poll.body) : null;
3849
+ if (error === "authorization_pending") continue;
3850
+ if (error === "slow_down") {
3851
+ interval = Math.min(MAX_INTERVAL_MS, interval + SLOW_DOWN_MS);
3852
+ continue;
3853
+ }
3854
+ if (error === "access_denied") throw new CliError(DENIED_MESSAGE);
3855
+ if (error === "expired_token") throw new CliError(EXPIRED_MESSAGE);
3856
+ if (poll.status >= 500 || poll.status === 429) continue;
3857
+ throw new CliError(UNEXPECTED);
3858
+ }
3859
+ }
3860
+ function accepted(body) {
3861
+ if (!isRecord3(body) || typeof body.accessToken !== "string" || !ACCOUNT_TOKEN2.test(body.accessToken)) throw new CliError("Unexpected account token from the API.");
3862
+ const account = body.account;
3863
+ if (!isRecord3(account) || typeof account.email !== "string") throw new CliError(UNEXPECTED);
3864
+ const email = printable(account.email).slice(0, EMAIL_MAX);
3865
+ if (email === "") throw new CliError(UNEXPECTED);
3866
+ return { token: body.accessToken, email };
3867
+ }
3868
+
3869
+ // src/commands/login.ts
3870
+ function defaultLoginDeps(env) {
3871
+ const home = homedir3();
3872
+ const platform = process.platform;
3873
+ return {
3874
+ accounts: createAccountStore({ env, platform, exec: spawnExec, home }),
3875
+ accountPath: accountPath(env, platform, home),
3876
+ detect: () => detectApps({ env, platform, home, exists: existsSync11, onPath: (bin) => onPath(bin, env, platform) }),
3877
+ home,
3878
+ terminal: process.stdin.isTTY === true && process.stdout.isTTY === true,
3879
+ hostname: hostname(),
3880
+ platform
3881
+ };
3882
+ }
3883
+ var sleepFor = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
3884
+ var UNTRUSTED_LOGIN_SERVER = (api) => `designsource will not sign in to ${api} from a script: outside a terminal it signs in only to ${DEFAULT_API_ORIGIN} or a server on this computer. If you trust ${api}, run npx designsource login --api ${api} in a terminal yourself.`;
3885
+ var REVOKE_FAILED = "Could not reach the server to revoke this sign-in; revoke it on your profile page.";
3886
+ function loginApi(args, terminal) {
3887
+ const api = originOf(args.api);
3888
+ if (!args.apiGiven || terminal || sameApi(api, DEFAULT_API_ORIGIN) || isLoopback(api)) return api;
3889
+ throw new CliError(UNTRUSTED_LOGIN_SERVER(api));
3890
+ }
3891
+ var NOT_A_PROJECT = "Run npx designsource login inside a project folder (one with a .git folder or a package.json).";
3892
+ var isProjectFolder = (root) => existsSync11(join10(root, ".git")) || existsSync11(join10(root, "package.json"));
3893
+ function savedLine2(where, file) {
3894
+ if (where === "keychain") return "Saved the sign-in in the macOS keychain \u2713";
3895
+ if (where === "secret-service") return "Saved the sign-in in the system keyring \u2713";
3896
+ if (where === "dpapi") return "Saved the sign-in with Windows protection \u2713";
3897
+ return `Saved the sign-in in ${file} (readable only by you) \u2713`;
3898
+ }
3899
+ var labelOf = (id) => APPS.find((a) => a.id === id).label;
3900
+ var listOf = (words) => words.length <= 1 ? words.join("") : `${words.slice(0, -1).join(", ")} and ${words.at(-1)}`;
3901
+ var KEEPS_PROJECT_ENTRY = (id, file) => `${labelOf(id)}: keeps its project-token entry, so it will not use this sign-in. To use it there, remove --project from the designsource entry in ${file}.`;
3902
+ function closingLines2(apps, changed, usesAccount) {
3903
+ return [
3904
+ ...changed.length > 0 ? [`Restart ${listOf(changed.map(labelOf))} so ${changed.length === 1 ? "it loads" : "they load"} designsource.`] : [],
3905
+ ...apps.includes("claude") ? ["Claude Code asks once to allow the server."] : [],
3906
+ ...usesAccount ? ["Then ask your agent to create a design system for this app."] : [],
3907
+ "These files hold no token and are safe to commit."
3908
+ ];
3909
+ }
3910
+ var plansFor = (root, apps) => apps.map((id) => ({ id, plan: planAppFile(root, id, null) }));
3911
+ var changes = (plan) => plan.contents !== null && (plan.status === "create" || plan.status === "update");
3912
+ async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
3913
+ const { accounts, terminal } = deps;
3914
+ const say = (lines) => io.stdout(lines.map((l) => `${l}
3915
+ `).join(""));
3916
+ const root = trustedRootFor(io.cwd);
3917
+ const refusal = homeFolderRefusal(root, normaliseFolder(deps.home));
3918
+ if (refusal) throw new CliError(refusal);
3919
+ if (!isProjectFolder(root)) throw new CliError(NOT_A_PROJECT);
3920
+ const api = loginApi(args, terminal);
3921
+ let apps;
3922
+ if (args.apps) apps = args.apps;
3923
+ else {
3924
+ const detected = deps.detect();
3925
+ if (terminal && !args.yes) {
3926
+ apps = await (deps.prompts ?? { pickMany }).pickMany("Set up which apps?", APP_OPTIONS, detected);
3927
+ if (apps.length === 0) throw new CliError(NO_APPS_PICKED);
3928
+ } else {
3929
+ if (detected.length === 0) throw new CliError(NO_APPS_FOUND);
3930
+ apps = detected;
3931
+ }
3932
+ }
3933
+ plansFor(root, apps);
3934
+ say([`Signing in for ${root}`]);
3935
+ const head = [];
3936
+ let email = null;
3937
+ const saved = accounts.get(api);
3938
+ const savedToken2 = saved ? await accounts.token(api).catch(() => null) : null;
3939
+ if (terminal && saved && savedToken2) {
3940
+ const check = await requestJson({ api, path: "/api/agent/projects", method: "GET", token: savedToken2 }, io.fetchImpl);
3941
+ if (check.status === 200) {
3942
+ accounts.trust(api, root);
3943
+ email = printable(saved.email);
3944
+ head.push(`Already signed in on this computer; your agent may now use it from ${root}.`);
3945
+ } else if (check.status !== 401 && check.status !== 403) {
3946
+ throw new CliError(messageForResponse(check.status, check.body, api));
3947
+ }
3948
+ }
3949
+ if (email === null) {
3950
+ const now = deps.now ?? Date.now;
3951
+ const open = terminal ? deps.open ?? ((url) => openBrowser(url, deps.platform)) : async () => false;
3952
+ const signedIn = await deviceLogin({
3953
+ api,
3954
+ clientName: clientName(deps.hostname),
3955
+ fetchImpl: io.fetchImpl,
3956
+ sleep: deps.sleep ?? sleepFor,
3957
+ now,
3958
+ show: (line) => say([line]),
3959
+ open
3960
+ });
3961
+ const entry = await accounts.save({ origin: api, email: signedIn.email, token: signedIn.token, folder: root });
3962
+ email = signedIn.email;
3963
+ if (savedToken2 && savedToken2 !== signedIn.token) await revoke(api, savedToken2, io.fetchImpl);
3964
+ if (entry.backup) head.push(`Your old account file could not be read, so it was kept as ${entry.backup}.`);
3965
+ head.push(savedLine2(entry.where, deps.accountPath));
3966
+ }
3967
+ const plans = plansFor(root, apps);
3968
+ const files = plans.flatMap(({ plan }) => changes(plan) ? [{ path: plan.path, contents: plan.contents }] : []);
3969
+ try {
3970
+ if (files.length > 0) writeFiles(root, files, { force: true, created: false });
3971
+ } catch (e) {
3972
+ if (e instanceof CliError) throw new CliError(`${e.message} You are signed in; run npx designsource login again to write the settings.`, e.exitCode);
3973
+ throw e;
3974
+ }
3975
+ const changed = plans.filter(({ plan }) => changes(plan)).map(({ id }) => id);
3976
+ const usesAccount = plans.some(({ plan }) => changes(plan) || plan.status === "unchanged" && !plan.keepsProject);
3977
+ const kept = plans.flatMap(({ id, plan }) => plan.status === "unchanged" && plan.keepsProject ? [KEEPS_PROJECT_ENTRY(id, plan.path)] : []);
3978
+ say([
3979
+ `Signed in as ${email} on this computer.`,
3980
+ ...head,
3981
+ ...plans.flatMap(({ id, plan }) => appLines(id, plan)),
3982
+ ...kept,
3983
+ ...closingLines2(apps, changed, usesAccount)
3984
+ ]);
3985
+ }
3986
+ async function revoke(api, token, fetchImpl) {
3987
+ try {
3988
+ const res = await requestJson({ api, path: "/api/agent/token", method: "DELETE", token }, fetchImpl);
3989
+ return res.status === 200 || res.status === 204 || res.status === 401;
3990
+ } catch {
3991
+ return false;
3992
+ }
3993
+ }
3994
+ function logoutOrigin(args, accounts) {
3995
+ if (args.apiGiven) return accounts.get(originOf(args.api))?.origin ?? null;
3996
+ const fallback = accounts.get(DEFAULT_API_ORIGIN);
3997
+ if (fallback) return fallback.origin;
3998
+ const all = accounts.all();
3999
+ if (all.length === 1) return all[0].origin;
4000
+ if (all.length > 1) throw new CliError(`More than one designsource account is signed in on this computer (${all.map((a) => a.origin).join(", ")}); pass --api.`);
4001
+ return null;
4002
+ }
4003
+ async function runLogout(args, io, deps = defaultLoginDeps(process.env)) {
4004
+ const { accounts } = deps;
4005
+ const origin = logoutOrigin(args, accounts);
4006
+ if (origin === null) {
4007
+ io.stdout(`Not signed in to ${args.apiGiven ? originOf(args.api) : DEFAULT_API_ORIGIN} on this computer.
4008
+ `);
4009
+ return;
4010
+ }
4011
+ const token = await accounts.token(origin).catch(() => null);
4012
+ const revoked = token ? await revoke(origin, token, io.fetchImpl) : false;
4013
+ const removed = await accounts.forget(origin);
4014
+ if (!revoked) io.stderr(`${REVOKE_FAILED}
4015
+ `);
4016
+ io.stdout(`Signed out of designsource${removed ? ` (${printable(removed.email)})` : ""} on this computer.
4017
+ `);
4018
+ }
4019
+
3420
4020
  // src/mcp/server.ts
3421
- import { createInterface as createInterface2 } from "node:readline";
4021
+ import { homedir as homedir4 } from "node:os";
3422
4022
 
3423
4023
  // src/version.ts
3424
- var VERSION = true ? "0.6.0" : "0.0.0-dev";
4024
+ var VERSION = true ? "0.7.0" : "0.0.0-dev";
4025
+
4026
+ // src/mcp/account-session.ts
4027
+ var NOT_SIGNED_IN_FOR = (root) => `Not signed in on this computer for ${printable(root)}. Ask the user to run npx designsource login in a terminal in that folder, then restart this app.`;
4028
+ var SEVERAL_ACCOUNTS = "More than one designsource account is signed in on this computer; pass --api.";
4029
+ var NO_LINK = "No design system is linked to this folder yet. Call create_design_system or use_design_system.";
4030
+ var ACCOUNT_TOKEN3 = /^dsa_[A-Za-z0-9_-]{43}$/;
4031
+ var PROJECT_ID3 = /^[A-Za-z0-9_-]+$/;
4032
+ var refuse = (message) => ({ kind: "none", message });
4033
+ function chooseAccount(api, apiGiven, accounts, notSignedIn) {
4034
+ if (apiGiven) {
4035
+ let origin;
4036
+ try {
4037
+ origin = originOf(api);
4038
+ } catch {
4039
+ return refuse(notSignedIn);
4040
+ }
4041
+ return accounts.get(origin) ?? refuse(notSignedIn);
4042
+ }
4043
+ const all = accounts.all();
4044
+ if (all.length === 1) return all[0];
4045
+ const fallback = accounts.get(DEFAULT_API_ORIGIN);
4046
+ if (fallback) return fallback;
4047
+ return refuse(all.length > 1 ? SEVERAL_ACCOUNTS : notSignedIn);
4048
+ }
4049
+ async function resolveAccount(input) {
4050
+ const { api, apiGiven, cwd, home, accounts } = input;
4051
+ const folder = trustedRootFor(cwd);
4052
+ const notSignedIn = NOT_SIGNED_IN_FOR(folder);
4053
+ const chosen = chooseAccount(api, apiGiven, accounts, notSignedIn);
4054
+ if ("kind" in chosen) return chosen;
4055
+ if (homeFolderRefusal(folder, normaliseFolder(home)) !== null) return refuse(notSignedIn);
4056
+ if (!chosen.folders.some((f) => normaliseFolder(f) === folder)) return refuse(notSignedIn);
4057
+ const linked = Object.entries(chosen.links).find(([f]) => normaliseFolder(f) === folder)?.[1];
4058
+ const projectId = linked !== void 0 && PROJECT_ID3.test(linked) ? linked : null;
4059
+ let token;
4060
+ try {
4061
+ token = await accounts.token(chosen.origin);
4062
+ } catch {
4063
+ return refuse(notSignedIn);
4064
+ }
4065
+ if (token === null || !ACCOUNT_TOKEN3.test(token)) return refuse(notSignedIn);
4066
+ return { kind: "account", origin: chosen.origin, email: chosen.email, token, folder, projectId };
4067
+ }
3425
4068
 
3426
4069
  // src/mcp/jsonrpc.ts
4070
+ import { StringDecoder } from "node:string_decoder";
3427
4071
  var PARSE_ERROR = -32700;
3428
4072
  var INVALID_REQUEST = -32600;
3429
4073
  var METHOD_NOT_FOUND = -32601;
@@ -3465,6 +4109,21 @@ function parseLine(line) {
3465
4109
  if (params !== void 0) message.params = params;
3466
4110
  return { kind: "notification", message };
3467
4111
  }
4112
+ async function* readLines(input) {
4113
+ const decoder = new StringDecoder("utf8");
4114
+ let buffered = "";
4115
+ for await (const chunk of input) {
4116
+ buffered += typeof chunk === "string" ? chunk : decoder.write(chunk);
4117
+ let end;
4118
+ while ((end = buffered.indexOf("\n")) !== -1) {
4119
+ const line = buffered.slice(0, end);
4120
+ buffered = buffered.slice(end + 1);
4121
+ yield line.endsWith("\r") ? line.slice(0, -1) : line;
4122
+ }
4123
+ }
4124
+ buffered += decoder.end();
4125
+ if (buffered) yield buffered.endsWith("\r") ? buffered.slice(0, -1) : buffered;
4126
+ }
3468
4127
 
3469
4128
  // src/mcp/prompts.ts
3470
4129
  var INTEGRATE_PROMPT_NAME = "integrate-design-system";
@@ -3477,25 +4136,201 @@ function getPrompt(name) {
3477
4136
  return { description: "Integrate the design system into the current repository.", messages: [{ role: "user", content: { type: "text", text: INTEGRATE_TEXT } }] };
3478
4137
  }
3479
4138
 
4139
+ // src/mcp/results.ts
4140
+ var textResult = (text) => ({ content: [{ type: "text", text }] });
4141
+ var errorResult = (text) => ({ content: [{ type: "text", text }], isError: true });
4142
+
4143
+ // src/mcp/account-tools.ts
4144
+ var PROJECT_TOKEN_SESSION = "This app runs designsource with a project token, so creating or switching design systems is off here. To turn it on, remove --project (and any token) from the designsource entry in this app's MCP settings, then ask the user to run npx designsource login in a terminal in this folder and restart this app.";
4145
+ var PROJECTS_PATH = "/api/agent/projects";
4146
+ var PROJECT_ID4 = /^[A-Za-z0-9_-]{1,64}$/;
4147
+ var BAD_ID = '"id" must be a design system id from list_design_systems.';
4148
+ var UNKNOWN_ID = (email) => `No design system with that id in ${email}'s account. Call list_design_systems.`;
4149
+ var UNEXPECTED2 = (api) => `${api} sent an answer designsource does not understand. Update designsource.`;
4150
+ var RECIPE_LISTS = {
4151
+ rampRoles: ["neutral", "brand", "accent", "destructive", "success", "warning"],
4152
+ semantics: [
4153
+ "background",
4154
+ "foreground",
4155
+ "card",
4156
+ "card-foreground",
4157
+ "popover",
4158
+ "popover-foreground",
4159
+ "primary",
4160
+ "primary-foreground",
4161
+ "secondary",
4162
+ "secondary-foreground",
4163
+ "muted",
4164
+ "muted-foreground",
4165
+ "accent",
4166
+ "accent-foreground",
4167
+ "destructive",
4168
+ "destructive-foreground",
4169
+ "border",
4170
+ "input",
4171
+ "ring"
4172
+ ],
4173
+ shades: ["50", "100", "150", "200", "250", "300", "350", "400", "450", "500", "550", "600", "650", "700", "750", "800", "850", "900", "950"],
4174
+ radius: ["none", "xs", "sm", "md", "lg", "xl", "2xl", "3xl", "4xl", "full"],
4175
+ sansFonts: [
4176
+ "system",
4177
+ "neo-grotesque",
4178
+ "humanist",
4179
+ "geometric",
4180
+ "classical",
4181
+ "rounded",
4182
+ "industrial",
4183
+ "transitional-serif",
4184
+ "old-style-serif",
4185
+ "slab-serif",
4186
+ "antique",
4187
+ "didone",
4188
+ "handwritten"
4189
+ ],
4190
+ monoFonts: ["system-mono", "code", "typewriter"],
4191
+ fontGenerics: ["sans-serif", "serif", "monospace", "cursive"],
4192
+ shadowLevels: ["flat", "subtle", "crisp", "normal", "diffuse", "dramatic"],
4193
+ chromaMax: 0.37,
4194
+ radiusStrategies: ["concentric", "uniform", "custom"]
4195
+ };
4196
+ var quoted = (xs) => xs.map((x) => `"${x}"`).join("|");
4197
+ var L = RECIPE_LISTS;
4198
+ var RECIPE_DESCRIPTION = `The design system as a recipe (the server validates it and builds every token from it): {"projectName": string (1-40 chars), "ramps": {each of ${L.rampRoles.map((r) => `"${r}"`).join(", ")} (all 6): {"hue": 0-360, "chroma": 0-${L.chromaMax}}} (the server builds 19 shades per ramp; hue 0 red, 30 orange, 60 amber, 90 yellow, 145 green, 195 teal, 230 blue, 260 indigo, 300 violet, 330 magenta; chroma 0.01 grey, 0.05 muted, 0.12 balanced, 0.2 vivid; neutral at chroma 0.02 or less), "semantics": {each of ${L.semantics.map((s) => `"${s}"`).join(", ")} (all 19): {"light": Ref, "dark": Ref}}, "radius": ${quoted(L.radius)} (the control corner; cards follow one step rounder), "fonts": {"sans": ${quoted(L.sansFonts)} | WebFont, "mono": ${quoted(L.monoFonts)} | WebFont}, "shadowLevel": ${quoted(L.shadowLevels)}, "shadowColor"?: Ref} where Ref = "<ramp role>.<shade>" (shade ${L.shades.join("|")}, e.g. "brand.600") | "white" | "black", and WebFont = {"family": a Google Fonts family spelled exactly as Google lists it, "generic"?: ${quoted(L.fontGenerics)}}.`;
4199
+ var CREATE_DESCRIPTION = "Create a new design system in the signed-in designsource account from a recipe you write, and link this folder to it, so the other tools and add_ui_kit read it. Before writing the recipe, read this codebase: its existing colours (Tailwind config, CSS variables, the global stylesheet), its fonts and its logo, and match them. Pick one brand hue (the brand ramp, which primary points at), keep the neutral ramp near grey, keep destructive red, success green and warning amber, and use only Google Fonts family names or the catalog font keys. The recipe's shape is in the recipe property's description. The server repairs contrast without moving primary and reports what it changed and what still fails. Creates a project in the user's account, so your client will ask the user first. The answer names the account and a link where the user can tweak the result.";
4200
+ function accountOf(ctx) {
4201
+ if (ctx.account) return ctx.account;
4202
+ return errorResult(ctx.accountRefusal ?? PROJECT_TOKEN_SESSION);
4203
+ }
4204
+ var isResult = (v) => "content" in v;
4205
+ var serverError = (status, body, api) => {
4206
+ if (status === 401) return errorResult(ACCOUNT_TOKEN_MESSAGE);
4207
+ const error = typeof body === "object" && body !== null ? body.error : void 0;
4208
+ return errorResult(typeof error === "string" && printable(error).trim() ? printable(error).trim() : `${api} answered ${status}.`);
4209
+ };
4210
+ var isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4211
+ var isStrings2 = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
4212
+ async function listProjects(account, ctx) {
4213
+ const { status, body } = await requestJson({ api: account.api, path: PROJECTS_PATH, method: "GET", token: account.token }, ctx.fetchImpl);
4214
+ if (status !== 200) return serverError(status, body, account.api);
4215
+ const projects = isPlainObject(body) ? body.projects : void 0;
4216
+ if (!Array.isArray(projects) || !projects.every((p) => isPlainObject(p) && typeof p.id === "string" && typeof p.name === "string")) {
4217
+ return errorResult(UNEXPECTED2(account.api));
4218
+ }
4219
+ return projects.map((p) => ({ id: p.id, name: printable(p.name) }));
4220
+ }
4221
+ async function listDesignSystems(ctx) {
4222
+ const account = accountOf(ctx);
4223
+ if (isResult(account)) return account;
4224
+ const projects = await listProjects(account, ctx);
4225
+ if (!Array.isArray(projects)) return projects;
4226
+ const lines = projects.length ? projects.map((p) => `${p.name} (${printable(p.id)})${p.id === account.projectId ? " (linked to this folder)" : ""}`) : ["No design systems in this account yet. Call create_design_system."];
4227
+ return textResult([...lines, `Signed in as ${printable(account.email)}.`].join("\n"));
4228
+ }
4229
+ async function createDesignSystem(args, ctx) {
4230
+ const account = accountOf(ctx);
4231
+ if (isResult(account)) return account;
4232
+ const { name, recipe, mockup, radius_strategy: strategy } = args;
4233
+ if (typeof name !== "string" || !name.trim()) return errorResult(`"name" must be the design system's name.`);
4234
+ if (!isPlainObject(recipe)) return errorResult('"recipe" must be an object (see the tool description for its shape).');
4235
+ if (mockup !== void 0 && !isPlainObject(mockup)) return errorResult('"mockup" must be an object, or left out.');
4236
+ if (strategy !== void 0 && !L.radiusStrategies.includes(strategy)) {
4237
+ return errorResult(`"radius_strategy" must be one of: ${L.radiusStrategies.join(", ")}.`);
4238
+ }
4239
+ const body = { name, recipe };
4240
+ if (mockup !== void 0) body.mockupSpec = mockup;
4241
+ if (strategy !== void 0) body.radiusStrategy = strategy;
4242
+ const res = await requestJson({ api: account.api, path: PROJECTS_PATH, method: "POST", token: account.token, body }, ctx.fetchImpl);
4243
+ if (res.status !== 201) return serverError(res.status, res.body, account.api);
4244
+ const c = res.body;
4245
+ if (!isPlainObject(c) || typeof c.id !== "string" || !PROJECT_ID4.test(c.id) || typeof c.name !== "string" || typeof c.url !== "string" || typeof c.score !== "number" || !isStrings2(c.failing) || !isStrings2(c.changes)) {
4246
+ return errorResult(UNEXPECTED2(account.api));
4247
+ }
4248
+ const serverEmail = isPlainObject(c.account) && typeof c.account.email === "string" ? c.account.email : account.email;
4249
+ const email = printable(serverEmail);
4250
+ const created = `Created "${printable(c.name)}" in ${email}'s account. Score ${c.score}/100. Open it to tweak: ${printable(c.url)}.`;
4251
+ const details = [
4252
+ ...c.changes.length ? ["Changes made:", ...c.changes.map((l) => `- ${printable(l)}`)] : [],
4253
+ ...c.failing.length ? ["Still failing contrast:", ...c.failing.map((l) => `- ${printable(l)}`)] : []
4254
+ ];
4255
+ if (!account.link(c.id)) return errorResult([created, `This folder was not linked to it: ${NOT_SIGNED_IN_FOR(account.folder)}`, ...details].join("\n"));
4256
+ return textResult([created, ...details].join("\n"));
4257
+ }
4258
+ async function useDesignSystem(args, ctx) {
4259
+ const account = accountOf(ctx);
4260
+ if (isResult(account)) return account;
4261
+ const { id } = args;
4262
+ if (typeof id !== "string" || !PROJECT_ID4.test(id)) return errorResult(BAD_ID);
4263
+ const projects = await listProjects(account, ctx);
4264
+ if (!Array.isArray(projects)) return projects;
4265
+ const email = printable(account.email);
4266
+ const found = projects.find((p) => p.id === id);
4267
+ if (!found) return errorResult(UNKNOWN_ID(email));
4268
+ if (!account.link(id)) return errorResult(NOT_SIGNED_IN_FOR(account.folder));
4269
+ return textResult(`This folder now uses "${found.name}" from ${email}'s account.`);
4270
+ }
4271
+ var ACCOUNT_TOOLS = [
4272
+ {
4273
+ name: "list_design_systems",
4274
+ description: "The design systems in the signed-in designsource account: name and id of each, and which one this folder is linked to. Use before use_design_system, or to check what create_design_system would add to.",
4275
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
4276
+ annotations: { readOnlyHint: true },
4277
+ needsSnapshot: false,
4278
+ accountTool: true,
4279
+ run: (_s, _at, _args, ctx) => listDesignSystems(ctx)
4280
+ },
4281
+ {
4282
+ name: "create_design_system",
4283
+ description: CREATE_DESCRIPTION,
4284
+ inputSchema: {
4285
+ type: "object",
4286
+ properties: {
4287
+ name: { type: "string", description: "The design system's name, as the user will see it (up to 60 characters). Usually the app's name." },
4288
+ recipe: { type: "object", description: RECIPE_DESCRIPTION },
4289
+ mockup: { type: "object", description: "Optional: a page layout in the shape get_mockup_page returns for an existing design system. Leave it out when unsure." },
4290
+ radius_strategy: { type: "string", enum: [...L.radiusStrategies], description: "How corners nest: concentric (default, recommended), uniform or custom." }
4291
+ },
4292
+ required: ["name", "recipe"],
4293
+ additionalProperties: false
4294
+ },
4295
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
4296
+ needsSnapshot: false,
4297
+ accountTool: true,
4298
+ run: (_s, _at, args, ctx) => createDesignSystem(args, ctx)
4299
+ },
4300
+ {
4301
+ name: "use_design_system",
4302
+ description: "Link this folder to an existing design system in the signed-in account (an id from list_design_systems), so the other tools and add_ui_kit read it. Changes no design system.",
4303
+ inputSchema: {
4304
+ type: "object",
4305
+ properties: { id: { type: "string", description: "A design system id from list_design_systems." } },
4306
+ required: ["id"],
4307
+ additionalProperties: false
4308
+ },
4309
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
4310
+ needsSnapshot: false,
4311
+ accountTool: true,
4312
+ run: (_s, _at, args, ctx) => useDesignSystem(args, ctx)
4313
+ }
4314
+ ];
4315
+
3480
4316
  // src/mcp/project-folder.ts
3481
- import { isAbsolute as isAbsolute4, relative as relative4, resolve as resolve5, sep as sep4 } from "node:path";
4317
+ import { isAbsolute as isAbsolute4, relative as relative4, resolve as resolve7, sep as sep5 } from "node:path";
3482
4318
  var NOT_SURE_WHICH_FOLDER = "Not sure which project folder to change: run npx designsource connect in it first.";
3483
4319
  function isWithin2(folder, root) {
3484
4320
  const rel = relative4(root, folder);
3485
- return rel === "" || rel !== ".." && !rel.startsWith(`..${sep4}`) && !isAbsolute4(rel);
4321
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep5}`) && !isAbsolute4(rel);
3486
4322
  }
3487
4323
  function resolveProjectFolder(cwd, entry) {
3488
4324
  if (!entry) return cwd;
3489
- const here = resolve5(cwd);
3490
- const holding = entry.folders.map((f) => resolve5(f)).filter((f) => isWithin2(here, f)).sort((a, b) => b.length - a.length);
4325
+ const here = resolve7(cwd);
4326
+ const holding = entry.folders.map((f) => resolve7(f)).filter((f) => isWithin2(here, f)).sort((a, b) => b.length - a.length);
3491
4327
  if (holding[0]) return holding[0];
3492
- return entry.folders.length === 1 ? resolve5(entry.folders[0]) : null;
4328
+ return entry.folders.length === 1 ? resolve7(entry.folders[0]) : null;
3493
4329
  }
3494
4330
 
3495
4331
  // src/mcp/tools.ts
4332
+ var accountProjectPath = (projectId, kind) => `/api/agent/projects/${encodeURIComponent(projectId)}/${kind}`;
3496
4333
  var READ_ONLY = { readOnlyHint: true };
3497
- var textResult = (text) => ({ content: [{ type: "text", text }] });
3498
- var errorResult = (text) => ({ content: [{ type: "text", text }], isError: true });
3499
4334
  var TIERS = ["design", "semantic", "component"];
3500
4335
  var CATEGORIES = ["color", "spacing", "radius", "typography", "shadow", "zIndex", "border"];
3501
4336
  var NO_INPUT = { type: "object", properties: {}, additionalProperties: false };
@@ -3529,9 +4364,16 @@ async function addUiKit(args, ctx) {
3529
4364
  }
3530
4365
  if (replace !== void 0 && typeof replace !== "boolean") return errorResult('"replace_existing" must be true or false.');
3531
4366
  if (noBlocks !== void 0 && typeof noBlocks !== "boolean") return errorResult('"no_blocks" must be true or false.');
3532
- if (ctx.token === null) return errorResult(ctx.missingToken ?? MCP_TOKEN_REQUIRED);
3533
- const root = resolveProjectFolder(ctx.cwd, ctx.projectFolders === null ? null : { folders: ctx.projectFolders });
3534
- if (root === null) return errorResult(NOT_SURE_WHICH_FOLDER);
4367
+ let target;
4368
+ if (ctx.token !== null) {
4369
+ const root = resolveProjectFolder(ctx.cwd, ctx.projectFolders === null ? null : { folders: ctx.projectFolders });
4370
+ if (root === null) return errorResult(NOT_SURE_WHICH_FOLDER);
4371
+ target = { root, token: ctx.token, api: ctx.api };
4372
+ } else if (ctx.account) {
4373
+ if (ctx.account.projectId === null) return errorResult(NO_LINK);
4374
+ const { folder, token, api, projectId } = ctx.account;
4375
+ target = { root: folder, token, api, kitPath: accountProjectPath(projectId, "kit"), messages: accountMessageForResponse };
4376
+ } else return errorResult(ctx.missingToken ?? MCP_TOKEN_REQUIRED);
3535
4377
  const questions = {
3536
4378
  pickComponents: async (all) => all,
3537
4379
  confirmReplace: async (paths) => {
@@ -3544,7 +4386,7 @@ async function addUiKit(args, ctx) {
3544
4386
  const exec = (cmd, cmdArgs, opts) => ctx.exec(cmd, cmdArgs, { ...opts, timeoutMs: MCP_EXEC_TIMEOUT_MS });
3545
4387
  try {
3546
4388
  const result = await runAdd(
3547
- { root, token: ctx.token, api: ctx.api, components: components ?? [], skipInstall: false, blocks: noBlocks !== true },
4389
+ { ...target, components: components ?? [], skipInstall: false, blocks: noBlocks !== true },
3548
4390
  { fetchImpl: ctx.fetchImpl, exec, questions, progress: (line) => progress.push(line) }
3549
4391
  );
3550
4392
  const written = result.added.filter((n) => n !== "preview-portal");
@@ -3696,7 +4538,8 @@ ${files.join("\n\n")}`);
3696
4538
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
3697
4539
  needsSnapshot: false,
3698
4540
  run: (_snapshot, _at, args, ctx) => addUiKit(args, ctx)
3699
- }
4541
+ },
4542
+ ...ACCOUNT_TOOLS
3700
4543
  ];
3701
4544
  var TOOL_NAMES = TOOLS.map((t) => t.name);
3702
4545
  function toolList() {
@@ -3741,7 +4584,7 @@ async function request(msg, deps) {
3741
4584
  deps.warn(`designsource mcp: finding the project token failed: ${message}`);
3742
4585
  return respond(id, errorResult(`Could not find the project token: ${message}`));
3743
4586
  }
3744
- if (context.token === null) return respond(id, errorResult(context.missingToken ?? MCP_TOKEN_REQUIRED));
4587
+ if (context.token === null && context.account === null && tool.accountTool !== true) return respond(id, errorResult(context.missingToken ?? MCP_TOKEN_REQUIRED));
3745
4588
  let cached = { snapshot: NO_SNAPSHOT, fetchedAt: 0 };
3746
4589
  if (tool.needsSnapshot !== false) {
3747
4590
  try {
@@ -3795,77 +4638,158 @@ function validateSnapshot(json) {
3795
4638
  if (blocks.header !== void 0 && typeof blocks.header !== "string") return { ...json, blocks: { ...blocks, header: void 0 } };
3796
4639
  return json;
3797
4640
  }
3798
- var FETCH_TIMEOUT_MS = 3e4;
3799
4641
  async function fetchSnapshot(opts, fetchImpl = fetch) {
3800
- const url = new URL("/api/snapshot", `${opts.api}/`);
3801
- let res;
3802
- try {
3803
- res = await fetchImpl(url.toString(), {
3804
- headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" },
3805
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
3806
- });
3807
- } catch {
3808
- throw new CliError(UNREACHABLE(opts.api));
3809
- }
3810
- const body = await res.json().catch(() => null);
3811
- if (!res.ok) throw new CliError(messageForResponse(res.status, body, opts.api));
3812
- return validateSnapshot(body);
4642
+ const { api, token, path = "/api/snapshot", messages } = opts;
4643
+ return validateSnapshot(await getJson({ api, token, path, ...messages ? { messages } : {} }, fetchImpl));
3813
4644
  }
4645
+ var STALE_RETRY_MS = 15e3;
4646
+ var servesStale = (e) => !(e instanceof ApiError) || e.status === null || e.status >= 500;
3814
4647
  function createSnapshotCache(fetcher, opts = {}) {
3815
4648
  const ttl = opts.ttlMs ?? 6e4;
3816
4649
  const now = opts.now ?? Date.now;
4650
+ const retry = opts.retryMs ?? STALE_RETRY_MS;
3817
4651
  let cached = null;
3818
4652
  let inflight = null;
4653
+ let retryAt = 0;
4654
+ let generation = 0;
3819
4655
  return {
3820
4656
  get() {
3821
- if (cached && now() - cached.fetchedAt < ttl) return Promise.resolve(cached);
4657
+ if (cached && (now() - cached.fetchedAt < ttl || now() < retryAt)) return Promise.resolve(cached);
3822
4658
  if (inflight) return inflight;
3823
- inflight = fetcher().then((snapshot) => {
3824
- cached = { snapshot, fetchedAt: now() };
4659
+ const mine = generation;
4660
+ const current = () => mine === generation;
4661
+ const pending = fetcher().then((snapshot) => {
4662
+ const fresh = { snapshot, fetchedAt: now() };
4663
+ if (!current()) return fresh;
4664
+ cached = fresh;
4665
+ retryAt = 0;
3825
4666
  return cached;
3826
4667
  }).catch((e) => {
3827
- if (!cached) throw e;
4668
+ if (!current() || !cached || !servesStale(e)) {
4669
+ if (current()) cached = null;
4670
+ throw e;
4671
+ }
4672
+ retryAt = now() + retry;
3828
4673
  opts.warn?.(`Could not refresh the design system; serving the snapshot from ${new Date(cached.fetchedAt).toISOString()}: ${e instanceof Error ? e.message : String(e)}`);
3829
4674
  return cached;
3830
4675
  }).finally(() => {
3831
- inflight = null;
4676
+ if (inflight === pending) inflight = null;
3832
4677
  });
4678
+ inflight = pending;
3833
4679
  return inflight;
4680
+ },
4681
+ clear() {
4682
+ generation++;
4683
+ cached = null;
4684
+ inflight = null;
4685
+ retryAt = 0;
3834
4686
  }
3835
4687
  };
3836
4688
  }
3837
4689
 
3838
4690
  // src/mcp/server.ts
4691
+ function toolAccountFor(session, accounts, onLink, onGone = () => {
4692
+ }) {
4693
+ const account = {
4694
+ api: session.origin,
4695
+ token: session.token,
4696
+ email: session.email,
4697
+ folder: session.folder,
4698
+ projectId: session.projectId,
4699
+ link(projectId) {
4700
+ if (accounts.link(session.origin, session.folder, projectId) === null) {
4701
+ onGone();
4702
+ return false;
4703
+ }
4704
+ account.projectId = projectId;
4705
+ onLink();
4706
+ return true;
4707
+ }
4708
+ };
4709
+ return account;
4710
+ }
3839
4711
  async function runMcp(args, io, streams = { input: process.stdin, output: process.stdout }, deps = {}) {
3840
4712
  const cwd = deps.cwd ?? process.cwd();
3841
4713
  const store = deps.store ?? defaultStore();
3842
4714
  const warn = (line) => io.stderr(`${line}
3843
4715
  `);
4716
+ const projectPath = Boolean(args.project || args.token);
3844
4717
  let found = null;
3845
4718
  const fromStore = !args.token;
3846
- const session = async () => {
3847
- if (!found && (args.token || args.project)) found = await resolveToken({ given: args.token, cwd, projectId: args.project, store, interactive: false, prompt: false });
3848
- else if (found && found.entry === null && args.project) found = { ...found, entry: store.entry(args.project) };
3849
- if (found) return { token: found.token, projectFolders: args.project ? found.entry?.folders ?? [] : null, api: apiFor(args, found.entry), cwd, fetchImpl: io.fetchImpl, exec: spawnExec };
4719
+ const projectSession = async () => {
4720
+ if (!found) found = await resolveToken({ given: args.token, cwd, projectId: args.project, store, interactive: false, prompt: false });
4721
+ else if (found.entry === null && args.project) found = { ...found, entry: store.entry(args.project) };
4722
+ if (found) {
4723
+ const api = fromStore ? apiFor(args, found.entry) : givenTokenApi(args, found.entry);
4724
+ return { token: found.token, projectFolders: args.project ? found.entry?.folders ?? [] : null, api, cwd, account: null, fetchImpl: io.fetchImpl, exec: spawnExec };
4725
+ }
3850
4726
  const missingToken = args.project ? NO_TOKEN_FOR_PROJECT(store.entry(args.project)?.name ?? args.project) : MCP_TOKEN_REQUIRED;
3851
- return { token: null, missingToken, projectFolders: args.project ? [] : null, api: args.api, cwd, fetchImpl: io.fetchImpl, exec: spawnExec };
4727
+ return { token: null, missingToken, projectFolders: args.project ? [] : null, api: args.api, cwd, account: null, fetchImpl: io.fetchImpl, exec: spawnExec };
3852
4728
  };
4729
+ let accounts = null;
4730
+ let account = null;
4731
+ const accountSession = async () => {
4732
+ if (!account) {
4733
+ accounts ??= (deps.accounts ?? (() => createAccountStore({ env: process.env, platform: process.platform, exec: spawnExec, home: homedir4() })))();
4734
+ const resolved = await resolveAccount({ api: args.api, apiGiven: args.apiGiven === true, cwd, home: deps.home ?? homedir4(), accounts });
4735
+ if (resolved.kind === "none") {
4736
+ return {
4737
+ token: null,
4738
+ missingToken: `${MCP_TOKEN_REQUIRED}
4739
+
4740
+ ${resolved.message}`,
4741
+ accountRefusal: resolved.message,
4742
+ projectFolders: null,
4743
+ api: args.api,
4744
+ cwd,
4745
+ account: null,
4746
+ fetchImpl: io.fetchImpl,
4747
+ exec: spawnExec
4748
+ };
4749
+ }
4750
+ const made = toolAccountFor(resolved, accounts, () => cache.clear(), () => {
4751
+ if (account === made) account = null;
4752
+ cache.clear();
4753
+ });
4754
+ account = made;
4755
+ }
4756
+ const current = account;
4757
+ const base = io.fetchImpl ?? fetch;
4758
+ const fetchImpl = (async (input, init) => {
4759
+ const res = await base(input, init);
4760
+ if (res.status === 401 && account === current) {
4761
+ account = null;
4762
+ cache.clear();
4763
+ }
4764
+ return res;
4765
+ });
4766
+ return { token: null, projectFolders: null, api: current.api, cwd, account: current, fetchImpl, exec: spawnExec };
4767
+ };
4768
+ const session = () => projectPath ? projectSession() : accountSession();
3853
4769
  const cache = createSnapshotCache(async () => {
3854
- const { token, missingToken, api } = await session();
3855
- if (token === null) throw new CliError(missingToken);
3856
- try {
3857
- return await fetchSnapshot({ api, token }, io.fetchImpl);
3858
- } catch (e) {
3859
- if (fromStore && e instanceof CliError && e.message === TOKEN_MESSAGE) found = null;
3860
- throw e;
4770
+ const ctx = await session();
4771
+ if (ctx.token !== null) {
4772
+ try {
4773
+ return await fetchSnapshot({ api: ctx.api, token: ctx.token }, ctx.fetchImpl);
4774
+ } catch (e) {
4775
+ if (fromStore && e instanceof CliError && e.message === TOKEN_MESSAGE) found = null;
4776
+ throw e;
4777
+ }
4778
+ }
4779
+ if (ctx.account) {
4780
+ const { projectId, api, token } = ctx.account;
4781
+ if (projectId === null) throw new CliError(NO_LINK);
4782
+ return fetchSnapshot({ api, token, path: accountProjectPath(projectId, "snapshot"), messages: accountMessageForResponse }, ctx.fetchImpl);
3861
4783
  }
4784
+ throw new CliError(ctx.missingToken ?? MCP_TOKEN_REQUIRED);
3862
4785
  }, { warn });
3863
4786
  const protocol = { version: VERSION, snapshot: () => cache.get(), warn, context: session };
3864
- const lines = createInterface2({ input: streams.input, crlfDelay: Infinity });
4787
+ let closed2 = false;
3865
4788
  streams.output.on("error", () => {
3866
- lines.close();
4789
+ closed2 = true;
3867
4790
  });
3868
- for await (const raw of lines) {
4791
+ for await (const raw of readLines(streams.input)) {
4792
+ if (closed2) break;
3869
4793
  const line = raw.trim();
3870
4794
  if (!line) continue;
3871
4795
  const response = await handle(parseLine(line), protocol);
@@ -3877,6 +4801,7 @@ async function runMcp(args, io, streams = { input: process.stdin, output: proces
3877
4801
  var MENU = [
3878
4802
  { value: "add", label: "Add the UI kit to a React app", hint: "your components and theme, set up for you" },
3879
4803
  { value: "connect", label: "Connect your coding apps", hint: "Claude Code, Cursor, VS Code and more" },
4804
+ { value: "login", label: "Sign in for coding agents", hint: "lets your agent create design systems" },
3880
4805
  { value: "integrate", label: "Add to an existing project", hint: "writes design-system/ \u2014 tokens, prompt, reference kit" },
3881
4806
  { value: "create", label: "Create a new project", hint: "a Next.js app with every component and your mockup page" }
3882
4807
  ];
@@ -3916,6 +4841,8 @@ ${USAGE}`);
3916
4841
  else if (command.kind === "connect") await runConnect(command.args, io, defaultConnectDeps(env));
3917
4842
  else if (command.kind === "create") await runCreate(command.args, env, io);
3918
4843
  else if (command.kind === "integrate") await runIntegrate(command.args, env, io);
4844
+ else if (command.kind === "login") await runLogin(command.args, io, defaultLoginDeps(env));
4845
+ else if (command.kind === "logout") await runLogout(command.args, io, defaultLoginDeps(env));
3919
4846
  return 0;
3920
4847
  } catch (e) {
3921
4848
  if (e instanceof CliError) {