designsource 0.11.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +1 -0
  2. package/dist/index.js +445 -292
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -11,6 +11,7 @@ The command line for a [DS source](https://designsource.app) design system. Node
11
11
  - **[`connect`](https://designsource.app/docs/cli/connect)** — connect your coding apps (Claude Code, Cursor, VS Code, Codex, Gemini CLI) to the design system: the project token saved once, privately, on this computer, and each app's MCP settings written in the project with no token in them.
12
12
  - **[`login`](https://designsource.app/docs/cli/login-and-logout)** / **`logout`** — sign this computer in to your account for coding agents, so your agent can create a design system for the app it is working on and add its UI kit.
13
13
  - **Pages** — the marketing pages you made (home, pricing, waitlist) come with `add --screen` too, and `create` puts them on their own routes with the home page at `/`. The CLI always asks the server for them.
14
+ - **Links between screens** — a screen's button, table row or empty-state action can open another screen; the `/design-system` section, the app shell and `create` route them.
14
15
  - **[`create`](https://designsource.app/docs/cli/create-and-integrate)** — a new Next.js project from it: tokens, every component, a front page, the design system under `/design-system` and your screens on `/app/<name>` in a sidebar shell (`--no-screens` leaves them out).
15
16
  - **[`integrate`](https://designsource.app/docs/cli/create-and-integrate)** — a `design-system/` folder for Vue, Svelte, Angular or plain CSS: your tokens as CSS variables, a prompt for your coding agent, the component kit as reference.
16
17
  - **[`mcp`](https://designsource.app/docs/cli/mcp)** — serve the design system to your coding agent over MCP: tokens, component source, blocks, your mockup page, an integration guide, and tools that add the UI kit (and your screens, with `screens`), list and read screens (`list_screens`, `get_screen_source`), create a design system, or, signed in with `login`, make a screen (`generate_screen`, which spends credits or your key and writes no files). `connect` and `login` write its config for you.
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 relative6 = posix.normalize(posix.join(tsconfig.baseUrl, best.resolved));
123
+ if (relative6 === ".." || relative6.startsWith("../") || posix.isAbsolute(relative6)) throw outside(alias);
124
+ return relative6 === "." ? "" : relative6;
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((resolve9) => {
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
+ resolve9({ 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
+ resolve9(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((resolve9) => {
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", () => resolve9(false));
2504
2547
  child.once("spawn", () => {
2505
2548
  child.unref();
2506
- resolve8(true);
2549
+ resolve9(true);
2507
2550
  });
2508
2551
  } catch {
2509
- resolve8(false);
2552
+ resolve9(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((resolve9, reject) => waiting.push({
3787
3846
  resolve: (line2) => {
3788
3847
  process.stdin.unref?.();
3789
- resolve8(line2);
3848
+ resolve9(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((resolve9, 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
+ resolve9(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((resolve9, 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
+ resolve9(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((resolve9) => setTimeout(resolve9, 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}.`);
@@ -4922,12 +5065,12 @@ async function runLogout(args, io, deps = defaultLoginDeps(process.env)) {
4922
5065
  import { homedir as homedir4 } 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.12.1" : "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 });
@@ -4949,12 +5092,15 @@ function chooseAccount(api, apiGiven, accounts, notSignedIn) {
4949
5092
  }
4950
5093
  async function resolveAccount(input) {
4951
5094
  const { api, apiGiven, cwd, home, accounts } = input;
4952
- const folder = trustedRootFor(cwd);
4953
- const notSignedIn = NOT_SIGNED_IN_FOR(folder);
5095
+ const { work, trust } = projectFolders(cwd);
5096
+ const notSignedIn = NOT_SIGNED_IN_FOR(trust);
4954
5097
  const chosen = chooseAccount(api, apiGiven, accounts, notSignedIn);
4955
5098
  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);
5099
+ const homeDir = normaliseFolder(home);
5100
+ if (homeFolderRefusal(trust, homeDir) !== null || homeFolderRefusal(work, homeDir) !== null) return refuse(notSignedIn);
5101
+ const trusted = (f) => chosen.folders.some((saved) => normaliseFolder(saved) === f);
5102
+ const folder = trusted(work) ? work : trusted(trust) ? trust : null;
5103
+ if (folder === null) return refuse(notSignedIn);
4958
5104
  const linked = Object.entries(chosen.links).find(([f]) => normaliseFolder(f) === folder)?.[1];
4959
5105
  const projectId = linked !== void 0 && PROJECT_ID3.test(linked) ? linked : null;
4960
5106
  let token;
@@ -4964,7 +5110,7 @@ async function resolveAccount(input) {
4964
5110
  return refuse(notSignedIn);
4965
5111
  }
4966
5112
  if (token === null || !ACCOUNT_TOKEN3.test(token)) return refuse(notSignedIn);
4967
- return { kind: "account", origin: chosen.origin, email: chosen.email, token, folder, projectId };
5113
+ return { kind: "account", origin: chosen.origin, email: chosen.email, token, folder, workFolder: work, projectId };
4968
5114
  }
4969
5115
 
4970
5116
  // src/mcp/jsonrpc.ts
@@ -5298,25 +5444,32 @@ var ACCOUNT_TOOLS = [
5298
5444
  ];
5299
5445
 
5300
5446
  // src/mcp/project-folder.ts
5301
- import { isAbsolute as isAbsolute4, relative as relative4, resolve as resolve7, sep as sep5 } from "node:path";
5447
+ import { isAbsolute as isAbsolute5, join as join13, relative as relative5, resolve as resolve8, sep as sep5 } from "node:path";
5302
5448
  var NOT_SURE_WHICH_FOLDER = "Not sure which project folder to change: run npx designsource connect in it first.";
5303
5449
  function isWithin2(folder, root) {
5304
- const rel = relative4(root, folder);
5305
- return rel === "" || rel !== ".." && !rel.startsWith(`..${sep5}`) && !isAbsolute4(rel);
5450
+ const rel = relative5(root, folder);
5451
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep5}`) && !isAbsolute5(rel);
5306
5452
  }
5307
- function resolveProjectFolder(cwd, entry) {
5453
+ function resolveProjectFolder(cwd, entry, worktree = worktreeOf(cwd)) {
5308
5454
  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);
5455
+ const here = resolve8(cwd);
5456
+ const saved = entry.folders.map((f) => resolve8(f));
5457
+ const mapped = worktree ? saved.map((f) => normaliseFolder(f)).filter((f) => isWithin2(f, worktree.main)).map((f) => join13(worktree.work, relative5(worktree.main, f))) : [];
5458
+ const realHere = worktree ? normaliseFolder(cwd) : here;
5459
+ const holding = [...mapped.filter((f) => isWithin2(realHere, f)), ...saved.filter((f) => isWithin2(here, f))].sort((a, b) => b.length - a.length);
5311
5460
  if (holding[0]) return holding[0];
5312
- return entry.folders.length === 1 ? resolve7(entry.folders[0]) : null;
5461
+ return entry.folders.length === 1 ? resolve8(entry.folders[0]) : null;
5462
+ }
5463
+ function worktreeOf(cwd) {
5464
+ const { work, trust, worktree } = projectFolders(cwd);
5465
+ return worktree ? { work, main: trust } : null;
5313
5466
  }
5314
5467
 
5315
5468
  // src/mcp/tools.ts
5316
5469
  var accountProjectPath = (projectId, kind) => `/api/agent/projects/${encodeURIComponent(projectId)}/${kind}`;
5317
5470
  var READ_ONLY = { readOnlyHint: true };
5318
5471
  var TIERS = ["design", "semantic", "component"];
5319
- var CATEGORIES = ["color", "spacing", "radius", "typography", "shadow", "zIndex", "border"];
5472
+ var CATEGORIES = ["color", "spacing", "radius", "typography", "shadow", "zIndex", "border", "gradient"];
5320
5473
  var NO_INPUT = { type: "object", properties: {}, additionalProperties: false };
5321
5474
  var pretty = (v) => JSON.stringify(v, null, 2);
5322
5475
  var NO_BLOCKS = "This server sent no blocks. Update designsource and the server.";
@@ -5420,7 +5573,7 @@ async function addUiKit(args, ctx) {
5420
5573
  if (!screens.ok) return errorResult(SCREENS_ARG);
5421
5574
  const access = kitAccess(ctx);
5422
5575
  if (isResult2(access)) return access;
5423
- const root = ctx.token !== null ? resolveProjectFolder(ctx.cwd, ctx.projectFolders === null ? null : { folders: ctx.projectFolders }) : ctx.account.folder;
5576
+ const root = ctx.token !== null ? resolveProjectFolder(ctx.cwd, ctx.projectFolders === null ? null : { folders: ctx.projectFolders }) : ctx.account.workFolder;
5424
5577
  if (root === null) return errorResult(NOT_SURE_WHICH_FOLDER);
5425
5578
  const questions = {
5426
5579
  pickComponents: async (all) => all,
@@ -5773,6 +5926,7 @@ function toolAccountFor(session, accounts, onLink, onGone = () => {
5773
5926
  token: session.token,
5774
5927
  email: session.email,
5775
5928
  folder: session.folder,
5929
+ workFolder: session.workFolder,
5776
5930
  projectId: session.projectId,
5777
5931
  link(projectId) {
5778
5932
  if (accounts.link(session.origin, session.folder, projectId) === null) {
@@ -5813,9 +5967,8 @@ async function runMcp(args, io, streams = { input: process.stdin, output: proces
5813
5967
  if (resolved.kind === "none") {
5814
5968
  return {
5815
5969
  token: null,
5816
- missingToken: `${MCP_TOKEN_REQUIRED}
5817
-
5818
- ${resolved.message}`,
5970
+ // The account path's own sentence: it names the folder and the one command (`login`).
5971
+ missingToken: resolved.message,
5819
5972
  accountRefusal: resolved.message,
5820
5973
  projectFolders: null,
5821
5974
  api: args.api,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "designsource",
3
- "version": "0.11.0",
3
+ "version": "0.12.1",
4
4
  "description": "The DS source CLI: add your design system's UI kit to a React app (add), add the design system to any other app (integrate), start a new Next.js project from it (create), or serve it to a coding agent over MCP (mcp) — tokens, every component and your mockup page.",
5
5
  "license": "MIT",
6
6
  "repository": {