@sudajs/cli 0.18.11 → 0.19.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.
package/dist/index.js CHANGED
@@ -6,9 +6,7 @@ import { createRequire } from 'module';
6
6
  import path2 from 'path';
7
7
  import { createInterface } from 'readline/promises';
8
8
  import { fileURLToPath, pathToFileURL } from 'url';
9
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
10
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
11
- import { themeDesignSystemSchema, createThemeDesignCssVariables, createThemeAgentManifest, createSudaPageAgentRuntime, checkThemeModule, formatThemeCheckResult, agentValidationResultSchema, agentPageSchemaOutputSchema, agentComponentOutputSchema } from '@sudajs/theme-engine';
9
+ import { themeDesignSystemSchema, createThemeDesignCssVariables, createThemeAgentManifest, createSudaPageAgentRuntime, checkThemeModule, formatThemeCheckResult, agentValidationResultSchema } from '@sudajs/theme-engine';
12
10
  import { themeManifestSchema, runWithThemePreviewLocale } from '@sudajs/theme-engine/server';
13
11
  import { Command } from 'commander';
14
12
  import { build } from 'esbuild';
@@ -1185,17 +1183,18 @@ async function validateThemeCssTokenContract(root) {
1185
1183
  }
1186
1184
  }
1187
1185
  }
1188
- const sudaAliases = /* @__PURE__ */ new Set();
1186
+ const platformTokenPattern = /var\(\s*--(?:background|foreground|primary(?:-foreground)?|secondary(?:-foreground)?|accent(?:-foreground)?|muted(?:-foreground)?|radius(?:-(?:card|button|input))?)(?:\s*[,)])/;
1187
+ const platformAliases = /* @__PURE__ */ new Set();
1189
1188
  let changed = true;
1190
1189
  while (changed) {
1191
1190
  changed = false;
1192
1191
  for (const [name, value] of declarations) {
1193
- const dependsOnSuda = /var\(\s*--suda-/.test(value);
1194
- const dependsOnAlias = [...sudaAliases].some(
1192
+ const dependsOnPlatformToken = platformTokenPattern.test(value);
1193
+ const dependsOnAlias = [...platformAliases].some(
1195
1194
  (alias) => new RegExp(`var\\(\\s*${escapeRegExp(alias)}(?:\\s*[,\\)])`).test(value)
1196
1195
  );
1197
- if ((dependsOnSuda || dependsOnAlias) && !sudaAliases.has(name)) {
1198
- sudaAliases.add(name);
1196
+ if ((dependsOnPlatformToken || dependsOnAlias) && !platformAliases.has(name)) {
1197
+ platformAliases.add(name);
1199
1198
  changed = true;
1200
1199
  }
1201
1200
  }
@@ -1211,7 +1210,7 @@ async function validateThemeCssTokenContract(root) {
1211
1210
  }
1212
1211
  }
1213
1212
  const searchable = handwrittenStyles.join("");
1214
- for (const alias of sudaAliases) {
1213
+ for (const alias of platformAliases) {
1215
1214
  const reference = new RegExp(`var\\(\\s*${escapeRegExp(alias)}(?:\\s*[,\\)])`, "g");
1216
1215
  for (const match of searchable.matchAll(reference)) {
1217
1216
  const line = searchable.slice(0, match.index ?? 0).split("\n").length;
@@ -1224,7 +1223,7 @@ async function validateThemeCssTokenContract(root) {
1224
1223
  [
1225
1224
  "Hand-written theme CSS must not consume Suda-backed Tailwind aliases from `@theme inline`.",
1226
1225
  ...issues.map((issue) => ` - ${issue}`),
1227
- "Use `var(--suda-*)` directly, or define and consume a theme-prefixed variable on the theme root. Tailwind utilities such as `bg-primary` remain supported."
1226
+ "Use an unprefixed platform token such as `var(--primary)` directly, or define and consume a theme-prefixed variable on the theme root. Tailwind utilities such as `bg-primary` remain supported."
1228
1227
  ].join("\n")
1229
1228
  );
1230
1229
  }
@@ -1724,8 +1723,14 @@ function runFooterContractCheck(theme, renderer) {
1724
1723
  return issues;
1725
1724
  }
1726
1725
  var __testUtils = {
1726
+ activateThemeOutputSchema,
1727
+ contactFormOutputSchema,
1728
+ createPageDraftOutputSchema,
1729
+ createProjectOutputSchema,
1727
1730
  createThemeProjectRequire,
1731
+ createVisualAuditPage,
1728
1732
  createRemotePageDraft,
1733
+ destructivePageOperationOutputSchema,
1729
1734
  findAnchorTagByHref,
1730
1735
  formatMissingSharpWarning,
1731
1736
  loadThemeScopedRenderer,
@@ -1736,13 +1741,18 @@ var __testUtils = {
1736
1741
  performConfirmedPageOperation,
1737
1742
  performUpdateContactForm,
1738
1743
  performUpdateThemeSettings,
1744
+ getRemoteContactForm,
1739
1745
  getRemoteThemeSettings,
1746
+ listProjectsOutputSchema,
1740
1747
  renderDevStarterPageHtml,
1741
1748
  renderDevEditorPageHtml,
1742
1749
  writeVitePreviewEntries,
1743
1750
  resolveDevEditorSlug,
1744
1751
  resolveDevStarterSlug,
1752
+ resolveDevVisualAuditComponent,
1753
+ getThemeVisualAuditComponentTypes,
1745
1754
  resolveScreenshotOptions,
1755
+ resolveVisualCheckOptions,
1746
1756
  slugifyThemeName,
1747
1757
  validateThemeKey,
1748
1758
  validateThemeName,
@@ -1753,7 +1763,11 @@ var __testUtils = {
1753
1763
  resolveThemePreviewLocale,
1754
1764
  withSerializedVitePreviewLocaleLoad,
1755
1765
  toViteModuleUrl,
1756
- updateRemotePageDraft
1766
+ themeSettingsOutputSchema,
1767
+ updateContactFormOutputSchema,
1768
+ updatePageDraftOutputSchema,
1769
+ updateRemotePageDraft,
1770
+ updateThemeSettingsOutputSchema
1757
1771
  };
1758
1772
  async function runThemeCheck(theme) {
1759
1773
  const result = checkThemeModule(theme.module);
@@ -1809,7 +1823,7 @@ async function watchTheme(root, port) {
1809
1823
  console.log(`previewing Vite theme at ${style.url(handle.url)}`);
1810
1824
  await new Promise(() => void 0);
1811
1825
  }
1812
- async function startViteDevPreviewServer(root, port) {
1826
+ async function startViteDevPreviewServer(root, port, options = {}) {
1813
1827
  const viteConfig = await findViteConfig(root);
1814
1828
  const vite = await loadThemeVite(root);
1815
1829
  await writeVitePreviewEntries(root);
@@ -1824,13 +1838,14 @@ async function startViteDevPreviewServer(root, port) {
1824
1838
  entries: [".suda-build/preview-client.ts", ".suda-build/editor-client.ts"]
1825
1839
  },
1826
1840
  server: { host, port },
1827
- plugins: [createSudaPreviewVitePlugin(root)]
1841
+ plugins: [createSudaPreviewVitePlugin(root, options)]
1828
1842
  });
1829
1843
  await server.listen(port);
1830
1844
  const url = server.resolvedUrls?.local.find((candidate) => candidate.includes("127.0.0.1")) ?? server.resolvedUrls?.local[0] ?? `http://${host}:${port}/`;
1831
1845
  return {
1832
1846
  url: url.replace(/\/$/, ""),
1833
1847
  port,
1848
+ server,
1834
1849
  close: () => server.close()
1835
1850
  };
1836
1851
  }
@@ -1840,8 +1855,8 @@ async function writeVitePreviewEntries(root) {
1840
1855
  const buildDir = path2.join(root, ".suda-build");
1841
1856
  await mkdir(buildDir, { recursive: true });
1842
1857
  await writeFile(
1843
- path2.join(buildDir, "runtime.dev.ts"),
1844
- createClientRuntimeSource(clientHooksImport, false),
1858
+ path2.join(buildDir, "runtime.dev.js"),
1859
+ createClientRuntimeSource(clientHooksImport, false, false),
1845
1860
  "utf8"
1846
1861
  );
1847
1862
  await writeFile(
@@ -1853,7 +1868,7 @@ async function writeVitePreviewEntries(root) {
1853
1868
  'if(!payloadElement){throw new Error("Missing Suda theme hydration payload.")}',
1854
1869
  "const payload=JSON.parse(payloadElement.textContent ?? '{}');",
1855
1870
  "if(payload.previewLocaleMessages){installThemePreviewLocale(payload.previewLocaleMessages)}",
1856
- 'const runtime=(await loadThemeRuntime("/.suda-build/runtime.dev.ts")).default;',
1871
+ 'const runtime=(await loadThemeRuntime("/.suda-build/runtime.dev.js")).default;',
1857
1872
  'const metadata={contactForm:payload.contactForm,resolveAssetUrl:(value: string | undefined)=>resolveAssetPath(value,{legacyResolve:(key)=>key.startsWith("themes/")?`/api/themes/${key.slice("themes/".length)}`:undefined})};',
1858
1873
  'await hydrateThemePage({container:document.querySelector("[data-theme-hydration-root]")!,runtime,pageData:payload.pageData,layoutData:payload.layoutData,metadata,onRecoverableError:(error)=>console.error("[theme-dev] theme hydration recovered from an error",error)});',
1859
1874
  ""
@@ -1883,7 +1898,28 @@ async function writeVitePreviewEntries(root) {
1883
1898
  "utf8"
1884
1899
  );
1885
1900
  }
1886
- function createClientRuntimeSource(clientHooksImport, useClientDirective) {
1901
+ function createClientRuntimeSource(clientHooksImport, useClientDirective, typescript = true) {
1902
+ if (!typescript) {
1903
+ return [
1904
+ ...useClientDirective ? ['"use client";'] : [],
1905
+ 'import * as themeConfig from "../src/config.js";',
1906
+ clientHooksImport,
1907
+ "const theme = {",
1908
+ " pageConfig: themeConfig.pageConfig,",
1909
+ " layoutConfig: themeConfig.layoutConfig,",
1910
+ "};",
1911
+ 'if ("rendering" in themeConfig && themeConfig.rendering !== undefined) {',
1912
+ " theme.rendering = themeConfig.rendering;",
1913
+ "}",
1914
+ "const hooks = clientHooks;",
1915
+ "const runtime = { theme };",
1916
+ "if (hooks.initialize !== undefined) {",
1917
+ " runtime.initialize = hooks.initialize;",
1918
+ "}",
1919
+ "export default runtime;",
1920
+ ""
1921
+ ].join("\n");
1922
+ }
1887
1923
  return [
1888
1924
  ...useClientDirective ? ['"use client";'] : [],
1889
1925
  'import type { ThemeClientHooks, ThemeClientRuntime, ThemeRenderModule } from "@sudajs/theme-engine/runtime";',
@@ -1905,22 +1941,49 @@ function createClientRuntimeSource(clientHooksImport, useClientDirective) {
1905
1941
  ""
1906
1942
  ].join("\n");
1907
1943
  }
1908
- function createSudaPreviewVitePlugin(root) {
1944
+ function createSudaPreviewVitePlugin(root, options = {}) {
1909
1945
  return {
1910
1946
  name: "suda-theme-preview",
1947
+ resolveId(source, importer) {
1948
+ if (importer === void 0 || !source.endsWith(".js") || !source.startsWith(".")) {
1949
+ return void 0;
1950
+ }
1951
+ const requestedPath = path2.resolve(path2.dirname(importer), source);
1952
+ if (!requestedPath.startsWith(`${root}${path2.sep}`)) {
1953
+ return void 0;
1954
+ }
1955
+ for (const extension of [".ts", ".tsx"]) {
1956
+ const candidate = `${requestedPath.slice(0, -3)}${extension}`;
1957
+ if (existsSync(candidate)) {
1958
+ return candidate;
1959
+ }
1960
+ }
1961
+ return void 0;
1962
+ },
1911
1963
  configureServer(server) {
1912
1964
  server.middlewares.use((request, response, next) => {
1913
1965
  void (async () => {
1914
1966
  const url = new URL(request.url ?? "/", "http://localhost");
1967
+ if (url.pathname.startsWith("/src/") && url.pathname.endsWith(".js")) {
1968
+ const sourcePath = path2.join(root, url.pathname.slice(1));
1969
+ for (const extension of [".ts", ".tsx"]) {
1970
+ const candidate = `${sourcePath.slice(0, -3)}${extension}`;
1971
+ if (existsSync(candidate)) {
1972
+ request.url = `${url.pathname.slice(0, -3)}${extension}${url.search}`;
1973
+ break;
1974
+ }
1975
+ }
1976
+ }
1915
1977
  const assetPrefixMatch = url.pathname.match(/^\/api\/themes\/[^/]+\/[^/]+\/assets\/(.+)$/);
1916
1978
  if (assetPrefixMatch?.[1]) {
1917
1979
  request.url = `/assets/${assetPrefixMatch[1]}${url.search}`;
1918
1980
  next();
1919
1981
  return;
1920
1982
  }
1983
+ const visualAuditComponent = resolveDevVisualAuditComponent(url.pathname);
1921
1984
  const editorSlug = resolveDevEditorSlug(url.pathname);
1922
1985
  const previewSlug = resolveDevStarterSlug(url.pathname);
1923
- if (editorSlug === void 0 && previewSlug === void 0) {
1986
+ if (visualAuditComponent === void 0 && editorSlug === void 0 && previewSlug === void 0) {
1924
1987
  next();
1925
1988
  return;
1926
1989
  }
@@ -1938,11 +2001,11 @@ function createSudaPreviewVitePlugin(root) {
1938
2001
  );
1939
2002
  const renderer = await loadThemeScopedRenderer(root);
1940
2003
  const starterSlug = slug ?? pickStarterSlug(localized.theme);
1941
- const starter = starterSlug ? findStarterPage(localized.theme, starterSlug) : null;
2004
+ const starter = visualAuditComponent ? createVisualAuditPage(localized.theme, visualAuditComponent) : starterSlug ? findStarterPage(localized.theme, starterSlug) : null;
1942
2005
  if (!starter) {
1943
2006
  response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
1944
2007
  response.end(
1945
- starterSlug ? `Unknown starter page: ${starterSlug}` : "No starter pages declared by this theme."
2008
+ starterSlug ? `Unknown starter page: ${starterSlug}` : visualAuditComponent ? `Unknown theme page component: ${visualAuditComponent}` : "No starter pages declared by this theme."
1946
2009
  );
1947
2010
  return;
1948
2011
  }
@@ -1960,7 +2023,8 @@ function createSudaPreviewVitePlugin(root) {
1960
2023
  localized.locale,
1961
2024
  canonicalLocale(explicitLang) !== null,
1962
2025
  localized.previewLocaleMessages,
1963
- url.searchParams
2026
+ url.searchParams,
2027
+ { showDevTools: options.showDevTools !== false }
1964
2028
  );
1965
2029
  const html = await server.transformIndexHtml(url.pathname, htmlSource);
1966
2030
  response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
@@ -2043,6 +2107,42 @@ function findStarterPage(theme, slug) {
2043
2107
  return theme.module.starterPages.find((page) => page.slug === slug) ?? null;
2044
2108
  }
2045
2109
  var DEV_EDITOR_PATH = "/__suda/editor";
2110
+ var DEV_VISUAL_AUDIT_PATH = "/__suda/visual-audit";
2111
+ function resolveDevVisualAuditComponent(pathname) {
2112
+ if (!pathname.startsWith(`${DEV_VISUAL_AUDIT_PATH}/`)) {
2113
+ return void 0;
2114
+ }
2115
+ const encodedComponent = pathname.slice(DEV_VISUAL_AUDIT_PATH.length + 1);
2116
+ if (!encodedComponent || encodedComponent.includes("/")) {
2117
+ return void 0;
2118
+ }
2119
+ try {
2120
+ return decodeURIComponent(encodedComponent);
2121
+ } catch {
2122
+ return void 0;
2123
+ }
2124
+ }
2125
+ function getThemeVisualAuditComponentTypes(theme) {
2126
+ return Object.keys(theme.module.pageConfig.components);
2127
+ }
2128
+ function createVisualAuditPage(theme, type) {
2129
+ const themeComponent = theme.module.pageConfig.components[type];
2130
+ if (!themeComponent) {
2131
+ return null;
2132
+ }
2133
+ const props = {
2134
+ ...themeComponent.defaultProps ?? {},
2135
+ id: `suda-visual-audit-${safeObjectKeyPart(type)}`
2136
+ };
2137
+ return {
2138
+ slug: `visual-audit-${safeObjectKeyPart(type).toLowerCase()}`,
2139
+ title: `Visual audit: ${type}`,
2140
+ data: {
2141
+ root: { props: {} },
2142
+ content: [{ type, props }]
2143
+ }
2144
+ };
2145
+ }
2046
2146
  function resolveDevEditorSlug(pathname) {
2047
2147
  if (pathname === DEV_EDITOR_PATH || pathname === `${DEV_EDITOR_PATH}/`) {
2048
2148
  return null;
@@ -2169,7 +2269,7 @@ async function loadThemeScopedRenderer(themeRoot) {
2169
2269
  renderToString: reactDomServerModule.renderToString
2170
2270
  };
2171
2271
  }
2172
- function renderDevStarterPageHtml(theme, page, renderer, locale = "en", preserveLang = false, previewLocaleMessages, searchParams = new URLSearchParams()) {
2272
+ function renderDevStarterPageHtml(theme, page, renderer, locale = "en", preserveLang = false, previewLocaleMessages, searchParams = new URLSearchParams(), options = {}) {
2173
2273
  const layoutData = createDevPreviewLayout(theme, searchParams);
2174
2274
  const chrome = renderer.extractLayoutChrome(layoutData);
2175
2275
  const metadata = {
@@ -2187,10 +2287,11 @@ function renderDevStarterPageHtml(theme, page, renderer, locale = "en", preserve
2187
2287
  const cssVarStyle = Object.entries(chrome.cssVariables).map(([key, value]) => `${key}: ${value};`).join(" ");
2188
2288
  const customHead = chrome.customHeadCode ?? "";
2189
2289
  const customBody = chrome.customBodyCode ?? "";
2190
- const designPalette = renderDevDesignPalette(
2290
+ const showDevTools = options.showDevTools !== false;
2291
+ const designPalette = showDevTools ? renderDevDesignPalette(
2191
2292
  theme.module.manifest.designSystem,
2192
2293
  createDevEditorHref(page.slug, searchParams)
2193
- );
2294
+ ) : null;
2194
2295
  const hydrationPayload = serializeInlineScriptValue({
2195
2296
  pageData: page.data,
2196
2297
  layoutData,
@@ -2209,12 +2310,12 @@ function renderDevStarterPageHtml(theme, page, renderer, locale = "en", preserve
2209
2310
  '<meta name="viewport" content="width=device-width, initial-scale=1" />',
2210
2311
  `<title>${escapeHtml(`${theme.module.manifest.name} \u2014 ${page.title}`)}</title>`,
2211
2312
  '<link rel="stylesheet" href="/src/styles.css" />',
2212
- designPalette.style,
2213
2313
  customHead,
2314
+ designPalette?.style ?? "",
2214
2315
  "</head>",
2215
2316
  `<body${cssVarStyle ? ` style="${cssVarStyle}"` : ""}>`,
2216
2317
  `<div data-theme-hydration-root="" style="display:contents">${body}</div>`,
2217
- designPalette.html,
2318
+ designPalette?.html ?? "",
2218
2319
  customBody,
2219
2320
  hydrationScript,
2220
2321
  ...preserveLang ? [
@@ -2347,7 +2448,7 @@ function renderDevDesignPalette(designSystem, editorHref) {
2347
2448
  });
2348
2449
  return {
2349
2450
  style: '<style data-suda-dev-palette-style>\n#suda-dev-palette{all:initial;position:fixed;z-index:2147483000;top:50%;right:16px;width:64px;max-height:calc(100svh - 32px);padding:8px 9px;overflow-x:hidden;overflow-y:auto;box-sizing:border-box;background:#fff;border:1px solid #d1d5db;border-radius:999px;box-shadow:0 8px 24px rgb(15 23 42 / 12%);transform:translateY(-50%);color-scheme:light;scrollbar-width:none;-ms-overflow-style:none}\n#suda-dev-palette::-webkit-scrollbar{display:none}\n#suda-dev-palette button{all:initial;position:relative;display:grid;width:44px;height:44px;box-sizing:border-box;cursor:pointer;border-radius:999px;place-items:center}\n#suda-dev-palette button span{display:block;width:32px;height:32px;border-radius:999px;transition:transform 120ms ease}\n#suda-dev-palette button:hover span{transform:scale(1.08)}\n#suda-dev-palette button[aria-pressed="true"] span{visibility:hidden}\n#suda-dev-palette .suda-dev-preset-selected-icon{position:absolute;display:block;width:32px;height:32px;color:var(--suda-dev-preset-primary);visibility:hidden;opacity:0;transform:scale(.85);transition:opacity 120ms ease,transform 120ms ease}\n#suda-dev-palette button[aria-pressed="true"] .suda-dev-preset-selected-icon{visibility:visible;opacity:1;transform:scale(1)}\n#suda-dev-palette button:focus-visible{outline:2px solid #94a3b8;outline-offset:2px}\n#suda-dev-palette .suda-dev-edit-divider{display:block;width:28px;height:1px;margin:4px auto;background:#e2e8f0}\n#suda-dev-palette .suda-dev-edit-link{all:initial;display:grid;width:44px;height:44px;box-sizing:border-box;color:#334155;cursor:pointer;border-radius:999px;place-items:center;transition:background-color 120ms ease,color 120ms ease}\n#suda-dev-palette .suda-dev-edit-link:hover{color:#0f172a;background:#f1f5f9}\n#suda-dev-palette .suda-dev-edit-link:focus-visible{outline:2px solid #94a3b8;outline-offset:2px}\n@media(max-width:640px){#suda-dev-palette{right:8px;max-height:calc(100svh - 16px)}}\n@media(prefers-reduced-motion:reduce){#suda-dev-palette button span,#suda-dev-palette .suda-dev-preset-selected-icon,#suda-dev-palette .suda-dev-edit-link{transition:none}}\n</style>',
2350
- html: `<aside id="suda-dev-palette" aria-label="Theme development tools">${buttons}${hasPresetSwitcher ? '<span class="suda-dev-edit-divider" aria-hidden="true"></span>' : ""}<a class="suda-dev-edit-link" data-suda-dev-editor-link="" href="${escapeHtml(editorHref)}" title="Edit starter page" aria-label="Edit starter page">${editIcon}</a></aside>` + (hasPresetSwitcher ? `<script data-suda-dev-palette-script>(function(){const config=${config};const palette=document.getElementById("suda-dev-palette");if(!palette)return;const byId=new Map(config.presets.map((preset)=>[preset.id,preset]));const params=new URL(location.href).searchParams;const requested=params.get("designPreset");const selected=byId.has(requested)?requested:config.defaultPresetId;function apply(id,updateUrl){const preset=byId.get(id);if(!preset)return;const properties=Object.keys(preset.variables);const targets=[document.documentElement,document.body,...document.querySelectorAll("[style]")].filter((element,index,items)=>items.indexOf(element)===index&&(element===document.documentElement||element===document.body||properties.some((property)=>element.style.getPropertyValue(property)!=="")));for(const target of targets){for(const [property,value] of Object.entries(preset.variables))target.style.setProperty(property,value)}for(const button of palette.querySelectorAll("[data-suda-dev-preset]")){const active=button.dataset.sudaDevPreset===id;button.setAttribute("aria-pressed",String(active));button.style.setProperty("--suda-dev-preset-primary",byId.get(button.dataset.sudaDevPreset).variables["--suda-color-primary"])}const editorLink=palette.querySelector("[data-suda-dev-editor-link]");if(editorLink){const editorUrl=new URL(editorLink.href,location.href);editorUrl.searchParams.set("designPreset",id);editorLink.href=editorUrl.pathname+editorUrl.search+editorUrl.hash}if(updateUrl){const url=new URL(location.href);url.searchParams.set("designPreset",id);history.replaceState(history.state,"",url)}}if(requested&&byId.has(requested))apply(selected,false);else for(const button of palette.querySelectorAll("[data-suda-dev-preset]")){button.setAttribute("aria-pressed",String(button.dataset.sudaDevPreset===selected));button.style.setProperty("--suda-dev-preset-primary",byId.get(button.dataset.sudaDevPreset).variables["--suda-color-primary"])}palette.addEventListener("click",(event)=>{const button=event.target.closest("[data-suda-dev-preset]");if(button)apply(button.dataset.sudaDevPreset,true)})})();</script>` : "")
2451
+ html: `<aside id="suda-dev-palette" aria-label="Theme development tools">${buttons}${hasPresetSwitcher ? '<span class="suda-dev-edit-divider" aria-hidden="true"></span>' : ""}<a class="suda-dev-edit-link" data-suda-dev-editor-link="" href="${escapeHtml(editorHref)}" title="Edit starter page" aria-label="Edit starter page">${editIcon}</a></aside>` + (hasPresetSwitcher ? `<script data-suda-dev-palette-script>(function(){const config=${config};const palette=document.getElementById("suda-dev-palette");if(!palette)return;const byId=new Map(config.presets.map((preset)=>[preset.id,preset]));const params=new URL(location.href).searchParams;const requested=params.get("designPreset");const selected=byId.has(requested)?requested:config.defaultPresetId;function apply(id,updateUrl){const preset=byId.get(id);if(!preset)return;const properties=Object.keys(preset.variables);const targets=[document.documentElement,document.body,...document.querySelectorAll("[style]")].filter((element,index,items)=>items.indexOf(element)===index&&(element===document.documentElement||element===document.body||properties.some((property)=>element.style.getPropertyValue(property)!=="")));for(const target of targets){for(const [property,value] of Object.entries(preset.variables))target.style.setProperty(property,value)}for(const button of palette.querySelectorAll("[data-suda-dev-preset]")){const active=button.dataset.sudaDevPreset===id;button.setAttribute("aria-pressed",String(active));button.style.setProperty("--suda-dev-preset-primary",byId.get(button.dataset.sudaDevPreset).variables["--primary"])}const editorLink=palette.querySelector("[data-suda-dev-editor-link]");if(editorLink){const editorUrl=new URL(editorLink.href,location.href);editorUrl.searchParams.set("designPreset",id);editorLink.href=editorUrl.pathname+editorUrl.search+editorUrl.hash}if(updateUrl){const url=new URL(location.href);url.searchParams.set("designPreset",id);history.replaceState(history.state,"",url)}}if(requested&&byId.has(requested))apply(selected,false);else for(const button of palette.querySelectorAll("[data-suda-dev-preset]")){button.setAttribute("aria-pressed",String(button.dataset.sudaDevPreset===selected));button.style.setProperty("--suda-dev-preset-primary",byId.get(button.dataset.sudaDevPreset).variables["--primary"])}palette.addEventListener("click",(event)=>{const button=event.target.closest("[data-suda-dev-preset]");if(button)apply(button.dataset.sudaDevPreset,true)})})();</script>` : "")
2351
2452
  };
2352
2453
  }
2353
2454
  var SCREENSHOT_DEVICES = ["desktop", "tablet", "mobile"];
@@ -2422,6 +2523,33 @@ function resolveScreenshotOptions(root, options) {
2422
2523
  fullPage: options.fullPage === true
2423
2524
  };
2424
2525
  }
2526
+ function parseVisualCheckPresetIds(theme, value) {
2527
+ const available = theme.module.manifest.designSystem.presets.map((preset) => preset.id);
2528
+ if (value === void 0) {
2529
+ return available;
2530
+ }
2531
+ const requested = (Array.isArray(value) ? value : [value]).flatMap((item) => item.split(",")).map((item) => item.trim()).filter(Boolean);
2532
+ if (requested.length === 0) {
2533
+ return available;
2534
+ }
2535
+ const unknown = requested.filter((preset) => !available.includes(preset));
2536
+ if (unknown.length > 0) {
2537
+ throw new Error(
2538
+ `Unknown design preset ${unknown.map((preset) => `"${preset}"`).join(", ")}. Available presets: ${available.join(", ")}.`
2539
+ );
2540
+ }
2541
+ return Array.from(new Set(requested));
2542
+ }
2543
+ function resolveVisualCheckOptions(root, theme, options) {
2544
+ const outputDir = path2.resolve(root, options.output ?? path2.join(".suda-build", "visual-check"));
2545
+ return {
2546
+ devices: parseScreenshotDevices(options.device),
2547
+ fullPage: options.fullPage === true,
2548
+ outputDir,
2549
+ port: parsePositiveInt(options.port, 4179),
2550
+ presetIds: parseVisualCheckPresetIds(theme, options.preset)
2551
+ };
2552
+ }
2425
2553
  function createThemeProjectRequire(themeRoot) {
2426
2554
  return createRequire(path2.join(themeRoot, "package.json"));
2427
2555
  }
@@ -2516,7 +2644,7 @@ async function optimizePngIfAvailable(themeRoot, filePath) {
2516
2644
  }
2517
2645
  async function captureScreenshot(root, options) {
2518
2646
  const playwright = await loadPlaywright(root);
2519
- const handle = await startViteDevPreviewServer(root, options.port);
2647
+ const handle = await startViteDevPreviewServer(root, options.port, { showDevTools: false });
2520
2648
  try {
2521
2649
  const browser = await playwright.chromium.launch({ headless: true });
2522
2650
  try {
@@ -2549,6 +2677,278 @@ async function screenshotTheme(root, options) {
2549
2677
  const resolved = resolveScreenshotOptions(root, options);
2550
2678
  await captureScreenshot(root, resolved);
2551
2679
  }
2680
+ function visualAuditUrl(baseUrl, component, preset) {
2681
+ const url = new URL(`${DEV_VISUAL_AUDIT_PATH}/${encodeURIComponent(component)}`, `${baseUrl}/`);
2682
+ url.searchParams.set("designPreset", preset);
2683
+ return url.href;
2684
+ }
2685
+ async function runThemeVisualCheck(root, options) {
2686
+ const playwright = await loadPlaywright(root);
2687
+ const handle = await startViteDevPreviewServer(root, parsePositiveInt(options.port, 4179));
2688
+ let theme;
2689
+ try {
2690
+ theme = await loadViteDevTheme(root, handle.server);
2691
+ } catch (error2) {
2692
+ await handle.close();
2693
+ throw error2;
2694
+ }
2695
+ const resolved = resolveVisualCheckOptions(root, theme, options);
2696
+ const components = getThemeVisualAuditComponentTypes(theme);
2697
+ const report = {
2698
+ components,
2699
+ issues: [],
2700
+ outputDir: resolved.outputDir,
2701
+ presets: resolved.presetIds
2702
+ };
2703
+ try {
2704
+ const browser = await playwright.chromium.launch({ headless: true });
2705
+ try {
2706
+ for (const preset of resolved.presetIds) {
2707
+ for (const device of resolved.devices) {
2708
+ const viewport = SCREENSHOT_DEVICE_CONFIG[device].viewport;
2709
+ const context = await browser.newContext({ viewport, deviceScaleFactor: 1 });
2710
+ try {
2711
+ for (const component of components) {
2712
+ const page = await context.newPage();
2713
+ const pageErrors = [];
2714
+ page.on("pageerror", (error2) => pageErrors.push(error2.message));
2715
+ try {
2716
+ await page.goto(visualAuditUrl(handle.url, component, preset), {
2717
+ waitUntil: "networkidle"
2718
+ });
2719
+ const audit = await page.evaluate(() => {
2720
+ const issues = [];
2721
+ const section = document.querySelector("[data-section]");
2722
+ if (!section) {
2723
+ return {
2724
+ issues: [
2725
+ {
2726
+ code: "section-missing",
2727
+ message: "The visual audit page did not render the theme component.",
2728
+ severity: "error"
2729
+ }
2730
+ ]
2731
+ };
2732
+ }
2733
+ const colorForToken = (token) => {
2734
+ const probe = document.createElement("span");
2735
+ probe.style.color = `var(${token})`;
2736
+ probe.style.display = "none";
2737
+ section.append(probe);
2738
+ const color = getComputedStyle(probe).color;
2739
+ probe.remove();
2740
+ return color;
2741
+ };
2742
+ const contrastRatio = (first, second) => {
2743
+ const channels = (value) => {
2744
+ const match = value.match(/^rgba?\\(([^)]+)\\)$/);
2745
+ if (!match?.[1]) return null;
2746
+ const parsed = match[1].split(",").slice(0, 3).map((channel) => Number.parseFloat(channel.trim()));
2747
+ if (parsed.length !== 3 || !parsed.every(Number.isFinite)) return null;
2748
+ const [red, green, blue] = parsed;
2749
+ if (red === void 0 || green === void 0 || blue === void 0) return null;
2750
+ return [red, green, blue];
2751
+ };
2752
+ const firstRgb = channels(first);
2753
+ const secondRgb = channels(second);
2754
+ if (!firstRgb || !secondRgb) return null;
2755
+ const luminance = (values) => {
2756
+ const [red, green, blue] = values.map((channel) => {
2757
+ const normalized = channel / 255;
2758
+ return normalized <= 0.04045 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
2759
+ });
2760
+ return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
2761
+ };
2762
+ const firstLuminance = luminance(firstRgb);
2763
+ const secondLuminance = luminance(secondRgb);
2764
+ return (Math.max(firstLuminance, secondLuminance) + 0.05) / (Math.min(firstLuminance, secondLuminance) + 0.05);
2765
+ };
2766
+ const tokenPairs = [
2767
+ ["--background", "--foreground"],
2768
+ ["--primary", "--primary-foreground"],
2769
+ ["--secondary", "--secondary-foreground"],
2770
+ ["--accent", "--accent-foreground"],
2771
+ ["--muted", "--muted-foreground"]
2772
+ ];
2773
+ for (const [surfaceToken, foregroundToken] of tokenPairs) {
2774
+ const ratio = contrastRatio(colorForToken(surfaceToken), colorForToken(foregroundToken));
2775
+ if (ratio === null) {
2776
+ issues.push({
2777
+ code: "token-color-unresolved",
2778
+ message: `${surfaceToken} or ${foregroundToken} did not resolve to a CSS color.`,
2779
+ severity: "error"
2780
+ });
2781
+ } else if (ratio < 4.5) {
2782
+ issues.push({
2783
+ code: "token-contrast",
2784
+ message: `${surfaceToken} and ${foregroundToken} have ${ratio.toFixed(2)}:1 contrast; 4.5:1 is required.`,
2785
+ severity: "error"
2786
+ });
2787
+ }
2788
+ }
2789
+ const semanticTokenPairs = [
2790
+ ["--background", "--foreground"],
2791
+ ["--primary", "--primary-foreground"],
2792
+ ["--secondary", "--secondary-foreground"],
2793
+ ["--accent", "--accent-foreground"],
2794
+ ["--muted", "--muted-foreground"]
2795
+ ];
2796
+ const semanticSurfaces = semanticTokenPairs.map(([surface, foreground]) => ({
2797
+ foreground,
2798
+ foregroundColor: colorForToken(foreground),
2799
+ surface,
2800
+ surfaceColor: colorForToken(surface)
2801
+ }));
2802
+ const semanticSurfacesByElement = /* @__PURE__ */ new Map();
2803
+ for (const element of [section, ...section.querySelectorAll("*")]) {
2804
+ const backgroundColor = getComputedStyle(element).backgroundColor;
2805
+ const surface = semanticSurfaces.find(
2806
+ (candidate) => candidate.surfaceColor === backgroundColor
2807
+ );
2808
+ if (surface) semanticSurfacesByElement.set(element, surface);
2809
+ }
2810
+ const visible = (element) => {
2811
+ const style2 = getComputedStyle(element);
2812
+ const rect = element.getBoundingClientRect();
2813
+ return style2.display !== "none" && style2.visibility !== "hidden" && Number.parseFloat(style2.opacity) > 0 && rect.width > 0 && rect.height > 0;
2814
+ };
2815
+ const closestSurface = (element) => {
2816
+ let current = element;
2817
+ while (current && section.contains(current)) {
2818
+ const match = semanticSurfacesByElement.get(current);
2819
+ if (match) return match;
2820
+ current = current.parentElement;
2821
+ }
2822
+ return null;
2823
+ };
2824
+ const reportedTextChecks = /* @__PURE__ */ new Set();
2825
+ const textWalker = document.createTreeWalker(section, NodeFilter.SHOW_TEXT);
2826
+ let textNode = textWalker.nextNode();
2827
+ while (textNode) {
2828
+ if (!textNode.textContent?.trim()) {
2829
+ textNode = textWalker.nextNode();
2830
+ continue;
2831
+ }
2832
+ const parent = textNode.parentElement;
2833
+ if (!parent || !visible(parent)) {
2834
+ textNode = textWalker.nextNode();
2835
+ continue;
2836
+ }
2837
+ const surface = closestSurface(parent);
2838
+ if (surface) {
2839
+ const actualForeground = getComputedStyle(parent).color;
2840
+ const ratio = contrastRatio(surface.surfaceColor, actualForeground);
2841
+ const key = `${surface.surface}/${actualForeground}`;
2842
+ if (ratio !== null && ratio < 4.5 && !reportedTextChecks.has(`contrast/${key}`)) {
2843
+ issues.push({
2844
+ code: "surface-text-contrast",
2845
+ message: `Text on ${surface.surface} has ${ratio.toFixed(2)}:1 contrast; 4.5:1 is required.`,
2846
+ severity: "error"
2847
+ });
2848
+ reportedTextChecks.add(`contrast/${key}`);
2849
+ }
2850
+ if (actualForeground !== surface.foregroundColor && !reportedTextChecks.has(`foreground/${key}`)) {
2851
+ issues.push({
2852
+ code: "surface-foreground-token-mismatch",
2853
+ message: `Text on ${surface.surface} uses ${actualForeground} instead of ${surface.foreground}; verify the custom foreground remains readable.`,
2854
+ severity: "warning"
2855
+ });
2856
+ reportedTextChecks.add(`foreground/${key}`);
2857
+ }
2858
+ }
2859
+ textNode = textWalker.nextNode();
2860
+ }
2861
+ const sectionRect = section.getBoundingClientRect();
2862
+ if (document.documentElement.scrollWidth > window.innerWidth + 1 || sectionRect.left < -1 || sectionRect.right > window.innerWidth + 1) {
2863
+ issues.push({
2864
+ code: "horizontal-overflow",
2865
+ message: "The page or audited section overflows the viewport horizontally.",
2866
+ severity: "error"
2867
+ });
2868
+ }
2869
+ const firstText = section.querySelector("h1, h2, h3, p");
2870
+ if (firstText) {
2871
+ const textRect = firstText.getBoundingClientRect();
2872
+ const overlays = Array.from(document.querySelectorAll("body *")).filter(
2873
+ (element) => {
2874
+ if (element === section || section.contains(element)) return false;
2875
+ const style2 = getComputedStyle(element);
2876
+ if (style2.position !== "fixed" || style2.visibility === "hidden") return false;
2877
+ const rect = element.getBoundingClientRect();
2878
+ return rect.bottom > textRect.top && rect.top < textRect.bottom && rect.right > textRect.left && rect.left < textRect.right;
2879
+ }
2880
+ );
2881
+ if (overlays.length > 0) {
2882
+ issues.push({
2883
+ code: "layout-overlay",
2884
+ message: "A fixed layout element overlaps the first section text. Add spacing in the theme layout if this is unintended.",
2885
+ severity: "warning"
2886
+ });
2887
+ }
2888
+ }
2889
+ return { issues };
2890
+ });
2891
+ for (const issue of audit.issues) {
2892
+ report.issues.push({ ...issue, component, device, preset });
2893
+ }
2894
+ for (const message of pageErrors) {
2895
+ report.issues.push({
2896
+ component,
2897
+ code: "page-error",
2898
+ device,
2899
+ message,
2900
+ preset,
2901
+ severity: "error"
2902
+ });
2903
+ }
2904
+ const outputPath = path2.join(
2905
+ resolved.outputDir,
2906
+ safeObjectKeyPart(preset),
2907
+ device,
2908
+ `${safeObjectKeyPart(component)}.png`
2909
+ );
2910
+ await mkdir(path2.dirname(outputPath), { recursive: true });
2911
+ await page.screenshot({ path: outputPath, fullPage: resolved.fullPage });
2912
+ await optimizePngIfAvailable(root, outputPath);
2913
+ } finally {
2914
+ await page.close();
2915
+ }
2916
+ }
2917
+ } finally {
2918
+ await context.close();
2919
+ }
2920
+ }
2921
+ }
2922
+ } finally {
2923
+ await browser.close();
2924
+ }
2925
+ } finally {
2926
+ await handle.close();
2927
+ }
2928
+ await mkdir(resolved.outputDir, { recursive: true });
2929
+ await writeFile(
2930
+ path2.join(resolved.outputDir, "report.json"),
2931
+ `${JSON.stringify(report, null, 2)}
2932
+ `
2933
+ );
2934
+ const errors = report.issues.filter((issue) => issue.severity === "error");
2935
+ const warnings = report.issues.filter((issue) => issue.severity === "warning");
2936
+ if (errors.length === 0) {
2937
+ console.log(success(`visual check passed; screenshots: ${style.path(report.outputDir)}`));
2938
+ } else {
2939
+ console.error(error(`visual check failed with ${errors.length} error(s).`));
2940
+ }
2941
+ for (const issue of report.issues) {
2942
+ const formatter = issue.severity === "error" ? error : warning;
2943
+ console.log(
2944
+ ` ${formatter(issue.severity)} ${issue.preset}/${issue.device}/${issue.component}: ${issue.message}`
2945
+ );
2946
+ }
2947
+ if (warnings.length > 0) {
2948
+ console.log(warning(`visual check completed with ${warnings.length} warning(s).`));
2949
+ }
2950
+ return errors.length === 0;
2951
+ }
2552
2952
  async function loadLocalAgentManifest(root) {
2553
2953
  const built = await readJsonIfExists(
2554
2954
  path2.join(root, "dist", "agent-manifest.json")
@@ -2910,422 +3310,6 @@ async function createAgentProject(options) {
2910
3310
  })
2911
3311
  });
2912
3312
  }
2913
- function mcpStructured(summary, value) {
2914
- return {
2915
- content: [
2916
- {
2917
- type: "text",
2918
- text: summary
2919
- }
2920
- ],
2921
- structuredContent: value
2922
- };
2923
- }
2924
- async function startMcpServer() {
2925
- const server = new McpServer({
2926
- name: "suda",
2927
- version: "0.1.0"
2928
- });
2929
- server.registerTool(
2930
- "list_projects",
2931
- {
2932
- description: "List Suda projects the current CLI user can access. ALWAYS call this first when the user asks to generate or edit a website. Flow: (1) If `projects` is empty, do NOT call this tool again; instead skip directly to gathering inputs and calling create_project (see its description). (2) If `projects` has one or more entries, you MUST ask the user which project to use before any further action \u2014 even if there is only a single project, present it and ask the user to confirm or pick a different one. Never auto-pick a project on the user's behalf.",
2933
- inputSchema: {},
2934
- outputSchema: listProjectsOutputSchema.shape
2935
- },
2936
- async () => {
2937
- const structuredContent = listProjectsOutputSchema.parse({
2938
- projects: await listAgentProjects()
2939
- });
2940
- return mcpStructured("Suda projects accessible to the current user.", structuredContent);
2941
- }
2942
- );
2943
- server.registerTool(
2944
- "create_project",
2945
- {
2946
- description: "Create a new Suda project for the current user. Only call this after list_projects returned an empty list. Conversation flow before calling: (1) Ask the user for the website / brand name in one turn and capture it as `name`. (2) Ask the user for a business introduction; the user is allowed (and expected) to answer over multiple turns \u2014 keep asking follow-up questions and accumulating their answers until they confirm they are done, then concatenate the accumulated text into a single `siteDescription` (trimmed). Do not invent details the user did not provide. Do not call this tool until both fields are confirmed by the user. The project is created with the default theme, starter pages, and a default project contact form. After creation, if the business context suggests better contact fields, call get_contact_form_settings, propose the contact form plan to the user, and only call update_contact_form_settings with confirm:true after they agree. No in-app AI site generation is triggered \u2014 drive page content afterwards via create_page_draft using the returned projectId.",
2947
- inputSchema: {
2948
- name: createProjectInputSchema.shape.name.describe(
2949
- "Website or brand name confirmed by the user in a dedicated turn. Used as the project name and site title."
2950
- ),
2951
- siteDescription: createProjectInputSchema.shape.siteDescription.describe(
2952
- "Business introduction the user provided, possibly across multiple turns, then concatenated and trimmed. Captures what the site is about and who it serves. Used to seed default site metadata."
2953
- )
2954
- },
2955
- outputSchema: createProjectOutputSchema.shape
2956
- },
2957
- async ({ name, siteDescription }) => {
2958
- const result = await createAgentProject({ name, siteDescription });
2959
- const structuredContent = createProjectOutputSchema.parse({
2960
- projectId: result.projectId,
2961
- name: result.name,
2962
- defaultDomain: result.defaultDomain,
2963
- dashboardUrl: result.dashboardUrl
2964
- });
2965
- return mcpStructured("Created Suda project.", structuredContent);
2966
- }
2967
- );
2968
- server.registerTool(
2969
- "list_themes",
2970
- {
2971
- description: "List themes visible to the current Suda CLI user.",
2972
- inputSchema: {
2973
- projectId: z.string().optional(),
2974
- themeRoot: z.string().optional()
2975
- },
2976
- outputSchema: {
2977
- themes: z.array(
2978
- z.object({
2979
- key: z.string(),
2980
- name: z.string(),
2981
- version: z.string(),
2982
- description: z.string().nullable().optional(),
2983
- categories: z.array(z.string()).optional(),
2984
- preview: z.string().optional(),
2985
- active: z.boolean().optional()
2986
- })
2987
- )
2988
- }
2989
- },
2990
- async ({ projectId, themeRoot }) => {
2991
- const structuredContent = { themes: await listAgentThemes({ projectId, themeRoot }) };
2992
- return mcpStructured("Available Suda themes.", structuredContent);
2993
- }
2994
- );
2995
- server.registerTool(
2996
- "describe_theme",
2997
- {
2998
- description: "Return the raw Suda agent manifest for a theme.",
2999
- inputSchema: {
3000
- theme: z.string(),
3001
- version: z.string().optional(),
3002
- projectId: z.string().optional(),
3003
- themeRoot: z.string().optional()
3004
- },
3005
- outputSchema: {
3006
- agentManifest: z.unknown()
3007
- }
3008
- },
3009
- async ({ theme, version, projectId, themeRoot }) => {
3010
- const structuredContent = {
3011
- agentManifest: await fetchAgentManifest(theme, { version, projectId, themeRoot })
3012
- };
3013
- return mcpStructured("Raw Suda theme agent manifest.", structuredContent);
3014
- }
3015
- );
3016
- server.registerTool(
3017
- "get_page_schema",
3018
- {
3019
- description: "Return the schema for configuring existing Suda theme sections as page content. Use only the returned section types, fields, defaultProps, and slot allowedComponents; never create theme source code or new component types. If the theme has a contact section, generate only the section placement/content props; public form fields and delivery integrations are project contact form settings exposed to themes as metadata.contactForm. Use get_contact_form_settings and update_contact_form_settings for user-approved contact form changes.",
3020
- inputSchema: {
3021
- theme: z.string(),
3022
- version: z.string().optional(),
3023
- projectId: z.string().optional(),
3024
- themeRoot: z.string().optional(),
3025
- includeExample: z.boolean().optional()
3026
- },
3027
- outputSchema: agentPageSchemaOutputSchema.shape
3028
- },
3029
- async ({ theme, version, projectId, themeRoot, includeExample }) => {
3030
- const manifest = await fetchAgentManifest(theme, { version, projectId, themeRoot });
3031
- const structuredContent = createSudaPageAgentRuntime(manifest).getPageSchemaOutput({
3032
- includeExample: includeExample === true
3033
- });
3034
- return mcpStructured("Suda page content configuration schema.", structuredContent);
3035
- }
3036
- );
3037
- server.registerTool(
3038
- "get_section_schema",
3039
- {
3040
- description: "Return the schema for configuring one existing section in a theme. Use the returned fields, defaultProps, and slot allowedComponents to set props; do not design or add theme components. For contact sections, use the schema for presentation props only and do not hardcode form field metadata, notification channels, webhook URLs, or recipients into page content. Use contact form tools for project-level contact settings.",
3041
- inputSchema: {
3042
- theme: z.string(),
3043
- section: z.string(),
3044
- version: z.string().optional(),
3045
- projectId: z.string().optional(),
3046
- themeRoot: z.string().optional()
3047
- },
3048
- outputSchema: agentComponentOutputSchema.shape
3049
- },
3050
- async ({ theme, section, version, projectId, themeRoot }) => {
3051
- const manifest = await fetchAgentManifest(theme, { version, projectId, themeRoot });
3052
- const structuredContent = createSectionSchema(manifest, section);
3053
- return mcpStructured("Suda section configuration schema.", structuredContent);
3054
- }
3055
- );
3056
- server.registerTool(
3057
- "validate_page_config",
3058
- {
3059
- description: "Validate Suda page content JSON against an existing theme schema.",
3060
- inputSchema: {
3061
- theme: z.string(),
3062
- data: z.unknown(),
3063
- version: z.string().optional(),
3064
- projectId: z.string().optional(),
3065
- themeRoot: z.string().optional()
3066
- },
3067
- outputSchema: agentValidationResultSchema.shape
3068
- },
3069
- async ({ theme, data, version, projectId, themeRoot }) => {
3070
- const manifest = await fetchAgentManifest(theme, { version, projectId, themeRoot });
3071
- const structuredContent = agentValidationResultSchema.parse(
3072
- createSudaPageAgentRuntime(manifest).validatePageContent(data)
3073
- );
3074
- return mcpStructured("Suda page content validation result.", structuredContent);
3075
- }
3076
- );
3077
- server.registerTool(
3078
- "get_contact_form_settings",
3079
- {
3080
- description: "Read project contact form settings. Use this before planning contact form changes. The result includes editable field metadata, masked notification/webhook URLs, and plan features/limits. Secrets are never returned.",
3081
- inputSchema: {
3082
- projectId: z.string()
3083
- },
3084
- outputSchema: contactFormOutputSchema.shape
3085
- },
3086
- async ({ projectId }) => {
3087
- const auth = await requireCliBaseUrl();
3088
- const structuredContent = contactFormOutputSchema.parse({
3089
- contactForm: await getRemoteContactForm(auth, projectId)
3090
- });
3091
- return mcpStructured("Suda contact form settings.", structuredContent);
3092
- }
3093
- );
3094
- server.registerTool(
3095
- "update_contact_form_settings",
3096
- {
3097
- description: "Plan or update project contact form settings. Use this when the user asks to change contact form fields, labels, validation, notification channels, or webhooks. Supported field types are text, textarea, checkbox, radio, and select. Conversation flow: first call get_contact_form_settings, then propose the exact draft to the user. Call this tool without confirm or with confirm:false to return the impact summary; only call again with confirm:true after the user explicitly agrees. Do not invent webhook URLs, notification recipients, or external delivery secrets. When updating an existing webhook, omit url to keep the stored secret; new webhooks need a user-provided url.",
3098
- inputSchema: updateContactFormInputSchema.shape,
3099
- outputSchema: {
3100
- status: z.enum(["needs_confirmation", "updated"]),
3101
- projectId: z.string(),
3102
- impact: z.string().optional(),
3103
- draft: updateContactFormInputSchema.omit({ confirm: true }).optional(),
3104
- contactForm: contactFormViewSchema.optional()
3105
- }
3106
- },
3107
- async (input) => {
3108
- const parsed = updateContactFormInputSchema.parse(input);
3109
- const auth = await requireCliBaseUrl();
3110
- const structuredContent = updateContactFormOutputSchema.parse(
3111
- await performUpdateContactForm(auth, parsed)
3112
- );
3113
- return mcpStructured(
3114
- structuredContent.status === "needs_confirmation" ? "Updating this contact form requires explicit confirmation." : "Updated Suda contact form settings.",
3115
- structuredContent
3116
- );
3117
- }
3118
- );
3119
- server.registerTool(
3120
- "get_theme_settings",
3121
- {
3122
- description: 'Read project theme layout root settings. Use this before planning theme style changes. The result includes manifest.designSystem presets, current rootProps, and the layout root schema. To use a preset, set rootProps.designSystem to { presetId }. To fully customize colors/radius, set rootProps.designSystem to { presetId: "custom", tokens: { colors, radius } } using every token from designSystem.',
3123
- inputSchema: {
3124
- projectId: z.string()
3125
- },
3126
- outputSchema: themeSettingsOutputSchema.shape
3127
- },
3128
- async ({ projectId }) => {
3129
- const auth = await requireCliBaseUrl();
3130
- const structuredContent = themeSettingsOutputSchema.parse({
3131
- themeSettings: await getRemoteThemeSettings(auth, projectId)
3132
- });
3133
- return mcpStructured("Suda theme settings.", structuredContent);
3134
- }
3135
- );
3136
- server.registerTool(
3137
- "update_theme_settings",
3138
- {
3139
- description: "Plan or update project theme layout root settings. Use this for choosing a designSystem preset or saving custom design tokens for colors and radius. Conversation flow: first call get_theme_settings, then propose the exact rootProps changes to the user. Call this tool without confirm or with confirm:false to return the impact summary; only call again with confirm:true after the user explicitly agrees. Do not create theme source code or introduce a second token system.",
3140
- inputSchema: updateThemeSettingsInputSchema.shape,
3141
- outputSchema: {
3142
- status: z.enum(["needs_confirmation", "updated"]),
3143
- projectId: z.string(),
3144
- impact: z.string().optional(),
3145
- draft: updateThemeSettingsInputSchema.omit({ confirm: true }).optional(),
3146
- themeSettings: themeSettingsViewSchema.optional()
3147
- }
3148
- },
3149
- async (input) => {
3150
- const parsed = updateThemeSettingsInputSchema.parse(input);
3151
- const auth = await requireCliBaseUrl();
3152
- const structuredContent = updateThemeSettingsOutputSchema.parse(
3153
- await performUpdateThemeSettings(auth, parsed)
3154
- );
3155
- return mcpStructured(
3156
- structuredContent.status === "needs_confirmation" ? "Updating these theme settings requires explicit confirmation." : "Updated Suda theme settings.",
3157
- structuredContent
3158
- );
3159
- }
3160
- );
3161
- server.registerTool(
3162
- "create_page_draft",
3163
- {
3164
- description: "Create a new workspace page draft from Suda page content JSON that configures existing theme sections. When creating a complete website, mark exactly one primary landing page with isHome: true so it becomes the public homepage at `/`. After this tool succeeds, tell the user the page is only a draft, explain that they can review it in the SudaCloud workspace by navigating to Pages, opening the created page, previewing it, then clicking Publish, and ask whether they want you to publish it now. Do not call publish_page until the user explicitly confirms.",
3165
- inputSchema: {
3166
- projectId: z.string(),
3167
- title: z.string(),
3168
- slug: z.string(),
3169
- isHome: z.boolean().optional().describe("Set true for exactly one page that should serve as the public homepage at `/`."),
3170
- theme: z.string(),
3171
- data: z.unknown(),
3172
- version: z.string().optional()
3173
- },
3174
- outputSchema: createPageDraftOutputSchema
3175
- },
3176
- async ({ projectId, title, slug, isHome, theme, data, version }) => {
3177
- const manifest = await fetchAgentManifest(theme, { version, projectId });
3178
- const prepared = createSudaPageAgentRuntime(manifest).preparePageData(data);
3179
- if (!prepared.validation.valid) {
3180
- return mcpStructured(
3181
- "Suda page content validation failed. Fix issues before creating a draft.",
3182
- createPageDraftOutputSchema.parse({
3183
- status: "invalid",
3184
- valid: false,
3185
- issues: prepared.validation.issues
3186
- })
3187
- );
3188
- }
3189
- const auth = await requireCliBaseUrl();
3190
- const response = await createRemotePageDraft(auth, {
3191
- projectId,
3192
- title,
3193
- slug,
3194
- isHome,
3195
- themeKey: manifest.manifest.key,
3196
- themeVersion: manifest.manifest.version,
3197
- data
3198
- });
3199
- return mcpStructured(
3200
- "Created Suda page draft. Tell the user they can review it in the SudaCloud workspace under Pages by opening the created page, previewing it, then clicking Publish. Ask whether they want you to publish it now before calling publish_page.",
3201
- createPageDraftOutputSchema.parse({ status: "created", ...response })
3202
- );
3203
- }
3204
- );
3205
- server.registerTool(
3206
- "update_page_draft",
3207
- {
3208
- description: "Update an existing workspace page draft by slug from Suda page content JSON that configures existing theme sections.",
3209
- inputSchema: {
3210
- projectId: z.string(),
3211
- slug: z.string(),
3212
- theme: z.string(),
3213
- data: z.unknown(),
3214
- version: z.string().optional()
3215
- },
3216
- outputSchema: updatePageDraftOutputSchema
3217
- },
3218
- async ({ projectId, slug, theme, data, version }) => {
3219
- const manifest = await fetchAgentManifest(theme, { version, projectId });
3220
- const prepared = createSudaPageAgentRuntime(manifest).preparePageData(data);
3221
- if (!prepared.validation.valid) {
3222
- return mcpStructured(
3223
- "Suda page content validation failed. Fix issues before updating a draft.",
3224
- updatePageDraftOutputSchema.parse({
3225
- status: "invalid",
3226
- valid: false,
3227
- issues: prepared.validation.issues
3228
- })
3229
- );
3230
- }
3231
- const auth = await requireCliBaseUrl();
3232
- const response = await updateRemotePageDraft(auth, {
3233
- projectId,
3234
- slug,
3235
- themeKey: manifest.manifest.key,
3236
- themeVersion: manifest.manifest.version,
3237
- data
3238
- });
3239
- return mcpStructured(
3240
- "Updated Suda page draft.",
3241
- updatePageDraftOutputSchema.parse({ status: "updated", ...response })
3242
- );
3243
- }
3244
- );
3245
- server.registerTool(
3246
- "delete_page",
3247
- {
3248
- description: "Delete a Suda page by slug. This is destructive: first call without confirm to get the exact project, slug, and impact; only call again with confirm: true after the user explicitly agrees.",
3249
- inputSchema: {
3250
- projectId: z.string(),
3251
- slug: z.string(),
3252
- confirm: z.boolean().optional()
3253
- },
3254
- outputSchema: destructivePageOperationOutputSchema
3255
- },
3256
- async ({ projectId, slug, confirm }) => {
3257
- const auth = await requireCliBaseUrl();
3258
- const structuredContent = destructivePageOperationOutputSchema.parse(
3259
- await performConfirmedPageOperation(auth, {
3260
- operation: "delete",
3261
- projectId,
3262
- slug,
3263
- confirm
3264
- })
3265
- );
3266
- return mcpStructured(
3267
- structuredContent.status === "needs_confirmation" ? "Deleting this Suda page requires explicit confirmation." : "Deleted Suda page.",
3268
- structuredContent
3269
- );
3270
- }
3271
- );
3272
- server.registerTool(
3273
- "publish_page",
3274
- {
3275
- description: "Publish the current saved draft for a Suda page by slug. This affects the public site: first call without confirm to get the exact project, slug, and impact; only call again with confirm: true after the user explicitly agrees. If the user wants to review manually first, tell them to open the SudaCloud workspace, navigate to Pages, open the created page, preview it, then click Publish.",
3276
- inputSchema: {
3277
- projectId: z.string(),
3278
- slug: z.string(),
3279
- confirm: z.boolean().optional()
3280
- },
3281
- outputSchema: destructivePageOperationOutputSchema
3282
- },
3283
- async ({ projectId, slug, confirm }) => {
3284
- const auth = await requireCliBaseUrl();
3285
- const structuredContent = destructivePageOperationOutputSchema.parse(
3286
- await performConfirmedPageOperation(auth, {
3287
- operation: "publish",
3288
- projectId,
3289
- slug,
3290
- confirm
3291
- })
3292
- );
3293
- return mcpStructured(
3294
- structuredContent.status === "needs_confirmation" ? "Publishing this Suda page requires explicit confirmation." : "Published Suda page.",
3295
- structuredContent
3296
- );
3297
- }
3298
- );
3299
- server.registerTool(
3300
- "activate_theme",
3301
- {
3302
- description: "Activate a theme for a Suda project. This affects how public pages render and may seed starter content on first activation: first call without confirm to get the exact project, theme, and impact; only call again with confirm: true after the user explicitly agrees.",
3303
- inputSchema: {
3304
- projectId: z.string(),
3305
- themeKey: z.string(),
3306
- themeVersion: z.string().optional(),
3307
- confirm: z.boolean().optional()
3308
- },
3309
- outputSchema: activateThemeOutputSchema
3310
- },
3311
- async ({ projectId, themeKey, themeVersion, confirm }) => {
3312
- const auth = await requireCliBaseUrl();
3313
- const structuredContent = activateThemeOutputSchema.parse(
3314
- await performActivateTheme(auth, {
3315
- projectId,
3316
- themeKey,
3317
- themeVersion,
3318
- confirm
3319
- })
3320
- );
3321
- return mcpStructured(
3322
- structuredContent.status === "needs_confirmation" ? "Activating this Suda theme requires explicit confirmation." : "Activated Suda theme.",
3323
- structuredContent
3324
- );
3325
- }
3326
- );
3327
- await server.connect(new StdioServerTransport());
3328
- }
3329
3313
  async function writeThemeArtifacts(theme) {
3330
3314
  const dist = path2.join(theme.root, "dist");
3331
3315
  const agentManifest = createThemeAgentManifest(theme.module);
@@ -3816,6 +3800,24 @@ function buildProgram() {
3816
3800
  ).option("--output <path>", "Output PNG path relative to theme root. Requires exactly one device.").option("--width <px>", "Override viewport width in pixels.").option("--height <px>", "Override viewport height in pixels.").option("--full-page", "Capture the full page instead of the viewport.").option("--port <port>", "Preview server port used during capture.", "4178").action(async (options) => {
3817
3801
  await screenshotTheme(resolveThemeRoot(options), options);
3818
3802
  });
3803
+ theme.command("visual-check").description(
3804
+ "Render every theme page component across presets and viewports, then report token contrast, semantic surface colors, overflow, and layout overlays."
3805
+ ).option("--theme-root <path>", "Theme source/artifact root.").option(
3806
+ "--device <device>",
3807
+ "Device to audit: desktop, tablet, mobile. Repeat or use comma-separated values.",
3808
+ collectOption,
3809
+ []
3810
+ ).option(
3811
+ "--preset <id>",
3812
+ "Design preset to audit. Repeat or use comma-separated values; defaults to every theme preset.",
3813
+ collectOption,
3814
+ []
3815
+ ).option("--output <path>", "Output directory relative to theme root.").option("--full-page", "Capture full-page screenshots instead of viewport screenshots.").option("--port <port>", "Preview server port used during visual checking.", "4179").action(async (options) => {
3816
+ const ok = await runThemeVisualCheck(resolveThemeRoot(options), options);
3817
+ if (!ok) {
3818
+ process.exitCode = 1;
3819
+ }
3820
+ });
3819
3821
  theme.command("publish").description("Upload artifact to S3 and upsert ThemePackage/ThemeVersion.").option("--theme-root <path>", "Theme source/artifact root.").option("--skip-build", "Publish existing dist files without rebuilding.").option("--host <host>", "Publish to this authenticated SudaCloud workspace host.").option(
3820
3822
  "--force",
3821
3823
  "Development recovery only: clear the existing themes/<key>/<version>/ prefix and ThemeVersion row before republishing. Re-published clients pinned to this version are unavailable until the new publish completes."
@@ -3887,9 +3889,6 @@ function buildProgram() {
3887
3889
  const manifest = await fetchAgentManifest(options.theme, options);
3888
3890
  printJson(createSectionSchema(manifest, options.section));
3889
3891
  });
3890
- program.command("mcp").description("Run the Suda local MCP server over stdio.").action(async () => {
3891
- await startMcpServer();
3892
- });
3893
3892
  const hostCmd = program.command("host").description("Manage the current SudaCloud workspace host.");
3894
3893
  hostCmd.command("current").description("Show the current authenticated workspace host.").action(async () => {
3895
3894
  await showCurrentHost();