designsource 0.11.0 → 0.13.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 +1 -0
  2. package/dist/index.js +610 -307
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -21,7 +21,7 @@ var CliError = class extends Error {
21
21
  };
22
22
  var CANCELLED = "Cancelled.";
23
23
  var TOKEN_MESSAGE = "Project token not recognised. In the workbench open Project settings and copy the project token.";
24
- var MCP_TOKEN_REQUIRED = "A project token is required: pass --token or set DS_SYNC_TOKEN (workbench \u2192 Project settings).";
24
+ var MCP_TOKEN_REQUIRED = "designsource has no project token or sign-in here. Ask the user to run npx designsource login in a terminal in the project folder, then restart this app. The server runs on this computer over stdio; there is no web address to connect to instead.";
25
25
  var UNREACHABLE = (api) => `Could not reach ${api}.`;
26
26
  var UPDATE_MESSAGE = "This design system needs a newer designsource CLI. Update it (for example `npx designsource@latest`) and run again.";
27
27
  var PLAN_MESSAGE = "This project's account is on the free plan. Exports need Pro: https://designsource.app/pricing";
@@ -119,9 +119,9 @@ function resolveAlias(alias, tsconfig) {
119
119
  best = { prefixLength: prefix.length, resolved: star === -1 ? target : target.replace("*", () => rest) };
120
120
  }
121
121
  if (!best) throw noAlias(alias);
122
- const relative5 = posix.normalize(posix.join(tsconfig.baseUrl, best.resolved));
123
- if (relative5 === ".." || relative5.startsWith("../") || posix.isAbsolute(relative5)) throw outside(alias);
124
- return relative5 === "." ? "" : relative5;
122
+ const relative7 = posix.normalize(posix.join(tsconfig.baseUrl, best.resolved));
123
+ if (relative7 === ".." || relative7.startsWith("../") || posix.isAbsolute(relative7)) throw outside(alias);
124
+ return relative7 === "." ? "" : relative7;
125
125
  }
126
126
  function resolveTargets(root, shadcn) {
127
127
  const { aliases, tailwind } = shadcn ?? {};
@@ -1370,14 +1370,14 @@ function quoteArg(arg) {
1370
1370
  function childEnv(env) {
1371
1371
  return Object.fromEntries(Object.entries(env).filter(([name]) => name.toUpperCase() !== "DS_SYNC_TOKEN"));
1372
1372
  }
1373
- var spawnExec = (cmd, args, { cwd, timeoutMs, input, stdoutOnly }) => new Promise((resolve8) => {
1373
+ var spawnExec = (cmd, args, { cwd, timeoutMs, input, stdoutOnly }) => new Promise((resolve10) => {
1374
1374
  let output = "";
1375
1375
  let child;
1376
1376
  try {
1377
1377
  const shell = process.platform === "win32";
1378
1378
  child = spawn(cmd, shell ? args.map(quoteArg) : args, { cwd, env: childEnv(process.env), stdio: [input === void 0 ? "ignore" : "pipe", "pipe", "pipe"], shell });
1379
1379
  } catch (e) {
1380
- resolve8({ code: 127, output: e instanceof Error ? e.message : String(e) });
1380
+ resolve10({ code: 127, output: e instanceof Error ? e.message : String(e) });
1381
1381
  return;
1382
1382
  }
1383
1383
  let timedOut = false;
@@ -1387,7 +1387,7 @@ var spawnExec = (cmd, args, { cwd, timeoutMs, input, stdoutOnly }) => new Promis
1387
1387
  }, timeoutMs);
1388
1388
  const done = (result) => {
1389
1389
  if (timer) clearTimeout(timer);
1390
- resolve8(timedOut ? { code: result.code === 0 ? 124 : result.code, output: `${result.output.trimEnd()}
1390
+ resolve10(timedOut ? { code: result.code === 0 ? 124 : result.code, output: `${result.output.trimEnd()}
1391
1391
  timed out after ${timeoutMs / 1e3}s` } : result);
1392
1392
  };
1393
1393
  child.stdout?.on("data", (chunk) => {
@@ -1537,6 +1537,10 @@ function assembleAppShell(input) {
1537
1537
  if (typeof input.name !== "string") throw new Error("Invalid app name");
1538
1538
  if (input.hrefFor !== "app" && input.hrefFor !== "root") throw new Error("Invalid hrefFor");
1539
1539
  const prefix = input.hrefFor === "app" ? "/app/" : "/";
1540
+ const screenLinks = input.screenLinks === true;
1541
+ const screenHrefs = Object.fromEntries(
1542
+ input.screens.map((s) => [s.slug, !isPageKind(s.kind) ? `${prefix}${s.slug}` : s.kind === "home" ? "/" : `/${s.slug}`])
1543
+ );
1540
1544
  const links = input.screens.filter(isAppScreen).map((s) => ({ href: `${prefix}${s.slug}`, title: s.title, kind: s.kind }));
1541
1545
  const icons = [...new Set(SCREEN_KINDS.map((k) => SCREEN_KIND_ICON_NAMES[k]))].sort();
1542
1546
  const kindIcons = SCREEN_KINDS.map((k) => ` ${k}: ${SCREEN_KIND_ICON_NAMES[k]},`);
@@ -1558,6 +1562,7 @@ function assembleAppShell(input) {
1558
1562
  " SidebarProvider,",
1559
1563
  " SidebarTrigger,",
1560
1564
  "} from '@/components/ui/sidebar'",
1565
+ ...screenLinks ? ["import { ScreenLinksProvider, type ScreenLinks } from '@/components/screens/parts/screen-links'"] : [],
1561
1566
  "",
1562
1567
  `type ScreenKind = ${SCREEN_KINDS.map((k) => `'${k}'`).join(" | ")}`,
1563
1568
  "type ShellLink = { href: string; title: string; kind: ScreenKind }",
@@ -1566,6 +1571,7 @@ function assembleAppShell(input) {
1566
1571
  "",
1567
1572
  `const SCREENS: ShellLink[] = ${jsonLiteral(links, 2)}`,
1568
1573
  "",
1574
+ ...screenLinks ? [`const SCREEN_LINKS: ScreenLinks = ${jsonLiteral({ strict: true, hrefs: screenHrefs }, 2)}`, ""] : [],
1569
1575
  "const KIND_ICONS: Record<ScreenKind, IconComponent> = {",
1570
1576
  ...kindIcons,
1571
1577
  "}",
@@ -1618,7 +1624,13 @@ function assembleAppShell(input) {
1618
1624
  ' <header className="flex h-12 shrink-0 items-center gap-2 border-b px-4 @[40rem]/stage:px-6">',
1619
1625
  ' <SidebarTrigger className="-ml-1" />',
1620
1626
  " </header>",
1621
- ' <div className="flex flex-1 flex-col">{children}</div>',
1627
+ ...screenLinks ? [
1628
+ ' <div className="flex flex-1 flex-col">',
1629
+ " <ScreenLinksProvider value={SCREEN_LINKS}>",
1630
+ " {children}",
1631
+ " </ScreenLinksProvider>",
1632
+ " </div>"
1633
+ ] : [' <div className="flex flex-1 flex-col">{children}</div>'],
1622
1634
  " </SidebarInset>",
1623
1635
  " </SidebarProvider>",
1624
1636
  " </div>",
@@ -1631,6 +1643,7 @@ function assembleAppShell(input) {
1631
1643
  }
1632
1644
  var DEFAULT_SCREENS_IMPORT = "@/components/screens";
1633
1645
  var SCREENS_IMPORT = /^[A-Za-z0-9@~#_.-]+(?:\/[A-Za-z0-9@~#_.-]+)*$/;
1646
+ var HREF_BASE = /^(?:\/|#\/)(?:[A-Za-z0-9_-]+\/)*$/;
1634
1647
  var HEAD = [
1635
1648
  `export type SectionScreenKind = ${[...SCREEN_KINDS, ...PAGE_KINDS].map((k) => `'${k}'`).join(" | ")}`,
1636
1649
  "export type SectionScreenEntry = { slug: string; title: string; kind: SectionScreenKind }"
@@ -1642,6 +1655,8 @@ function assembleScreenRegistry(input) {
1642
1655
  if (typeof input.name !== "string") throw new Error("Invalid site name");
1643
1656
  if (!Number.isInteger(input.year)) throw new Error("Invalid year");
1644
1657
  if (input.action !== void 0 && typeof input.action !== "string") throw new Error("Invalid action label");
1658
+ const base = input.screenHrefBase;
1659
+ if (base !== void 0 && (typeof base !== "string" || !HREF_BASE.test(base))) throw new Error("Invalid screenHrefBase");
1645
1660
  const entries = input.screens.map((s) => ({ slug: s.slug, title: s.title, kind: s.kind }));
1646
1661
  const pages = entries.flatMap((s) => isPageKind(s.kind) ? [{ slug: s.slug, title: s.title, kind: s.kind }] : []);
1647
1662
  const site = siteFrameProps({ name: input.name, pages, year: input.year, fallbackActionLabel: input.action });
@@ -1662,9 +1677,16 @@ function assembleScreenRegistry(input) {
1662
1677
  const views = entries.map(
1663
1678
  (s) => ` ${jsonLiteral(s.slug)}: lazy(() => import(${jsonLiteral(`${screensImport}/${s.slug}`)}).then((m) => ({ default: m.${screenComponentName(s.slug)} }))),`
1664
1679
  );
1680
+ const linksImport = base === void 0 ? [] : [`import { ScreenLinksProvider } from '${screensImport}/parts/screen-links'`];
1681
+ const linksConst = base === void 0 ? [] : [
1682
+ `const SCREEN_LINKS = ${jsonLiteral({ strict: true, hrefs: Object.fromEntries(entries.map((s) => [s.slug, `${base}${s.slug}`])) }, 2)}`,
1683
+ ""
1684
+ ];
1685
+ const wrap = (indent, inner) => base === void 0 ? inner : [`${indent}<ScreenLinksProvider value={SCREEN_LINKS}>`, ...inner.map((l) => ` ${l}`), `${indent}</ScreenLinksProvider>`];
1665
1686
  if (pages.length === 0) {
1666
1687
  return [
1667
1688
  "import { lazy, Suspense, type ComponentType } from 'react'",
1689
+ ...linksImport,
1668
1690
  "",
1669
1691
  ...HEAD,
1670
1692
  "",
@@ -1674,12 +1696,13 @@ function assembleScreenRegistry(input) {
1674
1696
  ...views,
1675
1697
  "}",
1676
1698
  "",
1699
+ ...linksConst,
1677
1700
  "export function SectionScreen({ slug }: { slug: string }) {",
1678
1701
  " const View = Object.prototype.hasOwnProperty.call(VIEWS, slug) ? VIEWS[slug] : undefined",
1679
1702
  " if (!View) return null",
1680
1703
  " return (",
1681
1704
  " <Suspense fallback={null}>",
1682
- " <View />",
1705
+ ...wrap(" ", [" <View />"]),
1683
1706
  " </Suspense>",
1684
1707
  " )",
1685
1708
  "}",
@@ -1692,6 +1715,7 @@ function assembleScreenRegistry(input) {
1692
1715
  "import { lazy, Suspense, type ComponentProps, type ComponentType } from 'react'",
1693
1716
  `import { SiteFrame, SiteHeader, SiteFooter } from '${screensImport}/parts/site-frame'`,
1694
1717
  `import { SiteLinksProvider } from '${screensImport}/parts/site-links'`,
1718
+ ...linksImport,
1695
1719
  "",
1696
1720
  ...HEAD,
1697
1721
  "",
@@ -1712,22 +1736,25 @@ function assembleScreenRegistry(input) {
1712
1736
  "",
1713
1737
  `const SITE: SiteProps = ${jsonLiteral(site, 2)}`,
1714
1738
  "",
1739
+ ...linksConst,
1715
1740
  "export function SectionScreen({ slug }: { slug: string }) {",
1716
1741
  " const View = Object.prototype.hasOwnProperty.call(VIEWS, slug) ? VIEWS[slug] : undefined",
1717
1742
  " if (!View) return null",
1718
1743
  " return (",
1719
1744
  " <Suspense fallback={null}>",
1720
- " {PAGES.has(slug) ? (",
1721
- " <SiteLinksProvider value={{ hrefs: SITE.hrefs, inert: true }}>",
1722
- " <SiteFrame>",
1723
- " <SiteHeader {...SITE.header} />",
1724
- " <View />",
1725
- " <SiteFooter {...SITE.footer} />",
1726
- " </SiteFrame>",
1727
- " </SiteLinksProvider>",
1728
- " ) : (",
1729
- " <View />",
1730
- " )}",
1745
+ ...wrap(" ", [
1746
+ " {PAGES.has(slug) ? (",
1747
+ " <SiteLinksProvider value={{ hrefs: SITE.hrefs, inert: true }}>",
1748
+ " <SiteFrame>",
1749
+ " <SiteHeader {...SITE.header} />",
1750
+ " <View />",
1751
+ " <SiteFooter {...SITE.footer} />",
1752
+ " </SiteFrame>",
1753
+ " </SiteLinksProvider>",
1754
+ " ) : (",
1755
+ " <View />",
1756
+ " )}"
1757
+ ]),
1731
1758
  " </Suspense>",
1732
1759
  " )",
1733
1760
  "}",
@@ -1769,18 +1796,37 @@ function assembleSiteShell(input) {
1769
1796
  if (typeof input.name !== "string") throw new Error("Invalid site name");
1770
1797
  if (!Number.isInteger(input.year)) throw new Error("Invalid year");
1771
1798
  if (input.fallbackActionLabel !== void 0 && typeof input.fallbackActionLabel !== "string") throw new Error("Invalid action label");
1799
+ const appBase = input.appBase;
1800
+ if (appBase !== void 0 && appBase !== "/app/" && appBase !== "/") throw new Error("Invalid appBase");
1772
1801
  const { hrefs, header, footer } = siteFrameProps({
1773
1802
  name: input.name,
1774
1803
  pages: input.pages,
1775
1804
  year: input.year,
1776
1805
  fallbackActionLabel: input.fallbackActionLabel
1777
1806
  });
1807
+ const linked = appBase !== void 0;
1808
+ const appScreens = linked ? (input.screens ?? []).filter((s) => !isPageKind(s.kind)) : [];
1809
+ if (linked) checkShellScreens([...input.pages, ...appScreens]);
1810
+ const screenHrefs = Object.fromEntries([
1811
+ ...input.pages.map((p) => [p.slug, p.kind === "home" ? "/" : `/${p.slug}`]),
1812
+ ...appScreens.map((s) => [s.slug, `${appBase}${s.slug}`])
1813
+ ]);
1814
+ const frame = [
1815
+ " <SiteLinksProvider value={{ hrefs }}>",
1816
+ " <SiteFrame>",
1817
+ " <SiteHeader {...header} />",
1818
+ " {children}",
1819
+ " <SiteFooter {...footer} />",
1820
+ " </SiteFrame>",
1821
+ " </SiteLinksProvider>"
1822
+ ];
1778
1823
  return [
1779
1824
  "'use client'",
1780
1825
  "",
1781
1826
  "import type { ComponentProps } from 'react'",
1782
1827
  "import { SiteFrame, SiteHeader, SiteFooter } from '@/components/screens/parts/site-frame'",
1783
1828
  "import { SiteLinksProvider } from '@/components/screens/parts/site-links'",
1829
+ ...linked ? ["import { ScreenLinksProvider, type ScreenLinks } from '@/components/screens/parts/screen-links'"] : [],
1784
1830
  "",
1785
1831
  `const hrefs: ComponentProps<typeof SiteLinksProvider>['value']['hrefs'] = ${jsonLiteral(hrefs, 2)}`,
1786
1832
  "",
@@ -1788,15 +1834,10 @@ function assembleSiteShell(input) {
1788
1834
  "",
1789
1835
  `const footer: ComponentProps<typeof SiteFooter> = ${jsonLiteral(footer, 2)}`,
1790
1836
  "",
1837
+ ...linked ? [`const screenLinks: ScreenLinks = ${jsonLiteral({ strict: true, hrefs: screenHrefs }, 2)}`, ""] : [],
1791
1838
  "export function SiteShell({ children }: { children: React.ReactNode }) {",
1792
1839
  " return (",
1793
- " <SiteLinksProvider value={{ hrefs }}>",
1794
- " <SiteFrame>",
1795
- " <SiteHeader {...header} />",
1796
- " {children}",
1797
- " <SiteFooter {...footer} />",
1798
- " </SiteFrame>",
1799
- " </SiteLinksProvider>",
1840
+ ...linked ? [" <ScreenLinksProvider value={screenLinks}>", ...frame.map((l) => ` ${l}`), " </ScreenLinksProvider>"] : frame,
1800
1841
  " )",
1801
1842
  "}",
1802
1843
  "",
@@ -1829,8 +1870,10 @@ function registrySite(manifest, year = (/* @__PURE__ */ new Date()).getUTCFullYe
1829
1870
  const action = manifest.screenIndex?.find((e) => e.kind === "home")?.action;
1830
1871
  return { name: manifest.name, year, ...typeof action === "string" ? { action } : {} };
1831
1872
  }
1832
- function registryFile(componentsDir, t, screens, site) {
1833
- return stamped(registryPath(componentsDir), REGISTRY_STAMP, rewriteForApp(assembleScreenRegistry({ screens, ...site }), t));
1873
+ var SECTION_SCREENS_BASE = "/design-system/screens/";
1874
+ function registryFile(componentsDir, t, screens, site, links = null) {
1875
+ const screenHrefBase = links === null ? void 0 : links.framework === "vite" ? "#/screens/" : SECTION_SCREENS_BASE;
1876
+ return stamped(registryPath(componentsDir), REGISTRY_STAMP, rewriteForApp(assembleScreenRegistry({ screens, ...site, ...screenHrefBase !== void 0 ? { screenHrefBase } : {} }), t));
1834
1877
  }
1835
1878
  function shownBlockGroups(groups, blocks, keptBlockIds = []) {
1836
1879
  if (blocks === "write") return groups;
@@ -1888,7 +1931,7 @@ function planSectionFiles(input) {
1888
1931
  }
1889
1932
  if (blocks === "skip") files.push(stamped(ds("block-view.tsx"), "section:block-view", NO_BLOCKS_VIEW));
1890
1933
  const screens = sectionKnowsScreens(manifest);
1891
- if (screens && input.screens !== null) files.push(registryFile(componentsDir, t, input.screens, registrySite(manifest)));
1934
+ if (screens && input.screens !== null) files.push(registryFile(componentsDir, t, input.screens, registrySite(manifest), input.screenLinks ? { framework: input.framework } : null));
1892
1935
  else if (screens && !input.registryOnDisk) {
1893
1936
  const fallback = section.files.find((f) => f.key === REGISTRY_KEY);
1894
1937
  files.push(stamped(registryPath(componentsDir), REGISTRY_STAMP, rewriteForApp(fallback.contents, t)));
@@ -2492,7 +2535,7 @@ async function postNdjson(opts, fetchImpl = fetch) {
2492
2535
 
2493
2536
  // src/connect/open-browser.ts
2494
2537
  import { spawn as spawn2 } from "node:child_process";
2495
- var launchDetached = (cmd, args) => new Promise((resolve8) => {
2538
+ var launchDetached = (cmd, args) => new Promise((resolve10) => {
2496
2539
  try {
2497
2540
  const child = spawn2(cmd, args, {
2498
2541
  shell: false,
@@ -2500,13 +2543,13 @@ var launchDetached = (cmd, args) => new Promise((resolve8) => {
2500
2543
  detached: true,
2501
2544
  windowsHide: true
2502
2545
  });
2503
- child.once("error", () => resolve8(false));
2546
+ child.once("error", () => resolve10(false));
2504
2547
  child.once("spawn", () => {
2505
2548
  child.unref();
2506
- resolve8(true);
2549
+ resolve10(true);
2507
2550
  });
2508
2551
  } catch {
2509
- resolve8(false);
2552
+ resolve10(false);
2510
2553
  }
2511
2554
  });
2512
2555
  function deviceUrl(api) {
@@ -2836,7 +2879,8 @@ function planScreenFiles(a) {
2836
2879
  for (const screen of (manifest.screens ?? []).filter((s) => wanted.includes(s.slug))) {
2837
2880
  const page = isPageKind(kindOf.get(screen.slug) ?? "");
2838
2881
  const withFrame = page && byName.has("site-frame");
2839
- const parts = closureOf(withFrame ? [...screen.parts, "site-frame"] : screen.parts, byName);
2882
+ const roots = [...screen.parts, ...withFrame ? ["site-frame"] : [], ...byName.has("screen-links") ? ["screen-links"] : []];
2883
+ const parts = closureOf(roots, byName);
2840
2884
  const blocker = force ? void 0 : parts.find(editedAndChanged);
2841
2885
  if (blocker) {
2842
2886
  plan.skipped.push({ slug: screen.slug, reason: SCREEN_PART_EDITED(screen.slug, blocker.file), agentReason: SCREEN_PART_EDITED_FOR_AGENT(screen.slug, blocker.file) });
@@ -2907,7 +2951,8 @@ function planShellFile(a) {
2907
2951
  const { targets: t } = a;
2908
2952
  if (t.componentsDir === null) throw new CliError(SCREENS_NEED_COMPONENTS_DIR(t.componentsAlias));
2909
2953
  const path = `${t.componentsDir}/screens/${SHELL_FILE}`;
2910
- const contents = stampContents(SHELL_STAMP, rewriteForApp(assembleAppShell({ name: a.name, screens: a.screens, hrefFor: "root" }), t));
2954
+ const source = assembleAppShell({ name: a.name, screens: a.screens, hrefFor: "root", ...a.screenLinks === true ? { screenLinks: true } : {} });
2955
+ const contents = stampContents(SHELL_STAMP, rewriteForApp(source, t));
2911
2956
  return { path, contents, status: existingFileStatus(resolveInside(a.root, path)), importPath: `${t.componentsAlias}/screens/app-shell` };
2912
2957
  }
2913
2958
  function sitePagesFor(slugs, index) {
@@ -2923,11 +2968,24 @@ function sitePagesFor(slugs, index) {
2923
2968
  }
2924
2969
  return pages;
2925
2970
  }
2971
+ function screenLinksPresent(root, t, manifest, disk, written) {
2972
+ const part = (manifest.screenParts ?? []).find((p) => p.name === "screen-links");
2973
+ if (!part) return false;
2974
+ if (written.some((w) => w.path.endsWith("/parts/screen-links.tsx"))) return true;
2975
+ const on = disk.parts.get("screen-links");
2976
+ return on !== void 0 && !on.edited && on.hash === hashOf(rewriteForApp(part.contents, t));
2977
+ }
2926
2978
  function planSiteFile(a) {
2927
2979
  const { targets: t } = a;
2928
2980
  if (t.componentsDir === null) throw new CliError(SCREENS_NEED_COMPONENTS_DIR(t.componentsAlias));
2929
2981
  const path = `${t.componentsDir}/screens/${SITE_FILE}`;
2930
- const source = assembleSiteShell({ name: a.name, pages: a.pages, year: a.year, ...a.action !== void 0 ? { fallbackActionLabel: a.action } : {} });
2982
+ const source = assembleSiteShell({
2983
+ name: a.name,
2984
+ pages: a.pages,
2985
+ year: a.year,
2986
+ ...a.action !== void 0 ? { fallbackActionLabel: a.action } : {},
2987
+ ...a.screens !== void 0 ? { appBase: "/", screens: a.screens } : {}
2988
+ });
2931
2989
  const contents = stampContents(SITE_STAMP, rewriteForApp(source, t));
2932
2990
  return { path, contents, status: existingFileStatus(resolveInside(a.root, path)), importPath: `${t.componentsAlias}/screens/site-shell` };
2933
2991
  }
@@ -3435,7 +3493,7 @@ function sectionDecision(input) {
3435
3493
  const blocks = !input.present ? input.blocksWanted ? "write" : "skip" : input.blocksOnDisk ? input.blocksWanted ? "write" : "keep" : "skip";
3436
3494
  return { write: true, blocks, note: null };
3437
3495
  }
3438
- function planSection(root, input, info, t, manifest, chosen, onDisk, screens) {
3496
+ function planSection(root, input, info, t, manifest, chosen, onDisk, screens, screenLinks) {
3439
3497
  const none = (note) => ({ decision: { write: false, blocks: "skip", note }, files: () => [], paths: [], packages: {}, blockCount: 0 });
3440
3498
  const section = manifest.section;
3441
3499
  if (!section) return none(null);
@@ -3451,7 +3509,7 @@ function planSection(root, input, info, t, manifest, chosen, onDisk, screens) {
3451
3509
  const framework = info.framework === "vite" ? "vite" : "next";
3452
3510
  const srcDir = existsSync9(join5(root, "src")) ? "src" : "";
3453
3511
  const registryOnDisk = existsSync9(resolveInside(root, registryPath(t.componentsDir)));
3454
- const files = (darkMarker) => planSectionFiles({ framework, appDir, srcDir, targets: t, manifest, blocks: decision.blocks, keptBlockIds: blockIds, darkMarker, screens, registryOnDisk });
3512
+ const files = (darkMarker) => planSectionFiles({ framework, appDir, srcDir, targets: t, manifest, blocks: decision.blocks, keptBlockIds: blockIds, darkMarker, screens, registryOnDisk, screenLinks });
3455
3513
  return {
3456
3514
  decision,
3457
3515
  files,
@@ -3510,18 +3568,19 @@ async function runAdd(input, deps) {
3510
3568
  const noScreensLeft = bareRerun && screensAfter.length === 0;
3511
3569
  const listScreens2 = fetchedScreens || noScreensLeft;
3512
3570
  const writeShell = input.shell === true || disk.shell && listScreens2;
3513
- const shellPlan = writeShell ? planShellFile({ root, targets: planned, name: manifest.name, screens: screensAfter }) : null;
3571
+ const screenLinks = screenLinksPresent(root, planned, manifest, disk, screenPlan?.write ?? []);
3572
+ const shellPlan = writeShell ? planShellFile({ root, targets: planned, name: manifest.name, screens: screensAfter, screenLinks }) : null;
3514
3573
  const siteSkipped = siteConflict !== null ? { reason: SITE_SKIPPED(siteConflict) } : screenPlan?.siteSkipped ?? null;
3515
3574
  const writeSite = (input.site === true || disk.site && listScreens2) && siteSkipped === null;
3516
3575
  const siteListed = noScreensLeft ? [] : sitePages;
3517
- const sitePlan = writeSite ? planSiteFile({ root, targets: planned, pages: siteListed, ...registrySite(manifest) }) : null;
3576
+ const sitePlan = writeSite ? planSiteFile({ root, targets: planned, pages: siteListed, ...registrySite(manifest), ...screenLinks ? { screens: noScreensLeft ? [] : screensAfter } : {} }) : null;
3518
3577
  const onDisk = sectionPresent(root, planned);
3519
3578
  const screensOnly = (input.screens !== void 0 || input.shell === true || input.site === true) && input.components.length === 0 && !input.all && !onDisk.present;
3520
3579
  const chosen = await chooseComponents(input, manifest, previouslyAdded(root, planned), onDisk.present, deps.questions, {
3521
3580
  components: [...screenPlan?.kitComponents ?? [], ...shellPlan ? SHELL_COMPONENTS : []],
3522
3581
  only: screensOnly
3523
3582
  });
3524
- const section = planSection(root, input, info, planned, manifest, chosen, onDisk, listScreens2 ? screensAfter : null);
3583
+ const section = planSection(root, input, info, planned, manifest, chosen, onDisk, listScreens2 ? screensAfter : null, screenLinks);
3525
3584
  let packages = planPackages(chosen, manifest, info.deps);
3526
3585
  let sectionNote = screensOnly && section.decision.note === SECTION_NEEDS_FULL_KIT ? null : section.decision.note;
3527
3586
  let writeSection = section.decision.write;
@@ -3537,7 +3596,7 @@ async function runAdd(input, deps) {
3537
3596
  (name) => !manifest.components.some((c) => c.name === name) ? SHELL_NOT_IN_KIT(name) : packages.skipped.find((k) => k.name === name)?.reason ?? null
3538
3597
  ).find((r) => r !== null) ?? null;
3539
3598
  const shellToWrite = shellBlocker === null ? shellPlan : null;
3540
- const registryAlone = !writeSection && onDisk.present && fetchedScreens && (screenPlan?.write.length ?? 0) > 0 && planned.componentsDir !== null && sectionReadsScreens(root, planned) ? registryFile(planned.componentsDir, planned, screensAfter, registrySite(manifest)) : null;
3599
+ const registryAlone = !writeSection && onDisk.present && fetchedScreens && (screenPlan?.write.length ?? 0) > 0 && planned.componentsDir !== null && sectionReadsScreens(root, planned) ? registryFile(planned.componentsDir, planned, screensAfter, registrySite(manifest), screenLinks ? { framework: info.framework === "vite" ? "vite" : "next" } : null) : null;
3541
3600
  const plan = planFiles(root, planned, componentClosure(packages.components, manifest), manifest);
3542
3601
  const sectionStatus = [...writeSection ? section.paths : [], ...registryAlone ? [registryAlone.path] : []].filter((p) => !p.endsWith(".json")).map((p) => [p, existingFileStatus(resolveInside(root, p))]);
3543
3602
  const shellStatus = [...shellToWrite ? [shellToWrite] : [], ...sitePlan ? [sitePlan] : []].map((f) => [f.path, f.status]);
@@ -3783,10 +3842,10 @@ function nextLine() {
3783
3842
  if (line !== void 0) return Promise.resolve(line);
3784
3843
  if (closed) return Promise.reject(new CliError(EOF_MESSAGE));
3785
3844
  process.stdin.ref?.();
3786
- return new Promise((resolve8, reject) => waiting.push({
3845
+ return new Promise((resolve10, reject) => waiting.push({
3787
3846
  resolve: (line2) => {
3788
3847
  process.stdin.unref?.();
3789
- resolve8(line2);
3848
+ resolve10(line2);
3790
3849
  },
3791
3850
  reject: (err) => {
3792
3851
  process.stdin.unref?.();
@@ -3899,7 +3958,7 @@ function pickTty(question, options, start, stdin, stdout) {
3899
3958
  stdin.resume();
3900
3959
  stdout.write("\x1B[?25l");
3901
3960
  draw([question, ...rows()]);
3902
- return new Promise((resolve8, reject) => {
3961
+ return new Promise((resolve10, reject) => {
3903
3962
  const finish = (after) => {
3904
3963
  stdin.off("keypress", onKey);
3905
3964
  stdin.setRawMode(false);
@@ -3920,7 +3979,7 @@ function pickTty(question, options, start, stdin, stdout) {
3920
3979
  stdout.write(`\r\x1B[J${question} ${chosen.label}
3921
3980
  `);
3922
3981
  });
3923
- resolve8(chosen.value);
3982
+ resolve10(chosen.value);
3924
3983
  return;
3925
3984
  }
3926
3985
  if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
@@ -3952,7 +4011,7 @@ function pickManyTty(question, options, preselected, stdin, stdout) {
3952
4011
  stdin.resume();
3953
4012
  stdout.write("\x1B[?25l");
3954
4013
  draw([head, ...rows()]);
3955
- return new Promise((resolve8, reject) => {
4014
+ return new Promise((resolve10, reject) => {
3956
4015
  const finish = (after) => {
3957
4016
  stdin.off("keypress", onKey);
3958
4017
  stdin.setRawMode(false);
@@ -3973,7 +4032,7 @@ function pickManyTty(question, options, preselected, stdin, stdout) {
3973
4032
  stdout.write(`\r\x1B[J${question} ${chosen.length > 0 ? chosen.map((o) => o.label).join(", ") : "none"}
3974
4033
  `);
3975
4034
  });
3976
- resolve8(chosen.map((o) => o.value));
4035
+ resolve10(chosen.map((o) => o.value));
3977
4036
  return;
3978
4037
  }
3979
4038
  if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
@@ -3989,14 +4048,20 @@ function pickManyTty(question, options, preselected, stdin, stdout) {
3989
4048
  }
3990
4049
 
3991
4050
  // src/commands/scaffold.ts
3992
- import { resolve as resolve4 } from "node:path";
4051
+ import { resolve as resolve7 } from "node:path";
3993
4052
 
3994
4053
  // src/connect/resolve-token.ts
3995
4054
  import { homedir } from "node:os";
4055
+ import { join as join10, relative as relative4 } from "node:path";
4056
+
4057
+ // src/connect/account-store.ts
4058
+ import { createHash as createHash2 } from "node:crypto";
4059
+ import { readFileSync as readFileSync11, realpathSync as realpathSync2 } from "node:fs";
4060
+ import { dirname as dirname3, join as join7, parse, resolve as resolve4, sep as sep3 } from "node:path";
3996
4061
 
3997
4062
  // src/connect/store.ts
3998
4063
  import { randomBytes } from "node:crypto";
3999
- import { chmodSync, constants, copyFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync10, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
4064
+ import { chmodSync, constants, copyFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync10, realpathSync, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
4000
4065
  import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join6, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
4001
4066
  var WHERE = ["keychain", "secret-service", "dpapi", "file"];
4002
4067
  function credentialsPath(env, platform, home) {
@@ -4083,6 +4148,16 @@ function isWithin(folder, root) {
4083
4148
  const rel = relative2(root, folder);
4084
4149
  return rel === "" || rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute2(rel);
4085
4150
  }
4151
+ function real(path) {
4152
+ try {
4153
+ return realpathSync(path);
4154
+ } catch {
4155
+ return resolve3(path);
4156
+ }
4157
+ }
4158
+ function savedHolds(folder, saved) {
4159
+ return isWithin(resolve3(folder), resolve3(saved)) || isWithin(real(folder), real(saved));
4160
+ }
4086
4161
  function createStore(opts) {
4087
4162
  const { env, platform, exec, home } = opts;
4088
4163
  const path = credentialsPath(env, platform, home);
@@ -4116,8 +4191,7 @@ function createStore(opts) {
4116
4191
  return osBackend(entry.where).get(projectId, entry.secret);
4117
4192
  },
4118
4193
  byFolder(folder) {
4119
- const target = resolve3(folder);
4120
- return Object.entries(readCredentials(path).projects).filter(([, e]) => e.folders.some((saved) => isWithin(target, resolve3(saved)))).map(([id, e]) => publicEntry(id, e));
4194
+ return Object.entries(readCredentials(path).projects).filter(([, e]) => e.folders.some((saved) => savedHolds(folder, saved))).map(([id, e]) => publicEntry(id, e));
4121
4195
  },
4122
4196
  entry(projectId) {
4123
4197
  const found = readCredentials(path).projects;
@@ -4148,6 +4222,253 @@ function createStore(opts) {
4148
4222
  };
4149
4223
  }
4150
4224
 
4225
+ // src/connect/account-store.ts
4226
+ var WHERE2 = ["keychain", "secret-service", "dpapi", "file"];
4227
+ var ACCOUNT_TOKEN2 = /^dsa_[A-Za-z0-9_-]{43}$/;
4228
+ var PROJECT_ID2 = /^[A-Za-z0-9_-]+$/;
4229
+ var LABEL = "account";
4230
+ function normaliseOrigin(origin) {
4231
+ let url;
4232
+ try {
4233
+ url = new URL(origin);
4234
+ } catch {
4235
+ throw new CliError(`Not a server address: ${JSON.stringify(origin)}.`);
4236
+ }
4237
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new CliError("A server address must start with http:// or https://.");
4238
+ if (url.username || url.password) throw new CliError("A server address must not carry a user name or password.");
4239
+ return `${url.origin.toLowerCase()}${url.pathname.replace(/\/+$/, "")}`;
4240
+ }
4241
+ function accountSecretId(origin) {
4242
+ const id = `account-${createHash2("sha256").update(normaliseOrigin(origin)).digest("hex").slice(0, 16)}`;
4243
+ assertProjectId(id);
4244
+ return id;
4245
+ }
4246
+ function accountPath(env, platform, home) {
4247
+ return join7(dirname3(credentialsPath(env, platform, home)), "account.json");
4248
+ }
4249
+ function normaliseFolder(folder) {
4250
+ let path = resolve4(folder);
4251
+ try {
4252
+ path = realpathSync2(path);
4253
+ } catch {
4254
+ }
4255
+ const root = parse(path).root;
4256
+ while (path.length > root.length && (path.endsWith(sep3) || path.endsWith("/"))) path = path.slice(0, -1);
4257
+ return path;
4258
+ }
4259
+ function isRecord3(value) {
4260
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4261
+ }
4262
+ function readAccount(value) {
4263
+ if (!isRecord3(value)) return null;
4264
+ const { email, where, folders, links, secret } = value;
4265
+ if (typeof email !== "string" || !WHERE2.includes(where)) return null;
4266
+ if (!Array.isArray(folders) || !folders.every((f) => typeof f === "string")) return null;
4267
+ if (!isRecord3(links) || !Object.values(links).every((id) => typeof id === "string" && PROJECT_ID2.test(id))) return null;
4268
+ if (secret !== void 0 && typeof secret !== "string") return null;
4269
+ const entry = { email, where, folders: [...folders], links: Object.assign(/* @__PURE__ */ Object.create(null), links) };
4270
+ if (secret !== void 0) entry.secret = secret;
4271
+ return entry;
4272
+ }
4273
+ function readAccounts(path) {
4274
+ const accounts = /* @__PURE__ */ Object.create(null);
4275
+ let text;
4276
+ try {
4277
+ text = readFileSync11(path, "utf8");
4278
+ } catch {
4279
+ return { version: 1, accounts };
4280
+ }
4281
+ let parsed;
4282
+ try {
4283
+ parsed = JSON.parse(text);
4284
+ } catch {
4285
+ return { version: 1, accounts, unreadable: true };
4286
+ }
4287
+ if (!isRecord3(parsed) || parsed.version !== 1 || !isRecord3(parsed.accounts)) return { version: 1, accounts, unreadable: true };
4288
+ for (const [origin, value] of Object.entries(parsed.accounts)) {
4289
+ const entry = readAccount(value);
4290
+ if (entry) accounts[origin] = entry;
4291
+ }
4292
+ return { version: 1, accounts };
4293
+ }
4294
+ function publicEntry2(origin, e) {
4295
+ return { origin, email: e.email, where: e.where, folders: [...e.folders], links: { ...e.links } };
4296
+ }
4297
+ function createAccountStore(opts) {
4298
+ const { env, platform, exec, home } = opts;
4299
+ const path = accountPath(env, platform, home);
4300
+ const forceFile = env.DESIGNSOURCE_STORE === "file";
4301
+ const osBackend = (where) => where === "file" ? null : backendFor(where, exec, home);
4302
+ const update = (origin, change) => {
4303
+ const key = normaliseOrigin(origin);
4304
+ const data = readAccounts(path);
4305
+ const entry = Object.hasOwn(data.accounts, key) ? data.accounts[key] : null;
4306
+ if (!entry) return null;
4307
+ if (change(entry)) writePrivateJson(path, data);
4308
+ return publicEntry2(key, entry);
4309
+ };
4310
+ return {
4311
+ all() {
4312
+ return Object.entries(readAccounts(path).accounts).map(([origin, e]) => publicEntry2(origin, e));
4313
+ },
4314
+ get(origin) {
4315
+ const key = normaliseOrigin(origin);
4316
+ const { accounts } = readAccounts(path);
4317
+ return Object.hasOwn(accounts, key) ? publicEntry2(key, accounts[key]) : null;
4318
+ },
4319
+ async token(origin) {
4320
+ const key = normaliseOrigin(origin);
4321
+ const { accounts } = readAccounts(path);
4322
+ if (!Object.hasOwn(accounts, key)) return null;
4323
+ const entry = accounts[key];
4324
+ const value = entry.where === "file" ? entry.secret ?? null : await osBackend(entry.where).get(accountSecretId(key), entry.secret);
4325
+ return value !== null && ACCOUNT_TOKEN2.test(value) ? value : null;
4326
+ },
4327
+ async save({ origin, email, token, folder }) {
4328
+ const key = normaliseOrigin(origin);
4329
+ if (!ACCOUNT_TOKEN2.test(token)) throw new CliError("Unexpected account token from the API.");
4330
+ const id = accountSecretId(key);
4331
+ const { unreadable, ...data } = readAccounts(path);
4332
+ const previous = Object.hasOwn(data.accounts, key) ? data.accounts[key] : void 0;
4333
+ const folders = [.../* @__PURE__ */ new Set([...previous?.folders ?? [], normaliseFolder(folder)])];
4334
+ const links = Object.assign(/* @__PURE__ */ Object.create(null), previous?.links);
4335
+ let entry = { email, where: "file", folders, links, secret: token };
4336
+ const backend = forceFile ? null : await chooseBackend({ platform, exec, cwd: home, token });
4337
+ if (backend) {
4338
+ const kept = await backend.put(id, LABEL, token);
4339
+ if (kept) entry = { email, where: backend.where, folders, links, ...kept.secret === void 0 ? {} : { secret: kept.secret } };
4340
+ }
4341
+ data.accounts[key] = entry;
4342
+ const backup = unreadable ? backUp(path) : void 0;
4343
+ writePrivateJson(path, data);
4344
+ if (previous && previous.where !== entry.where) await osBackend(previous.where)?.remove(id);
4345
+ return { ...publicEntry2(key, entry), ...backup === void 0 ? {} : { backup } };
4346
+ },
4347
+ trust(origin, folder) {
4348
+ const target = normaliseFolder(folder);
4349
+ return update(origin, (entry) => {
4350
+ if (entry.folders.includes(target)) return false;
4351
+ entry.folders = [...entry.folders, target];
4352
+ return true;
4353
+ });
4354
+ },
4355
+ link(origin, folder, projectId) {
4356
+ assertProjectId(projectId);
4357
+ const target = normaliseFolder(folder);
4358
+ return update(origin, (entry) => {
4359
+ if (entry.links[target] === projectId) return false;
4360
+ entry.links[target] = projectId;
4361
+ return true;
4362
+ });
4363
+ },
4364
+ async forget(origin) {
4365
+ const key = normaliseOrigin(origin);
4366
+ const data = readAccounts(path);
4367
+ if (!Object.hasOwn(data.accounts, key)) return null;
4368
+ const entry = data.accounts[key];
4369
+ try {
4370
+ await osBackend(entry.where)?.remove(accountSecretId(key));
4371
+ } catch {
4372
+ }
4373
+ delete data.accounts[key];
4374
+ writePrivateJson(path, data);
4375
+ return publicEntry2(key, entry);
4376
+ }
4377
+ };
4378
+ }
4379
+
4380
+ // src/connect/project-root.ts
4381
+ import { existsSync as existsSync10 } from "node:fs";
4382
+ import { dirname as dirname4, isAbsolute as isAbsolute3, join as join8, relative as relative3, resolve as resolve5, sep as sep4 } from "node:path";
4383
+ function projectRoot(cwd, exists = existsSync10) {
4384
+ let dir = resolve5(cwd);
4385
+ for (; ; ) {
4386
+ if (exists(join8(dir, ".git"))) return dir;
4387
+ const parent = dirname4(dir);
4388
+ if (parent === dir) return resolve5(cwd);
4389
+ dir = parent;
4390
+ }
4391
+ }
4392
+ function within2(folder, root) {
4393
+ const rel = relative3(root, folder);
4394
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep4}`) && !isAbsolute3(rel);
4395
+ }
4396
+ function homeFolderRefusal(root, home) {
4397
+ const folder = resolve5(root);
4398
+ const homeDir = resolve5(home);
4399
+ const tail = "and writing there would set up every project on this computer.";
4400
+ if (folder === homeDir) return `Run this in your project folder \u2014 ${folder} is your home folder, ${tail}`;
4401
+ if (dirname4(folder) === folder || within2(homeDir, folder)) return `Run this in your project folder \u2014 ${folder} is a system folder, ${tail}`;
4402
+ return null;
4403
+ }
4404
+
4405
+ // src/connect/worktree.ts
4406
+ import { lstatSync, readFileSync as readFileSync12, realpathSync as realpathSync3 } from "node:fs";
4407
+ import { basename as basename2, dirname as dirname5, isAbsolute as isAbsolute4, join as join9, resolve as resolve6 } from "node:path";
4408
+ var POINTER_MAX_BYTES = 4096;
4409
+ var realWorktreeFs = {
4410
+ readSmall(path) {
4411
+ try {
4412
+ const st = lstatSync(path);
4413
+ if (!st.isFile() || st.size > POINTER_MAX_BYTES) return null;
4414
+ return readFileSync12(path, "utf8");
4415
+ } catch {
4416
+ return null;
4417
+ }
4418
+ },
4419
+ realpath(path) {
4420
+ try {
4421
+ return realpathSync3(path);
4422
+ } catch {
4423
+ return null;
4424
+ }
4425
+ }
4426
+ };
4427
+ function oneLine(text) {
4428
+ const lines = text.split(/\r?\n/).filter((l) => l.trim() !== "");
4429
+ if (lines.length !== 1) return null;
4430
+ const line = lines[0].trim();
4431
+ return /[\u0000-\u001f\u007f]/.test(line) ? null : line;
4432
+ }
4433
+ function mainRepoRoot(root, fs = realWorktreeFs) {
4434
+ const dotGit = join9(root, ".git");
4435
+ const pointer = fs.readSmall(dotGit);
4436
+ if (pointer === null) return null;
4437
+ const line = oneLine(pointer);
4438
+ if (line === null || !line.startsWith("gitdir:")) return null;
4439
+ const target = line.slice("gitdir:".length).trim();
4440
+ if (target === "") return null;
4441
+ const gitdir = fs.realpath(isAbsolute4(target) ? target : resolve6(root, target));
4442
+ if (gitdir === null) return null;
4443
+ const worktrees = dirname5(gitdir);
4444
+ if (basename2(worktrees) !== "worktrees") return null;
4445
+ const commonText = fs.readSmall(join9(gitdir, "commondir"));
4446
+ const commonLine = commonText === null ? null : oneLine(commonText);
4447
+ if (commonLine === null) return null;
4448
+ const common = fs.realpath(isAbsolute4(commonLine) ? commonLine : resolve6(gitdir, commonLine));
4449
+ if (common === null || common !== dirname5(worktrees)) return null;
4450
+ if (basename2(common) !== ".git") return null;
4451
+ const backText = fs.readSmall(join9(gitdir, "gitdir"));
4452
+ const backLine = backText === null ? null : oneLine(backText);
4453
+ if (backLine === null || !isAbsolute4(backLine)) return null;
4454
+ const back = fs.realpath(backLine);
4455
+ const here = fs.realpath(dotGit);
4456
+ if (back === null || here === null || back !== here) return null;
4457
+ const main2 = fs.realpath(dirname5(common));
4458
+ return main2 !== null && main2 !== fs.realpath(root) ? main2 : null;
4459
+ }
4460
+
4461
+ // src/connect/account-paths.ts
4462
+ function originOf(api) {
4463
+ normaliseOrigin(api);
4464
+ return new URL(api).origin;
4465
+ }
4466
+ function projectFolders(cwd) {
4467
+ const work = normaliseFolder(projectRoot(normaliseFolder(cwd)));
4468
+ const main2 = mainRepoRoot(work);
4469
+ return main2 === null ? { work, trust: work, worktree: false } : { work, trust: normaliseFolder(main2), worktree: true };
4470
+ }
4471
+
4151
4472
  // src/connect/resolve-token.ts
4152
4473
  var NO_TOKEN_FOR_PROJECT = (nameOrId) => `This computer has no token for the "${nameOrId}" design system. Run npx designsource connect in the project folder.`;
4153
4474
  function defaultStore(env = process.env) {
@@ -4161,7 +4482,7 @@ async function resolveToken(input, prompts = TERMINAL) {
4161
4482
  const token = await store.token(projectId);
4162
4483
  return token ? { token, entry: store.entry(projectId) } : null;
4163
4484
  }
4164
- const matches = store.byFolder(cwd);
4485
+ const matches = byFolderOrMain(store, cwd);
4165
4486
  let chosen = matches[0];
4166
4487
  if (matches.length > 1) {
4167
4488
  if (!interactive) {
@@ -4178,6 +4499,12 @@ async function resolveToken(input, prompts = TERMINAL) {
4178
4499
  const typed = await prompts.askHidden("Project token (workbench \u2192 Project settings):");
4179
4500
  return typed ? { token: typed, entry: null } : null;
4180
4501
  }
4502
+ function byFolderOrMain(store, cwd) {
4503
+ const here = store.byFolder(cwd);
4504
+ if (here.length > 0) return here;
4505
+ const { work, trust, worktree } = projectFolders(cwd);
4506
+ return worktree ? store.byFolder(join10(trust, relative4(work, normaliseFolder(cwd)))) : here;
4507
+ }
4181
4508
 
4182
4509
  // src/manifest.ts
4183
4510
  var malformed2 = () => new CliError("Unexpected response from the API \u2014 not a starter manifest.");
@@ -4269,7 +4596,7 @@ async function scaffold(input, env, io) {
4269
4596
  ${written.map((p) => ` ${p}`).join("\n")}
4270
4597
 
4271
4598
  `);
4272
- io.stdout(nextStepsText({ runner, framework, folder, here: root === resolve4(io.cwd) }));
4599
+ io.stdout(nextStepsText({ runner, framework, folder, here: root === resolve7(io.cwd) }));
4273
4600
  }
4274
4601
 
4275
4602
  // src/commands/add.ts
@@ -4351,7 +4678,7 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
4351
4678
  // src/commands/connect.ts
4352
4679
  import { accessSync, constants as constants2, existsSync as existsSync11, statSync as statSync3 } from "node:fs";
4353
4680
  import { homedir as homedir2 } from "node:os";
4354
- import { join as join8 } from "node:path";
4681
+ import { join as join11 } from "node:path";
4355
4682
 
4356
4683
  // src/connect/fetch-project.ts
4357
4684
  var RejectedTokenError = class extends CliError {
@@ -4375,31 +4702,6 @@ async function fetchProject(opts, fetchImpl = fetch) {
4375
4702
  return { id, name };
4376
4703
  }
4377
4704
 
4378
- // src/connect/project-root.ts
4379
- import { existsSync as existsSync10 } from "node:fs";
4380
- import { dirname as dirname3, isAbsolute as isAbsolute3, join as join7, relative as relative3, resolve as resolve5, sep as sep3 } from "node:path";
4381
- function projectRoot(cwd, exists = existsSync10) {
4382
- let dir = resolve5(cwd);
4383
- for (; ; ) {
4384
- if (exists(join7(dir, ".git"))) return dir;
4385
- const parent = dirname3(dir);
4386
- if (parent === dir) return resolve5(cwd);
4387
- dir = parent;
4388
- }
4389
- }
4390
- function within2(folder, root) {
4391
- const rel = relative3(root, folder);
4392
- return rel === "" || rel !== ".." && !rel.startsWith(`..${sep3}`) && !isAbsolute3(rel);
4393
- }
4394
- function homeFolderRefusal(root, home) {
4395
- const folder = resolve5(root);
4396
- const homeDir = resolve5(home);
4397
- const tail = "and writing there would set up every project on this computer.";
4398
- if (folder === homeDir) return `Run this in your project folder \u2014 ${folder} is your home folder, ${tail}`;
4399
- if (dirname3(folder) === folder || within2(homeDir, folder)) return `Run this in your project folder \u2014 ${folder} is a system folder, ${tail}`;
4400
- return null;
4401
- }
4402
-
4403
4705
  // src/commands/connect.ts
4404
4706
  var TERMINAL_PROMPTS = { pickMany, pick: (question, options) => pick(question, options, 0), askHidden };
4405
4707
  function onPath(bin, env, platform) {
@@ -4408,7 +4710,7 @@ function onPath(bin, env, platform) {
4408
4710
  const exts = windows ? ["", ...(env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""];
4409
4711
  return dirs.some(
4410
4712
  (dir) => exts.some((ext) => {
4411
- const file = join8(dir, bin + ext);
4713
+ const file = join11(dir, bin + ext);
4412
4714
  try {
4413
4715
  if (!statSync3(file).isFile()) return false;
4414
4716
  if (!windows) accessSync(file, constants2.X_OK);
@@ -4458,6 +4760,8 @@ function appLines(id, plan) {
4458
4760
  }
4459
4761
  var CODEX_TRUST_NOTE = "Codex reads it once you trust this project in Codex.";
4460
4762
  var GEMINI_TRUST_NOTE = "Gemini CLI reads it unless folder trust is on and this folder is not trusted.";
4763
+ var COMMIT_SETTINGS_NOTE = "Commit these settings files: they hold no token, and worktrees and teammates get designsource only from a committed copy.";
4764
+ var WORKTREE_NOTE = (main2) => `This folder is a git worktree of ${main2}: that repository and every worktree of it are set up; the settings files go here.`;
4461
4765
  function closingLines(apps, changed) {
4462
4766
  const has = (id) => apps.includes(id);
4463
4767
  const restart = [changed.includes("cursor") && "Cursor", changed.includes("vscode") && "VS Code"].filter((s) => typeof s === "string");
@@ -4468,7 +4772,8 @@ function closingLines(apps, changed) {
4468
4772
  ...has("codex") ? [CODEX_TRUST_NOTE] : [],
4469
4773
  ...has("gemini") ? [GEMINI_TRUST_NOTE] : [],
4470
4774
  "Then ask your agent to add the UI kit.",
4471
- "These files hold no token and are safe to commit; teammates run npx designsource connect once."
4775
+ COMMIT_SETTINGS_NOTE,
4776
+ "Teammates run npx designsource connect once."
4472
4777
  ];
4473
4778
  }
4474
4779
  async function runConnect(args, io, deps = defaultConnectDeps(process.env)) {
@@ -4477,14 +4782,16 @@ async function runConnect(args, io, deps = defaultConnectDeps(process.env)) {
4477
4782
  const interactive = terminal && !args.yes;
4478
4783
  const prompts = deps.prompts ?? TERMINAL_PROMPTS;
4479
4784
  const root = projectRoot(io.cwd);
4785
+ const main2 = mainRepoRoot(normaliseFolder(root));
4786
+ const saveFolder = main2 ?? root;
4480
4787
  const say = (lines) => io.stdout(lines.map((l) => `${l}
4481
4788
  `).join(""));
4482
- if (args.forget) return forget(args, root, store, interactive, prompts, deps.credentialsPath, say);
4483
- const refusal = homeFolderRefusal(root, deps.home ?? homedir2());
4789
+ if (args.forget) return forget(args, root, saveFolder, store, interactive, prompts, deps.credentialsPath, say);
4790
+ const refusal = homeFolderRefusal(root, deps.home ?? homedir2()) ?? (main2 ? homeFolderRefusal(main2, deps.home ?? homedir2()) : null);
4484
4791
  if (refusal) throw new CliError(refusal);
4485
- say([`Connecting ${root}`]);
4792
+ say([`Connecting ${root}`, ...main2 ? [WORKTREE_NOTE(main2)] : []]);
4486
4793
  let apps;
4487
- const connected = args.apps ? null : connectedApps(root, store);
4794
+ const connected = args.apps ? null : connectedApps(root, saveFolder, store);
4488
4795
  if (args.apps) apps = args.apps;
4489
4796
  else if (connected) apps = connected;
4490
4797
  else {
@@ -4515,8 +4822,8 @@ async function runConnect(args, io, deps = defaultConnectDeps(process.env)) {
4515
4822
  project = await fetchProject({ api, token }, io.fetchImpl);
4516
4823
  }
4517
4824
  const plans = apps.map((id) => ({ id, plan: planAppFile(root, id, project.id) }));
4518
- const kept = saved && saved.projectId === project.id ? store.addFolder(project.id, root, savedApi) : null;
4519
- const entry = kept ?? await store.save({ projectId: project.id, name: project.name, folder: root, token, ...savedApi === void 0 ? {} : { api: savedApi } });
4825
+ const kept = saved && saved.projectId === project.id ? store.addFolder(project.id, saveFolder, savedApi) : null;
4826
+ const entry = kept ?? await store.save({ projectId: project.id, name: project.name, folder: saveFolder, token, ...savedApi === void 0 ? {} : { api: savedApi } });
4520
4827
  const files = plans.flatMap(({ plan }) => plan.contents !== null && (plan.status === "create" || plan.status === "update") ? [{ path: plan.path, contents: plan.contents }] : []);
4521
4828
  try {
4522
4829
  if (files.length > 0) writeFiles(root, files, { force: true, created: false });
@@ -4528,8 +4835,8 @@ async function runConnect(args, io, deps = defaultConnectDeps(process.env)) {
4528
4835
  const backup = "backup" in entry && entry.backup ? [`Your old credentials file could not be read, so it was kept as ${entry.backup}.`] : [];
4529
4836
  say([...backup, savedLine(project.name, entry.where, deps.credentialsPath, kept !== null), ...plans.flatMap(({ id, plan }) => appLines(id, plan)), ...closingLines(apps, changed)]);
4530
4837
  }
4531
- function connectedApps(root, store) {
4532
- const saved = store.byFolder(root);
4838
+ function connectedApps(root, saveFolder, store) {
4839
+ const saved = savedFor(store, root, saveFolder);
4533
4840
  if (saved.length !== 1) return null;
4534
4841
  const { projectId } = saved[0];
4535
4842
  const apps = APPS.filter((a) => {
@@ -4541,8 +4848,8 @@ function connectedApps(root, store) {
4541
4848
  }).map((a) => a.id);
4542
4849
  return apps.length > 0 ? apps : null;
4543
4850
  }
4544
- async function forget(args, root, store, interactive, prompts, file, say) {
4545
- const matches = store.byFolder(root).filter((m) => args.project === void 0 || m.projectId === args.project);
4851
+ async function forget(args, root, saveFolder, store, interactive, prompts, file, say) {
4852
+ const matches = savedFor(store, root, saveFolder).filter((m) => args.project === void 0 || m.projectId === args.project);
4546
4853
  if (matches.length === 0) return say(["No saved token for this folder."]);
4547
4854
  let chosen = matches[0];
4548
4855
  if (matches.length > 1) {
@@ -4556,6 +4863,10 @@ async function forget(args, root, store, interactive, prompts, file, say) {
4556
4863
  const removed = await store.forget(chosen.projectId) ?? chosen;
4557
4864
  say([`Removed the saved token for "${removed.name}" from ${whereFrom(removed.where, file)}.`]);
4558
4865
  }
4866
+ function savedFor(store, root, saveFolder) {
4867
+ const here = store.byFolder(root);
4868
+ return here.length > 0 || saveFolder === root ? here : store.byFolder(saveFolder);
4869
+ }
4559
4870
 
4560
4871
  // src/commands/create.ts
4561
4872
  async function runCreate(args, env, io, store) {
@@ -4582,177 +4893,8 @@ async function runIntegrate(args, env, io, store) {
4582
4893
 
4583
4894
  // src/commands/login.ts
4584
4895
  import { existsSync as existsSync12 } from "node:fs";
4585
- import { join as join10 } from "node:path";
4896
+ import { join as join12 } from "node:path";
4586
4897
  import { homedir as homedir3, hostname } from "node:os";
4587
-
4588
- // src/connect/account-store.ts
4589
- import { createHash as createHash2 } from "node:crypto";
4590
- import { readFileSync as readFileSync11, realpathSync } from "node:fs";
4591
- import { dirname as dirname4, join as join9, parse, resolve as resolve6, sep as sep4 } from "node:path";
4592
- var WHERE2 = ["keychain", "secret-service", "dpapi", "file"];
4593
- var ACCOUNT_TOKEN2 = /^dsa_[A-Za-z0-9_-]{43}$/;
4594
- var PROJECT_ID2 = /^[A-Za-z0-9_-]+$/;
4595
- var LABEL = "account";
4596
- function normaliseOrigin(origin) {
4597
- let url;
4598
- try {
4599
- url = new URL(origin);
4600
- } catch {
4601
- throw new CliError(`Not a server address: ${JSON.stringify(origin)}.`);
4602
- }
4603
- if (url.protocol !== "http:" && url.protocol !== "https:") throw new CliError("A server address must start with http:// or https://.");
4604
- if (url.username || url.password) throw new CliError("A server address must not carry a user name or password.");
4605
- return `${url.origin.toLowerCase()}${url.pathname.replace(/\/+$/, "")}`;
4606
- }
4607
- function accountSecretId(origin) {
4608
- const id = `account-${createHash2("sha256").update(normaliseOrigin(origin)).digest("hex").slice(0, 16)}`;
4609
- assertProjectId(id);
4610
- return id;
4611
- }
4612
- function accountPath(env, platform, home) {
4613
- return join9(dirname4(credentialsPath(env, platform, home)), "account.json");
4614
- }
4615
- function normaliseFolder(folder) {
4616
- let path = resolve6(folder);
4617
- try {
4618
- path = realpathSync(path);
4619
- } catch {
4620
- }
4621
- const root = parse(path).root;
4622
- while (path.length > root.length && (path.endsWith(sep4) || path.endsWith("/"))) path = path.slice(0, -1);
4623
- return path;
4624
- }
4625
- function isRecord3(value) {
4626
- return typeof value === "object" && value !== null && !Array.isArray(value);
4627
- }
4628
- function readAccount(value) {
4629
- if (!isRecord3(value)) return null;
4630
- const { email, where, folders, links, secret } = value;
4631
- if (typeof email !== "string" || !WHERE2.includes(where)) return null;
4632
- if (!Array.isArray(folders) || !folders.every((f) => typeof f === "string")) return null;
4633
- if (!isRecord3(links) || !Object.values(links).every((id) => typeof id === "string" && PROJECT_ID2.test(id))) return null;
4634
- if (secret !== void 0 && typeof secret !== "string") return null;
4635
- const entry = { email, where, folders: [...folders], links: Object.assign(/* @__PURE__ */ Object.create(null), links) };
4636
- if (secret !== void 0) entry.secret = secret;
4637
- return entry;
4638
- }
4639
- function readAccounts(path) {
4640
- const accounts = /* @__PURE__ */ Object.create(null);
4641
- let text;
4642
- try {
4643
- text = readFileSync11(path, "utf8");
4644
- } catch {
4645
- return { version: 1, accounts };
4646
- }
4647
- let parsed;
4648
- try {
4649
- parsed = JSON.parse(text);
4650
- } catch {
4651
- return { version: 1, accounts, unreadable: true };
4652
- }
4653
- if (!isRecord3(parsed) || parsed.version !== 1 || !isRecord3(parsed.accounts)) return { version: 1, accounts, unreadable: true };
4654
- for (const [origin, value] of Object.entries(parsed.accounts)) {
4655
- const entry = readAccount(value);
4656
- if (entry) accounts[origin] = entry;
4657
- }
4658
- return { version: 1, accounts };
4659
- }
4660
- function publicEntry2(origin, e) {
4661
- return { origin, email: e.email, where: e.where, folders: [...e.folders], links: { ...e.links } };
4662
- }
4663
- function createAccountStore(opts) {
4664
- const { env, platform, exec, home } = opts;
4665
- const path = accountPath(env, platform, home);
4666
- const forceFile = env.DESIGNSOURCE_STORE === "file";
4667
- const osBackend = (where) => where === "file" ? null : backendFor(where, exec, home);
4668
- const update = (origin, change) => {
4669
- const key = normaliseOrigin(origin);
4670
- const data = readAccounts(path);
4671
- const entry = Object.hasOwn(data.accounts, key) ? data.accounts[key] : null;
4672
- if (!entry) return null;
4673
- if (change(entry)) writePrivateJson(path, data);
4674
- return publicEntry2(key, entry);
4675
- };
4676
- return {
4677
- all() {
4678
- return Object.entries(readAccounts(path).accounts).map(([origin, e]) => publicEntry2(origin, e));
4679
- },
4680
- get(origin) {
4681
- const key = normaliseOrigin(origin);
4682
- const { accounts } = readAccounts(path);
4683
- return Object.hasOwn(accounts, key) ? publicEntry2(key, accounts[key]) : null;
4684
- },
4685
- async token(origin) {
4686
- const key = normaliseOrigin(origin);
4687
- const { accounts } = readAccounts(path);
4688
- if (!Object.hasOwn(accounts, key)) return null;
4689
- const entry = accounts[key];
4690
- const value = entry.where === "file" ? entry.secret ?? null : await osBackend(entry.where).get(accountSecretId(key), entry.secret);
4691
- return value !== null && ACCOUNT_TOKEN2.test(value) ? value : null;
4692
- },
4693
- async save({ origin, email, token, folder }) {
4694
- const key = normaliseOrigin(origin);
4695
- if (!ACCOUNT_TOKEN2.test(token)) throw new CliError("Unexpected account token from the API.");
4696
- const id = accountSecretId(key);
4697
- const { unreadable, ...data } = readAccounts(path);
4698
- const previous = Object.hasOwn(data.accounts, key) ? data.accounts[key] : void 0;
4699
- const folders = [.../* @__PURE__ */ new Set([...previous?.folders ?? [], normaliseFolder(folder)])];
4700
- const links = Object.assign(/* @__PURE__ */ Object.create(null), previous?.links);
4701
- let entry = { email, where: "file", folders, links, secret: token };
4702
- const backend = forceFile ? null : await chooseBackend({ platform, exec, cwd: home, token });
4703
- if (backend) {
4704
- const kept = await backend.put(id, LABEL, token);
4705
- if (kept) entry = { email, where: backend.where, folders, links, ...kept.secret === void 0 ? {} : { secret: kept.secret } };
4706
- }
4707
- data.accounts[key] = entry;
4708
- const backup = unreadable ? backUp(path) : void 0;
4709
- writePrivateJson(path, data);
4710
- if (previous && previous.where !== entry.where) await osBackend(previous.where)?.remove(id);
4711
- return { ...publicEntry2(key, entry), ...backup === void 0 ? {} : { backup } };
4712
- },
4713
- trust(origin, folder) {
4714
- const target = normaliseFolder(folder);
4715
- return update(origin, (entry) => {
4716
- if (entry.folders.includes(target)) return false;
4717
- entry.folders = [...entry.folders, target];
4718
- return true;
4719
- });
4720
- },
4721
- link(origin, folder, projectId) {
4722
- assertProjectId(projectId);
4723
- const target = normaliseFolder(folder);
4724
- return update(origin, (entry) => {
4725
- if (entry.links[target] === projectId) return false;
4726
- entry.links[target] = projectId;
4727
- return true;
4728
- });
4729
- },
4730
- async forget(origin) {
4731
- const key = normaliseOrigin(origin);
4732
- const data = readAccounts(path);
4733
- if (!Object.hasOwn(data.accounts, key)) return null;
4734
- const entry = data.accounts[key];
4735
- try {
4736
- await osBackend(entry.where)?.remove(accountSecretId(key));
4737
- } catch {
4738
- }
4739
- delete data.accounts[key];
4740
- writePrivateJson(path, data);
4741
- return publicEntry2(key, entry);
4742
- }
4743
- };
4744
- }
4745
-
4746
- // src/connect/account-paths.ts
4747
- function originOf(api) {
4748
- normaliseOrigin(api);
4749
- return new URL(api).origin;
4750
- }
4751
- function trustedRootFor(cwd) {
4752
- return normaliseFolder(projectRoot(normaliseFolder(cwd)));
4753
- }
4754
-
4755
- // src/commands/login.ts
4756
4898
  function defaultLoginDeps(env) {
4757
4899
  const home = homedir3();
4758
4900
  const platform = process.platform;
@@ -4766,7 +4908,7 @@ function defaultLoginDeps(env) {
4766
4908
  platform
4767
4909
  };
4768
4910
  }
4769
- var sleepFor = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
4911
+ var sleepFor = (ms) => new Promise((resolve10) => setTimeout(resolve10, ms));
4770
4912
  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.`;
4771
4913
  var ACCOUNT_SCOPES_NEEDED = ["projects:create", "projects:read", "screens:create"];
4772
4914
  var REVOKE_FAILED = "Could not reach the server to revoke this sign-in; revoke it on your profile page.";
@@ -4776,7 +4918,7 @@ function loginApi(args, terminal) {
4776
4918
  throw new CliError(UNTRUSTED_LOGIN_SERVER(api));
4777
4919
  }
4778
4920
  var NOT_A_PROJECT = "Run npx designsource login inside a project folder (one with a .git folder or a package.json).";
4779
- var isProjectFolder = (root) => existsSync12(join10(root, ".git")) || existsSync12(join10(root, "package.json"));
4921
+ var isProjectFolder = (root) => existsSync12(join12(root, ".git")) || existsSync12(join12(root, "package.json"));
4780
4922
  function savedLine2(where, file) {
4781
4923
  if (where === "keychain") return "Saved the sign-in in the macOS keychain \u2713";
4782
4924
  if (where === "secret-service") return "Saved the sign-in in the system keyring \u2713";
@@ -4793,7 +4935,7 @@ function closingLines2(apps, changed, usesAccount) {
4793
4935
  ...apps.includes("codex") ? [CODEX_TRUST_NOTE] : [],
4794
4936
  ...apps.includes("gemini") ? [GEMINI_TRUST_NOTE] : [],
4795
4937
  ...usesAccount ? ["Then ask your agent to create a design system for this app."] : [],
4796
- "These files hold no token and are safe to commit."
4938
+ COMMIT_SETTINGS_NOTE
4797
4939
  ];
4798
4940
  }
4799
4941
  var plansFor = (root, apps) => apps.map((id) => ({ id, plan: planAppFile(root, id, null) }));
@@ -4802,8 +4944,9 @@ async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
4802
4944
  const { accounts, terminal } = deps;
4803
4945
  const say = (lines) => io.stdout(lines.map((l) => `${l}
4804
4946
  `).join(""));
4805
- const root = trustedRootFor(io.cwd);
4806
- const refusal = homeFolderRefusal(root, normaliseFolder(deps.home));
4947
+ const { work: root, trust, worktree } = projectFolders(io.cwd);
4948
+ const homeDir = normaliseFolder(deps.home);
4949
+ const refusal = homeFolderRefusal(root, homeDir) ?? homeFolderRefusal(trust, homeDir);
4807
4950
  if (refusal) throw new CliError(refusal);
4808
4951
  if (!isProjectFolder(root)) throw new CliError(NOT_A_PROJECT);
4809
4952
  const api = loginApi(args, terminal);
@@ -4820,7 +4963,7 @@ async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
4820
4963
  }
4821
4964
  }
4822
4965
  plansFor(root, apps);
4823
- say([`Signing in for ${root}`]);
4966
+ say([`Signing in for ${trust}`, ...worktree ? [WORKTREE_NOTE(trust)] : []]);
4824
4967
  const head = [];
4825
4968
  let email = null;
4826
4969
  const saved = accounts.get(api);
@@ -4829,9 +4972,9 @@ async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
4829
4972
  const check = await requestJson({ api, path: "/api/agent/projects", method: "GET", token: savedToken2 }, io.fetchImpl);
4830
4973
  const stale = check.status === 200 && await lacksScope(api, savedToken2, io.fetchImpl);
4831
4974
  if (check.status === 200 && !stale) {
4832
- accounts.trust(api, root);
4975
+ accounts.trust(api, trust);
4833
4976
  email = printable(saved.email);
4834
- head.push(`Already signed in on this computer; your agent may now use it from ${root}.`);
4977
+ head.push(`Already signed in on this computer; your agent may now use it from ${trust}.`);
4835
4978
  } else if (check.status !== 200 && check.status !== 401 && check.status !== 403) {
4836
4979
  throw new CliError(messageForResponse(check.status, check.body, api));
4837
4980
  }
@@ -4848,7 +4991,7 @@ async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
4848
4991
  show: (line) => say([line]),
4849
4992
  open
4850
4993
  });
4851
- const entry = await accounts.save({ origin: api, email: signedIn.email, token: signedIn.token, folder: root });
4994
+ const entry = await accounts.save({ origin: api, email: signedIn.email, token: signedIn.token, folder: trust });
4852
4995
  email = signedIn.email;
4853
4996
  if (savedToken2 && savedToken2 !== signedIn.token) await revoke(api, savedToken2, io.fetchImpl);
4854
4997
  if (entry.backup) head.push(`Your old account file could not be read, so it was kept as ${entry.backup}.`);
@@ -4919,18 +5062,25 @@ async function runLogout(args, io, deps = defaultLoginDeps(process.env)) {
4919
5062
  }
4920
5063
 
4921
5064
  // src/mcp/server.ts
4922
- import { homedir as homedir4 } from "node:os";
5065
+ import { homedir as homedir5 } from "node:os";
4923
5066
 
4924
5067
  // src/version.ts
4925
- var VERSION = true ? "0.11.0" : "0.0.0-dev";
5068
+ var VERSION = true ? "0.13.0" : "0.0.0-dev";
4926
5069
 
4927
5070
  // src/mcp/account-session.ts
4928
- 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.`;
5071
+ var NOT_SIGNED_IN_FOR = (root) => `designsource is not signed in for ${printable(root)}. Ask the user to run npx designsource login in a terminal in that folder, then restart this app. A sign-in there also covers its git worktrees.`;
4929
5072
  var SEVERAL_ACCOUNTS = "More than one designsource account is signed in on this computer; pass --api.";
4930
- var NO_LINK = "No design system is linked to this folder yet. Call create_design_system or use_design_system.";
5073
+ var NO_LINK = "No design system is linked to this folder yet. Call list_design_systems, then use_design_system with one of its ids, or call create_design_system to make a new one.";
4931
5074
  var ACCOUNT_TOKEN3 = /^dsa_[A-Za-z0-9_-]{43}$/;
4932
5075
  var PROJECT_ID3 = /^[A-Za-z0-9_-]+$/;
4933
5076
  var refuse = (message) => ({ kind: "none", message });
5077
+ function trustedFolderOf(entry, roots) {
5078
+ const trusted = (f) => entry.folders.some((saved) => normaliseFolder(saved) === f);
5079
+ const folder = trusted(roots.work) ? roots.work : trusted(roots.trust) ? roots.trust : null;
5080
+ if (folder === null) return null;
5081
+ const linked = Object.entries(entry.links).find(([f]) => normaliseFolder(f) === folder)?.[1];
5082
+ return { folder, projectId: linked !== void 0 && PROJECT_ID3.test(linked) ? linked : null };
5083
+ }
4934
5084
  function chooseAccount(api, apiGiven, accounts, notSignedIn) {
4935
5085
  if (apiGiven) {
4936
5086
  let origin;
@@ -4949,14 +5099,15 @@ function chooseAccount(api, apiGiven, accounts, notSignedIn) {
4949
5099
  }
4950
5100
  async function resolveAccount(input) {
4951
5101
  const { api, apiGiven, cwd, home, accounts } = input;
4952
- const folder = trustedRootFor(cwd);
4953
- const notSignedIn = NOT_SIGNED_IN_FOR(folder);
5102
+ const { work, trust } = projectFolders(cwd);
5103
+ const notSignedIn = NOT_SIGNED_IN_FOR(trust);
4954
5104
  const chosen = chooseAccount(api, apiGiven, accounts, notSignedIn);
4955
5105
  if ("kind" in chosen) return chosen;
4956
- if (homeFolderRefusal(folder, normaliseFolder(home)) !== null) return refuse(notSignedIn);
4957
- if (!chosen.folders.some((f) => normaliseFolder(f) === folder)) return refuse(notSignedIn);
4958
- const linked = Object.entries(chosen.links).find(([f]) => normaliseFolder(f) === folder)?.[1];
4959
- const projectId = linked !== void 0 && PROJECT_ID3.test(linked) ? linked : null;
5106
+ const homeDir = normaliseFolder(home);
5107
+ if (homeFolderRefusal(trust, homeDir) !== null || homeFolderRefusal(work, homeDir) !== null) return refuse(notSignedIn);
5108
+ const found = trustedFolderOf(chosen, { work, trust });
5109
+ if (found === null) return refuse(notSignedIn);
5110
+ const { folder, projectId } = found;
4960
5111
  let token;
4961
5112
  try {
4962
5113
  token = await accounts.token(chosen.origin);
@@ -4964,7 +5115,7 @@ async function resolveAccount(input) {
4964
5115
  return refuse(notSignedIn);
4965
5116
  }
4966
5117
  if (token === null || !ACCOUNT_TOKEN3.test(token)) return refuse(notSignedIn);
4967
- return { kind: "account", origin: chosen.origin, email: chosen.email, token, folder, projectId };
5118
+ return { kind: "account", origin: chosen.origin, email: chosen.email, token, folder, workFolder: work, projectId };
4968
5119
  }
4969
5120
 
4970
5121
  // src/mcp/jsonrpc.ts
@@ -5037,6 +5188,11 @@ function getPrompt(name) {
5037
5188
  return { description: "Integrate the design system into the current repository.", messages: [{ role: "user", content: { type: "text", text: INTEGRATE_TEXT } }] };
5038
5189
  }
5039
5190
 
5191
+ // src/mcp/tools.ts
5192
+ import { existsSync as existsSync14 } from "node:fs";
5193
+ import { homedir as homedir4 } from "node:os";
5194
+ import { join as join15 } from "node:path";
5195
+
5040
5196
  // src/mcp/account-tools.ts
5041
5197
  import { randomUUID } from "node:crypto";
5042
5198
 
@@ -5298,25 +5454,129 @@ var ACCOUNT_TOOLS = [
5298
5454
  ];
5299
5455
 
5300
5456
  // src/mcp/project-folder.ts
5301
- import { isAbsolute as isAbsolute4, relative as relative4, resolve as resolve7, sep as sep5 } from "node:path";
5457
+ import { isAbsolute as isAbsolute5, join as join13, relative as relative5, resolve as resolve8, sep as sep5 } from "node:path";
5302
5458
  var NOT_SURE_WHICH_FOLDER = "Not sure which project folder to change: run npx designsource connect in it first.";
5303
5459
  function isWithin2(folder, root) {
5304
- const rel = relative4(root, folder);
5305
- return rel === "" || rel !== ".." && !rel.startsWith(`..${sep5}`) && !isAbsolute4(rel);
5460
+ const rel = relative5(root, folder);
5461
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep5}`) && !isAbsolute5(rel);
5306
5462
  }
5307
- function resolveProjectFolder(cwd, entry) {
5463
+ function resolveProjectFolder(cwd, entry, worktree = worktreeOf(cwd)) {
5308
5464
  if (!entry) return cwd;
5309
- const here = resolve7(cwd);
5310
- const holding = entry.folders.map((f) => resolve7(f)).filter((f) => isWithin2(here, f)).sort((a, b) => b.length - a.length);
5465
+ const here = resolve8(cwd);
5466
+ const saved = entry.folders.map((f) => resolve8(f));
5467
+ const mapped = worktree ? saved.map((f) => normaliseFolder(f)).filter((f) => isWithin2(f, worktree.main)).map((f) => join13(worktree.work, relative5(worktree.main, f))) : [];
5468
+ const realHere = worktree ? normaliseFolder(cwd) : here;
5469
+ const holding = [...mapped.filter((f) => isWithin2(realHere, f)), ...saved.filter((f) => isWithin2(here, f))].sort((a, b) => b.length - a.length);
5311
5470
  if (holding[0]) return holding[0];
5312
- return entry.folders.length === 1 ? resolve7(entry.folders[0]) : null;
5471
+ return entry.folders.length === 1 ? resolve8(entry.folders[0]) : null;
5472
+ }
5473
+ function worktreeOf(cwd) {
5474
+ const { work, trust, worktree } = projectFolders(cwd);
5475
+ return worktree ? { work, main: trust } : null;
5476
+ }
5477
+
5478
+ // src/mcp/target-folder.ts
5479
+ import { existsSync as existsSync13, readdirSync as readdirSync5, realpathSync as realpathSync4, statSync as statSync4 } from "node:fs";
5480
+ import { dirname as dirname6, isAbsolute as isAbsolute6, join as join14, relative as relative6, resolve as resolve9, sep as sep6 } from "node:path";
5481
+ var FOLDER_ARG_MAX = 1024;
5482
+ var CANDIDATES_MAX = 8;
5483
+ var SCAN_DIRS_MAX = 200;
5484
+ var FOLDER_ARG = '"folder" must be a path to a folder (relative to the project, or absolute).';
5485
+ var FOLDER_NOT_FOUND = (folder) => `No folder at ${printable(folder)}. Pass the path of the app's folder (the one with its package.json).`;
5486
+ var FOLDER_NOT_SIGNED_IN = (root, work) => `designsource is not signed in for ${printable(root)}. Ask the user to run npx designsource login in a terminal in that folder, then call add_ui_kit again; or pass a folder inside ${printable(work)}.`;
5487
+ var FOLDER_NOT_CONNECTED = (root, work) => `${printable(root)} is not connected to this design system. Ask the user to run npx designsource connect in a terminal in that folder, then call add_ui_kit again; or pass a folder inside ${printable(work)}.`;
5488
+ var FOLDER_OUTSIDE = (folder, work) => `${printable(folder)} is outside ${printable(work)}. This app runs designsource with a project token for that folder only; pass a folder inside it, or ask the user to run npx designsource connect in a terminal in the app's folder and restart this app.`;
5489
+ var FOLDER_HOME = (root) => `${printable(root)} is the home folder or a system folder; designsource never writes there. Pass the app's own folder.`;
5490
+ var NO_APP_HERE = (root, candidates, signInFirst = []) => [
5491
+ `No package.json in ${printable(root)}, so there is no app here to add the UI kit to. Call add_ui_kit again with folder set to the app's folder.`,
5492
+ ...candidates.length > 0 ? [`Folders with an app you may pass: ${candidates.map(printable).join(", ")}.`] : [],
5493
+ ...signInFirst.length > 0 ? [`Apps that are repositories of their own, which the user must first run npx designsource login in (in a terminal, then restart this app): ${signInFirst.map(printable).join(", ")}.`] : ["A folder in another repository works only once the user has run npx designsource login in a terminal there."]
5494
+ ].join(" ");
5495
+ function within3(folder, root) {
5496
+ const rel = relative6(root, folder);
5497
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep6}`) && !isAbsolute6(rel);
5498
+ }
5499
+ function crossesRepository(target, base) {
5500
+ for (let dir = target; dir !== base && within3(dir, base); dir = dirname6(dir)) {
5501
+ if (existsSync13(join14(dir, ".git"))) return true;
5502
+ }
5503
+ return false;
5504
+ }
5505
+ function resolveTarget(arg, src) {
5506
+ if (typeof arg !== "string" || arg.trim() === "" || arg.length > FOLDER_ARG_MAX || /[\u0000-\u001f\u007f]/.test(arg)) return { ok: false, message: FOLDER_ARG };
5507
+ if (!isAbsolute6(arg) && src.base === null) return { ok: false, message: FOLDER_ARG };
5508
+ const asked = isAbsolute6(arg) ? resolve9(arg) : resolve9(src.base, arg);
5509
+ let real2;
5510
+ try {
5511
+ real2 = realpathSync4(asked);
5512
+ if (!statSync4(real2).isDirectory()) return { ok: false, message: FOLDER_NOT_FOUND(asked) };
5513
+ } catch {
5514
+ return { ok: false, message: FOLDER_NOT_FOUND(asked) };
5515
+ }
5516
+ const roots = projectFolders(real2);
5517
+ if (relative6(roots.work, real2).split(sep6).some((part) => part === ".git" || part === "node_modules")) return { ok: false, message: FOLDER_ARG };
5518
+ const home = normaliseFolder(src.home);
5519
+ if (homeFolderRefusal(real2, home) !== null) return { ok: false, message: FOLDER_HOME(real2) };
5520
+ if (src.base !== null && within3(real2, src.base) && !crossesRepository(real2, src.base)) return { ok: true, folder: real2, via: "inside" };
5521
+ if (homeFolderRefusal(roots.work, home) !== null || homeFolderRefusal(roots.trust, home) !== null) return { ok: false, message: FOLDER_HOME(roots.work) };
5522
+ const work = src.base ?? real2;
5523
+ const found = trustFor(src, roots);
5524
+ if (found) return { ok: true, folder: real2, via: "trusted", root: found.folder, projectId: found.projectId };
5525
+ if (src.accountTrust) return { ok: false, message: FOLDER_NOT_SIGNED_IN(roots.trust, work) };
5526
+ return { ok: false, message: src.savedFolders ? FOLDER_NOT_CONNECTED(roots.trust, work) : FOLDER_OUTSIDE(real2, work) };
5527
+ }
5528
+ function trustFor(src, roots) {
5529
+ if (src.accountTrust) return src.accountTrust(roots);
5530
+ const saved = (src.savedFolders ?? []).map((f) => normaliseFolder(f));
5531
+ const folder = [roots.work, roots.trust].find((r) => saved.includes(r));
5532
+ return folder === void 0 ? null : { folder, projectId: null };
5533
+ }
5534
+ var hasApp = (dir) => {
5535
+ try {
5536
+ return statSync4(join14(dir, "package.json")).isFile();
5537
+ } catch {
5538
+ return false;
5539
+ }
5540
+ };
5541
+ function appCandidates(base, near, src, trusted = []) {
5542
+ const apps = [];
5543
+ const signInFirst = [];
5544
+ const children = (dir) => {
5545
+ try {
5546
+ return readdirSync5(dir, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.name.startsWith(".") && d.name !== "node_modules").map((d) => join14(dir, d.name)).sort();
5547
+ } catch {
5548
+ return [];
5549
+ }
5550
+ };
5551
+ let read = 0;
5552
+ const visit = (dir, depth, inBase) => {
5553
+ if (read >= SCAN_DIRS_MAX || apps.length >= CANDIDATES_MAX && signInFirst.length >= CANDIDATES_MAX) return;
5554
+ read++;
5555
+ const ownRepo = existsSync13(join14(dir, ".git"));
5556
+ if (hasApp(dir)) {
5557
+ const real2 = normaliseFolder(dir);
5558
+ if (ownRepo) {
5559
+ const list = trustFor(src, projectFolders(real2)) ? apps : signInFirst;
5560
+ if (!list.includes(real2) && list.length < CANDIDATES_MAX) list.push(real2);
5561
+ } else if (inBase && !apps.includes(real2) && apps.length < CANDIDATES_MAX) apps.push(real2);
5562
+ if (ownRepo || inBase) return;
5563
+ }
5564
+ if (depth < 2 && !ownRepo) for (const child of children(dir)) visit(child, depth + 1, inBase);
5565
+ };
5566
+ for (const child of children(base)) visit(child, 1, true);
5567
+ if (near !== base) for (const child of children(near)) visit(child, 1, false);
5568
+ for (const f of [...trusted].map((t) => normaliseFolder(t)).sort()) {
5569
+ if (apps.length >= CANDIDATES_MAX) break;
5570
+ if (f !== base && !apps.includes(f) && dirname6(f) === dirname6(near) && hasApp(f)) apps.push(f);
5571
+ }
5572
+ return { apps, signInFirst };
5313
5573
  }
5314
5574
 
5315
5575
  // src/mcp/tools.ts
5316
5576
  var accountProjectPath = (projectId, kind) => `/api/agent/projects/${encodeURIComponent(projectId)}/${kind}`;
5317
5577
  var READ_ONLY = { readOnlyHint: true };
5318
5578
  var TIERS = ["design", "semantic", "component"];
5319
- var CATEGORIES = ["color", "spacing", "radius", "typography", "shadow", "zIndex", "border"];
5579
+ var CATEGORIES = ["color", "spacing", "radius", "typography", "shadow", "zIndex", "border", "gradient"];
5320
5580
  var NO_INPUT = { type: "object", properties: {}, additionalProperties: false };
5321
5581
  var pretty = (v) => JSON.stringify(v, null, 2);
5322
5582
  var NO_BLOCKS = "This server sent no blocks. Update designsource and the server.";
@@ -5341,10 +5601,11 @@ function optionalEnum(args, key, allowed) {
5341
5601
  var MCP_EXEC_TIMEOUT_MS = 10 * 60 * 1e3;
5342
5602
  var UNKNOWN_FOR_AGENT = (names) => `Unknown component(s): ${names.join(", ")}. Call list_components for the names.`;
5343
5603
  var FOREIGN_FILES = (paths) => `These files exist and were not added by designsource: ${paths.join(", ")}. Ask the user whether to replace them, then call add_ui_kit again with replace_existing: true.`;
5344
- function kitAccess(ctx) {
5604
+ function kitAccess(ctx, linkedTo) {
5345
5605
  if (ctx.token !== null) return { token: ctx.token, api: ctx.api };
5346
5606
  if (!ctx.account) return errorResult(ctx.missingToken ?? MCP_TOKEN_REQUIRED);
5347
- const { token, api, projectId } = ctx.account;
5607
+ const { token, api } = ctx.account;
5608
+ const projectId = linkedTo ?? ctx.account.projectId;
5348
5609
  if (projectId === null) return errorResult(NO_LINK);
5349
5610
  return { token, api, kitPath: accountProjectPath(projectId, "kit"), messages: accountMessageForResponse };
5350
5611
  }
@@ -5409,6 +5670,14 @@ function screensArg(v) {
5409
5670
  if (!names.every(isScreenName2)) return { ok: false };
5410
5671
  return { ok: true, value: names.length > 0 ? [...new Set(names)] : void 0, site };
5411
5672
  }
5673
+ function targetSources(ctx, base) {
5674
+ return {
5675
+ base,
5676
+ home: ctx.home ?? homedir4(),
5677
+ ...ctx.token === null && ctx.account ? { accountTrust: (roots) => ctx.account.trustOf?.(roots) ?? null } : {},
5678
+ ...ctx.token !== null ? { savedFolders: ctx.projectFolders } : {}
5679
+ };
5680
+ }
5412
5681
  async function addUiKit(args, ctx) {
5413
5682
  const { components, replace_existing: replace, no_blocks: noBlocks } = args;
5414
5683
  if (components !== void 0 && !(Array.isArray(components) && components.every((c) => typeof c === "string"))) {
@@ -5418,10 +5687,33 @@ async function addUiKit(args, ctx) {
5418
5687
  if (noBlocks !== void 0 && typeof noBlocks !== "boolean") return errorResult('"no_blocks" must be true or false.');
5419
5688
  const screens = screensArg(args.screens);
5420
5689
  if (!screens.ok) return errorResult(SCREENS_ARG);
5421
- const access = kitAccess(ctx);
5690
+ if (ctx.token === null && !ctx.account) return errorResult(ctx.missingToken ?? MCP_TOKEN_REQUIRED);
5691
+ const fallback = ctx.token !== null ? resolveProjectFolder(ctx.cwd, ctx.projectFolders === null ? null : { folders: ctx.projectFolders }) : ctx.account.workFolder;
5692
+ const base = fallback === null ? null : normaliseFolder(fallback);
5693
+ let root;
5694
+ let linkedTo;
5695
+ let usedLine = [];
5696
+ if (args.folder !== void 0) {
5697
+ const target = resolveTarget(args.folder, targetSources(ctx, base));
5698
+ if (!target.ok) return errorResult(target.message);
5699
+ root = target.folder;
5700
+ if (target.via === "trusted" && ctx.token === null) {
5701
+ linkedTo = target.projectId;
5702
+ usedLine = [target.projectId !== null ? `Using the design system linked to ${printable(target.root)}.` : `Using this session's design system (${printable(target.root)} has none linked).`];
5703
+ }
5704
+ } else {
5705
+ if (base === null) return errorResult(NOT_SURE_WHICH_FOLDER);
5706
+ root = base;
5707
+ const own = kitAccess(ctx);
5708
+ if (isResult2(own)) return own;
5709
+ if (!existsSync14(join15(root, "package.json"))) {
5710
+ const near = ctx.account?.folder ?? root;
5711
+ const found = appCandidates(root, near, targetSources(ctx, base), ctx.account?.trustedFolders?.() ?? []);
5712
+ return errorResult(NO_APP_HERE(root, found.apps, found.signInFirst));
5713
+ }
5714
+ }
5715
+ const access = kitAccess(ctx, linkedTo);
5422
5716
  if (isResult2(access)) return access;
5423
- const root = ctx.token !== null ? resolveProjectFolder(ctx.cwd, ctx.projectFolders === null ? null : { folders: ctx.projectFolders }) : ctx.account.folder;
5424
- if (root === null) return errorResult(NOT_SURE_WHICH_FOLDER);
5425
5717
  const questions = {
5426
5718
  pickComponents: async (all) => all,
5427
5719
  confirmReplace: async (paths) => {
@@ -5450,6 +5742,7 @@ async function addUiKit(args, ctx) {
5450
5742
  const written = result.added.filter((n) => n !== "preview-portal");
5451
5743
  return textResult(
5452
5744
  [
5745
+ ...usedLine,
5453
5746
  ...progress,
5454
5747
  ...summaryLines(result, "agent"),
5455
5748
  ...written.length > 0 ? [`Added: ${written.join(", ")}`] : [],
@@ -5598,14 +5891,15 @@ ${files.join("\n\n")}`);
5598
5891
  },
5599
5892
  {
5600
5893
  name: "add_ui_kit",
5601
- description: `Add this design system's UI kit to the React app in the current folder: the theme, the components and their libraries. Sets up Tailwind and shadcn when the app lacks them. A full run (no components and no screens named) also writes the /design-system section, every component, block and sample page in the project's theme, with its blocks unless no_blocks is true, and refreshes the screens an earlier run wrote. screens (names from list_screens, or ["all"]) writes those app screens and marketing pages with the parts and components they import; you mount each on a route. Add "site" to screens to write the site menu (header and footer) that pages mount inside, at least one page being pulled with it. Changes files in the project, so your client will ask the user first. Never overwrites components or screens the user edited.`,
5894
+ description: `Add this design system's UI kit to the React app in the current folder: the theme, the components and their libraries. Sets up Tailwind and shadcn when the app lacks them. A full run (no components and no screens named) also writes the /design-system section, every component, block and sample page in the project's theme, with its blocks unless no_blocks is true, and refreshes the screens an earlier run wrote. screens (names from list_screens, or ["all"]) writes those app screens and marketing pages with the parts and components they import; you mount each on a route. Add "site" to screens to write the site menu (header and footer) that pages mount inside, at least one page being pulled with it. When the app is not in the current folder (a monorepo, or a workspace holding the app as a repository of its own), pass folder; a repository of its own works once the user has run npx designsource login in it, and its linked design system is used. Changes files in the project, so your client will ask the user first. Never overwrites components or screens the user edited.`,
5602
5895
  inputSchema: {
5603
5896
  type: "object",
5604
5897
  properties: {
5605
5898
  components: { type: "array", items: { type: "string" }, description: "Component names such as button or dialog. Omit to add everything (or refresh what was added before)." },
5606
5899
  replace_existing: { type: "boolean", description: "Replace component files that exist but were not added by designsource. Ask the user first." },
5607
5900
  no_blocks: { type: "boolean", description: "Add the /design-system section without its blocks and their libraries. Blocks an earlier run wrote are left in place." },
5608
- screens: { type: "array", items: { type: "string" }, description: `Screen names from list_screens, or ["all"] for every screen; "site" adds the site menu for marketing pages. Each is written under the components folder's screens/ with the parts and kit components it imports.` }
5901
+ screens: { type: "array", items: { type: "string" }, description: `Screen names from list_screens, or ["all"] for every screen; "site" adds the site menu for marketing pages. Each is written under the components folder's screens/ with the parts and kit components it imports.` },
5902
+ folder: { type: "string", description: "The app's folder when it is not the current one: a path inside this project (a monorepo's apps/web), or a repository of its own the user ran npx designsource login in. Omit for the current folder." }
5609
5903
  },
5610
5904
  additionalProperties: false
5611
5905
  },
@@ -5773,6 +6067,7 @@ function toolAccountFor(session, accounts, onLink, onGone = () => {
5773
6067
  token: session.token,
5774
6068
  email: session.email,
5775
6069
  folder: session.folder,
6070
+ workFolder: session.workFolder,
5776
6071
  projectId: session.projectId,
5777
6072
  link(projectId) {
5778
6073
  if (accounts.link(session.origin, session.folder, projectId) === null) {
@@ -5782,12 +6077,20 @@ function toolAccountFor(session, accounts, onLink, onGone = () => {
5782
6077
  account.projectId = projectId;
5783
6078
  onLink();
5784
6079
  return true;
6080
+ },
6081
+ trustOf(roots) {
6082
+ const entry = accounts.get(session.origin);
6083
+ return entry ? trustedFolderOf(entry, roots) : null;
6084
+ },
6085
+ trustedFolders() {
6086
+ return accounts.get(session.origin)?.folders ?? [];
5785
6087
  }
5786
6088
  };
5787
6089
  return account;
5788
6090
  }
5789
6091
  async function runMcp(args, io, streams = { input: process.stdin, output: process.stdout }, deps = {}) {
5790
6092
  const cwd = deps.cwd ?? process.cwd();
6093
+ const home = deps.home ?? homedir5();
5791
6094
  const store = deps.store ?? defaultStore();
5792
6095
  const warn = (line) => io.stderr(`${line}
5793
6096
  `);
@@ -5799,30 +6102,30 @@ async function runMcp(args, io, streams = { input: process.stdin, output: proces
5799
6102
  else if (found.entry === null && args.project) found = { ...found, entry: store.entry(args.project) };
5800
6103
  if (found) {
5801
6104
  const api = fromStore ? apiFor(args, found.entry) : givenTokenApi(args, found.entry);
5802
- return { token: found.token, projectFolders: args.project ? found.entry?.folders ?? [] : null, api, cwd, account: null, fetchImpl: io.fetchImpl, exec: spawnExec };
6105
+ return { token: found.token, projectFolders: args.project ? found.entry?.folders ?? [] : null, api, cwd, account: null, fetchImpl: io.fetchImpl, exec: spawnExec, home };
5803
6106
  }
5804
6107
  const missingToken = args.project ? NO_TOKEN_FOR_PROJECT(store.entry(args.project)?.name ?? args.project) : MCP_TOKEN_REQUIRED;
5805
- return { token: null, missingToken, projectFolders: args.project ? [] : null, api: args.api, cwd, account: null, fetchImpl: io.fetchImpl, exec: spawnExec };
6108
+ return { token: null, missingToken, projectFolders: args.project ? [] : null, api: args.api, cwd, account: null, fetchImpl: io.fetchImpl, exec: spawnExec, home };
5806
6109
  };
5807
6110
  let accounts = null;
5808
6111
  let account = null;
5809
6112
  const accountSession = async () => {
5810
6113
  if (!account) {
5811
- accounts ??= (deps.accounts ?? (() => createAccountStore({ env: process.env, platform: process.platform, exec: spawnExec, home: homedir4() })))();
5812
- const resolved = await resolveAccount({ api: args.api, apiGiven: args.apiGiven === true, cwd, home: deps.home ?? homedir4(), accounts });
6114
+ accounts ??= (deps.accounts ?? (() => createAccountStore({ env: process.env, platform: process.platform, exec: spawnExec, home: homedir5() })))();
6115
+ const resolved = await resolveAccount({ api: args.api, apiGiven: args.apiGiven === true, cwd, home, accounts });
5813
6116
  if (resolved.kind === "none") {
5814
6117
  return {
5815
6118
  token: null,
5816
- missingToken: `${MCP_TOKEN_REQUIRED}
5817
-
5818
- ${resolved.message}`,
6119
+ // The account path's own sentence: it names the folder and the one command (`login`).
6120
+ missingToken: resolved.message,
5819
6121
  accountRefusal: resolved.message,
5820
6122
  projectFolders: null,
5821
6123
  api: args.api,
5822
6124
  cwd,
5823
6125
  account: null,
5824
6126
  fetchImpl: io.fetchImpl,
5825
- exec: spawnExec
6127
+ exec: spawnExec,
6128
+ home
5826
6129
  };
5827
6130
  }
5828
6131
  const made = toolAccountFor(resolved, accounts, () => cache.clear(), () => {
@@ -5841,7 +6144,7 @@ ${resolved.message}`,
5841
6144
  }
5842
6145
  return res;
5843
6146
  });
5844
- return { token: null, projectFolders: null, api: current.api, cwd, account: current, fetchImpl, exec: spawnExec, dropSnapshot: () => cache.clear() };
6147
+ return { token: null, projectFolders: null, api: current.api, cwd, account: current, fetchImpl, exec: spawnExec, home, dropSnapshot: () => cache.clear() };
5845
6148
  };
5846
6149
  const session = () => projectPath ? projectSession() : accountSession();
5847
6150
  const cache = createSnapshotCache(async () => {