Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

feat: Improve MCP project audits, visual verification, and dynamic content authoring (#5874)

Oleg Isonend186d24501b0
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-general.tsx b/apps/builder/app/builder/features/pages/page-settings/section-general.tsx
index cd6145fe66..d6fc8a3e26 100644
--- a/apps/builder/app/builder/features/pages/page-settings/section-general.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/section-general.tsx
@@ -33,7 +33,7 @@ import type {
PageSettingsErrors,
PageSettingsValues,
} from "@webstudio-is/project-build/runtime/pages";
-import type { OnChange } from "./shared";
+import { computePageSettingsText, type OnChange } from "./shared";
const autoSelectHandler: FocusEventHandler<HTMLInputElement> = (event) =>
event.target.select();
@@ -268,7 +268,7 @@ const RedirectField = ({
id={id}
placeholder="/another-path"
disabled={disabled || isLiteralExpression(value) === false}
- value={String(computeExpression(value, variableValues))}
+ value={computePageSettingsText(value, variableValues)}
onChange={(event) => onChange(JSON.stringify(event.target.value))}
/>
</InputErrorsTooltip>
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx b/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx
index 2387c096dd..e3d669bd7b 100644
--- a/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx
@@ -9,13 +9,12 @@ import {
Switch,
theme,
} from "@webstudio-is/design-system";
-import { computeExpression } from "@webstudio-is/project-build/runtime/data";
import { ImageControl } from "~/shared/project-settings";
import { $assets } from "~/shared/sync/data-stores";
import { Card } from "../../marketplace/card";
import { ImageInfo } from "../image-info";
import type { PageSettingsValues } from "@webstudio-is/project-build/runtime/pages";
-import type { OnChange } from "./shared";
+import { computePageSettingsText, type OnChange } from "./shared";
export const MarketplaceSection = ({
values,
@@ -30,10 +29,11 @@ export const MarketplaceSection = ({
({ property }) => property === "ws:category"
);
// @todo remove after all stores are migrated
- const categoryFallback = String(
- computeExpression(categoryMeta?.content ?? `""`, new Map())
+ const categoryFallback = computePageSettingsText(
+ categoryMeta?.content ?? `""`,
+ new Map()
);
- const category = values.marketplace.category ?? categoryFallback ?? "Pages";
+ const category = values.marketplace.category || categoryFallback || "Pages";
const assets = useStore($assets);
const thumbnailAsset = assets.get(values.marketplace.thumbnailAssetId);
const thumnailFallbackAsset = assets.get(values.socialImageAssetId);
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-search.tsx b/apps/builder/app/builder/features/pages/page-settings/section-search.tsx
index 91d911ab1d..38444b13e8 100644
--- a/apps/builder/app/builder/features/pages/page-settings/section-search.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/section-search.tsx
@@ -24,7 +24,7 @@ import { useStore } from "@nanostores/react";
import { $assets, $projectSettings } from "~/shared/sync/data-stores";
import { $pageRootScope } from "../page-utils";
import { SearchPreview } from "../search-preview";
-import { usePageUrl, type OnChange } from "./shared";
+import { computePageSettingsText, usePageUrl, type OnChange } from "./shared";
const LanguageField = ({
errors,
@@ -63,7 +63,7 @@ const LanguageField = ({
id={id}
placeholder="en-US"
disabled={disabled || isLiteralExpression(value) === false}
- value={String(computeExpression(value, variableValues))}
+ value={computePageSettingsText(value, variableValues)}
onChange={(event) => onChange(JSON.stringify(event.target.value))}
/>
</InputErrorsTooltip>
@@ -100,9 +100,10 @@ export const SearchSection = ({
const pageUrl = usePageUrl(values);
const faviconAsset = assets.get(projectSettings?.meta.faviconAssetId ?? "");
const faviconUrl = faviconAsset?.type === "image" ? faviconAsset.name : "";
- const title = String(computeExpression(values.title, variableValues));
- const description = String(
- computeExpression(values.description, variableValues)
+ const title = computePageSettingsText(values.title, variableValues);
+ const description = computePageSettingsText(
+ values.description,
+ variableValues
);
const excludePageFromSearch = Boolean(
computeExpression(values.excludePageFromSearch, variableValues)
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx b/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx
index ff0d394cc8..bb9cd67a9a 100644
--- a/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx
@@ -11,7 +11,6 @@ import {
BindingControl,
BindingPopover,
} from "~/builder/shared/binding-popover";
-import { computeExpression } from "@webstudio-is/project-build/runtime/data";
import type {
PageSettingsErrors,
PageSettingsValues,
@@ -22,7 +21,7 @@ import { isLiteralExpression } from "@webstudio-is/sdk";
import { $pageRootScope } from "../page-utils";
import { ImageInfo } from "../image-info";
import { SocialPreview } from "../social-preview";
-import { usePageUrl, type OnChange } from "./shared";
+import { computePageSettingsText, usePageUrl, type OnChange } from "./shared";
export const SocialImageSection = ({
values,
@@ -41,13 +40,15 @@ export const SocialImageSection = ({
const assets = useStore($assets);
const socialImageAsset = assets.get(values.socialImageAssetId);
const { variableValues, scope, aliases } = useStore($pageRootScope);
- const socialImageUrl = String(
- computeExpression(values.socialImageUrl, variableValues)
+ const socialImageUrl = computePageSettingsText(
+ values.socialImageUrl,
+ variableValues
);
const pageUrl = usePageUrl(values);
- const title = String(computeExpression(values.title, variableValues));
- const description = String(
- computeExpression(values.description, variableValues)
+ const title = computePageSettingsText(values.title, variableValues);
+ const description = computePageSettingsText(
+ values.description,
+ variableValues
);
return (
<Grid gap={2}>
diff --git a/apps/builder/app/builder/features/pages/page-settings/shared.test.ts b/apps/builder/app/builder/features/pages/page-settings/shared.test.ts
new file mode 100644
index 0000000000..3fb88ddc03
--- /dev/null
+++ b/apps/builder/app/builder/features/pages/page-settings/shared.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, test } from "vitest";
+import { computePageSettingsText } from "./shared";
+
+describe("computePageSettingsText", () => {
+ test("renders literal and computed values as text", () => {
+ expect(computePageSettingsText(`"Page title"`, new Map())).toBe(
+ "Page title"
+ );
+ expect(computePageSettingsText("42", new Map())).toBe("42");
+ });
+
+ test("does not expose missing expression values as text", () => {
+ expect(computePageSettingsText("missingVariable", new Map())).toBe("");
+ expect(computePageSettingsText("null", new Map())).toBe("");
+ });
+});
diff --git a/apps/builder/app/builder/features/pages/page-settings/shared.ts b/apps/builder/app/builder/features/pages/page-settings/shared.ts
index ea5fb62878..9b47895bbb 100644
--- a/apps/builder/app/builder/features/pages/page-settings/shared.ts
+++ b/apps/builder/app/builder/features/pages/page-settings/shared.ts
@@ -1,6 +1,7 @@
import { useStore } from "@nanostores/react";
import { getPagePath } from "@webstudio-is/sdk";
import type { PageSettingsValues } from "@webstudio-is/project-build/runtime/pages";
+import { computeExpression } from "@webstudio-is/project-build/runtime/data";
import {
compilePathnamePattern,
tokenizePathnamePattern,
@@ -18,6 +19,14 @@ export type OnChange = (
}[keyof PageSettingsValues]
) => void;
+export const computePageSettingsText = (
+ expression: string,
+ variables: Map<string, unknown>
+) => {
+ const value = computeExpression(expression, variables);
+ return value === undefined || value === null ? "" : String(value);
+};
+
export const usePageUrl = (values: PageSettingsValues) => {
const pages = useStore($pages);
let path = "";
diff --git a/apps/builder/app/services/api-router.server.test.ts b/apps/builder/app/services/api-router.server.test.ts
index 3da001c450..3db3ffbcd7 100644
--- a/apps/builder/app/services/api-router.server.test.ts
+++ b/apps/builder/app/services/api-router.server.test.ts
@@ -8,6 +8,8 @@ import * as projectBuild from "@webstudio-is/project-build/index.server";
import * as projectApi from "@webstudio-is/project/index.server";
import {
buildPatchTransaction,
+ publicApiContractVersion,
+ publicApiOperationRequiresServerSupport,
publicApiOperations,
} from "@webstudio-is/protocol";
import {
@@ -286,6 +288,14 @@ describe("api router permits", () => {
canPublish: false,
canPublishProjectDomain: false,
canPublishCustomDomains: false,
+ apiContract: {
+ version: publicApiContractVersion,
+ operationIds: publicApiOperations.flatMap((operation) =>
+ publicApiOperationRequiresServerSupport(operation)
+ ? [operation.id]
+ : []
+ ),
+ },
});
});
diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.ts
index a044a05ea7..55f1b2ce7c 100644
--- a/apps/builder/app/services/api-router.server.ts
+++ b/apps/builder/app/services/api-router.server.ts
@@ -25,6 +25,11 @@ import {
import { getBuilderRuntimeOperationInputSchema } from "@webstudio-is/project-build/runtime/registry";
import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";
import { buildPatchTransaction } from "@webstudio-is/protocol/schema";
+import {
+ publicApiContractVersion,
+ publicApiOperationRequiresServerSupport,
+ publicApiOperations,
+} from "@webstudio-is/protocol";
import {
assertApiProjectPermit,
getTokenPermits,
@@ -554,6 +559,14 @@ export const apiRouter = router({
canPublishProjectDomain:
token.canPublish === true || token.relation === "builders",
canPublishCustomDomains: token.canPublish === true,
+ apiContract: {
+ version: publicApiContractVersion,
+ operationIds: publicApiOperations.flatMap((operation) =>
+ publicApiOperationRequiresServerSupport(operation)
+ ? [operation.id]
+ : []
+ ),
+ },
};
}),
diff --git a/apps/builder/app/shared/polly/types.ts b/apps/builder/app/shared/polly/types.ts
index b922d5b741..f77bcfee80 100644
--- a/apps/builder/app/shared/polly/types.ts
+++ b/apps/builder/app/shared/polly/types.ts
@@ -58,7 +58,7 @@ export const topicNames = [
// Compile-time check: every `TopicRegistry` key must appear in `topicNames`.
// If you add a topic to the registry but forget `topicNames`, this line errors.
-// prettier-ignore
+// oxfmt-ignore
type EnsureAllTopicsCovered =
Exclude<TopicName, (typeof topicNames)[number]> extends never
? true
diff --git a/apps/builder/e2e/fixtures/content-mode-project.ts b/apps/builder/e2e/fixtures/content-mode-project.ts
index 9a66643ff4..5f9aa1ef45 100644
--- a/apps/builder/e2e/fixtures/content-mode-project.ts
+++ b/apps/builder/e2e/fixtures/content-mode-project.ts
@@ -874,8 +874,8 @@ const createContentModeBuildData = ({
export const prepareExistingContentModeProject = async ({
projectId,
- editorToken = "e2e-editor-token",
- builderToken = "e2e-builder-token",
+ editorToken: editorTokenLabel = "e2e-editor-token",
+ builderToken: builderTokenLabel = "e2e-builder-token",
listItemInstanceId = "list-item",
linkInstanceId = "content-link",
imageInstanceId = "content-image",
@@ -892,10 +892,13 @@ export const prepareExistingContentModeProject = async ({
assetNamePrefix?: string;
}): Promise<SeededContentModeProject> => {
const build = await loadDevBuild({ projectId });
- const seededAssetTemplateImageName = `${assetNamePrefix}${assetTemplateImageName}`;
- const seededAssetTemplateVideoName = `${assetNamePrefix}${assetTemplateVideoName}`;
- const seededAssetTemplateImageAssetId = `${assetNamePrefix}${assetTemplateImageAssetId}`;
- const seededAssetTemplateVideoAssetId = `${assetNamePrefix}${assetTemplateVideoAssetId}`;
+ const fixturePrefix = `${projectId}-${assetNamePrefix}`;
+ const editorToken = `${projectId}-${editorTokenLabel}`;
+ const builderToken = `${projectId}-${builderTokenLabel}`;
+ const seededAssetTemplateImageName = `${fixturePrefix}${assetTemplateImageName}`;
+ const seededAssetTemplateVideoName = `${fixturePrefix}${assetTemplateVideoName}`;
+ const seededAssetTemplateImageAssetId = `${fixturePrefix}${assetTemplateImageAssetId}`;
+ const seededAssetTemplateVideoAssetId = `${fixturePrefix}${assetTemplateVideoAssetId}`;
await Promise.all([
insertFile({
diff --git a/apps/builder/e2e/fixtures/content-mode-suite.ts b/apps/builder/e2e/fixtures/content-mode-suite.ts
index 38def19760..ba21daa1a5 100644
--- a/apps/builder/e2e/fixtures/content-mode-suite.ts
+++ b/apps/builder/e2e/fixtures/content-mode-suite.ts
@@ -1,5 +1,5 @@
import { loginAndCreateBlankProject } from "../flows/dashboard";
-import { newPage } from "../harness";
+import { getBrowserScopeKey, newPage } from "../harness";
import { measure } from "../perf";
import {
prepareExistingContentModeProject,
@@ -15,7 +15,7 @@ type ContentModeProjectOptions = {
builderToken?: string;
};
-let sharedProject: SeededContentModeProject | undefined;
+const sharedProjects = new WeakMap<object, SeededContentModeProject>();
export const createContentModeProject = async ({
email = "[email protected]",
@@ -55,11 +55,13 @@ export const createContentModeProject = async ({
export const setupSharedContentModeProject = async (
options?: ContentModeProjectOptions
) => {
- sharedProject = await createContentModeProject(options);
- return sharedProject;
+ const project = await createContentModeProject(options);
+ sharedProjects.set(getBrowserScopeKey(), project);
+ return project;
};
export const getSharedContentModeProject = () => {
+ const sharedProject = sharedProjects.get(getBrowserScopeKey());
if (sharedProject === undefined) {
throw new Error("Expected shared content-mode project to be initialized");
}
diff --git a/apps/builder/e2e/harness.ts b/apps/builder/e2e/harness.ts
index 1aa72e5883..d397d9708b 100644
--- a/apps/builder/e2e/harness.ts
+++ b/apps/builder/e2e/harness.ts
@@ -115,12 +115,21 @@ export type BrowserScope = {
};
type BrowserScopeState = {
+ scopeKey: object;
context: BrowserContext;
isolatedContexts: Set<BrowserContext>;
};
const browserScopeStorage = new AsyncLocalStorage<BrowserScopeState>();
+export const getBrowserScopeKey = () => {
+ const scopeKey = browserScopeStorage.getStore()?.scopeKey;
+ if (scopeKey === undefined) {
+ throw new Error("Expected an active browser scope");
+ }
+ return scopeKey;
+};
+
const browserContextOptions: BrowserContextOptions = {
ignoreHTTPSErrors: true,
permissions: ["clipboard-read", "clipboard-write"],
@@ -157,8 +166,10 @@ export const stopBrowser = async () => {
export const createBrowserScopeForBrowser = async (
browserInstance: Pick<Browser, "newContext">
): Promise<BrowserScope> => {
+ const scopeKey = {};
const createState = async (): Promise<BrowserScopeState> => {
return {
+ scopeKey,
context: await browserInstance.newContext(browserContextOptions),
isolatedContexts: new Set(),
};
diff --git a/apps/builder/e2e/process.test.ts b/apps/builder/e2e/process.test.ts
index c2f56399c3..7aea90a2d1 100644
--- a/apps/builder/e2e/process.test.ts
+++ b/apps/builder/e2e/process.test.ts
@@ -97,3 +97,36 @@ test.runIf(process.platform !== "win32")(
kill.mockRestore();
}
);
+
+test.runIf(process.platform !== "win32")(
+ "uses the child state when a stopped process group cannot be probed",
+ async () => {
+ const child = createChild();
+ Object.defineProperty(child, "pid", { value: 42 });
+ let signalSent = false;
+ const kill = vi
+ .spyOn(process, "kill")
+ .mockImplementation((_pid, signal) => {
+ if (signal === 0 && signalSent) {
+ throw Object.assign(new Error("Process group cannot be probed"), {
+ code: "EPERM",
+ });
+ }
+ if (signal === "SIGTERM") {
+ signalSent = true;
+ Object.defineProperty(child, "signalCode", {
+ value: signal,
+ writable: true,
+ });
+ child.emit("exit", null, signal);
+ }
+ return true;
+ });
+
+ await stopChildProcess(child, { killGroup: true, timeoutMs: 1 });
+
+ expect(kill).toHaveBeenCalledWith(-42, "SIGTERM");
+ expect(child.kill).not.toHaveBeenCalled();
+ kill.mockRestore();
+ }
+);
diff --git a/apps/builder/e2e/process.ts b/apps/builder/e2e/process.ts
index 6aae427a80..8f63beb4bd 100644
--- a/apps/builder/e2e/process.ts
+++ b/apps/builder/e2e/process.ts
@@ -6,14 +6,18 @@ const delay = (milliseconds: number) =>
const hasExited = (child: ChildProcess) =>
child.exitCode !== null || child.signalCode !== null;
-const isProcessGroupRunning = (pid: number) => {
+const isProcessGroupRunning = (child: ChildProcess, pid: number) => {
try {
process.kill(-pid, 0);
return true;
} catch (error) {
- if ((error as NodeJS.ErrnoException).code === "ESRCH") {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === "ESRCH") {
return false;
}
+ if (code === "EPERM") {
+ return hasExited(child) === false;
+ }
throw error;
}
};
@@ -29,7 +33,7 @@ export const stopChildProcess = async (
killGroup && process.platform !== "win32" && child.pid !== undefined;
const isRunning = () =>
usesProcessGroup
- ? isProcessGroupRunning(child.pid as number)
+ ? isProcessGroupRunning(child, child.pid as number)
: hasExited(child) === false;
const waitUntilStopped = async () => {
const deadline = Date.now() + timeoutMs;
diff --git a/fixtures/README.md b/fixtures/README.md
index 2907ee380f..302409a780 100644
--- a/fixtures/README.md
+++ b/fixtures/README.md
@@ -54,7 +54,7 @@ To add a new asset (image, video, audio, etc.) to a fixture:
- Update the `--buildId` parameter in the `fixtures:sync` script
```json
- "fixtures:sync": "pnpm cli sync --buildId NEW_BUILD_ID_HERE && pnpm prettier --write ./.webstudio/"
+ "fixtures:sync": "pnpm cli sync --buildId NEW_BUILD_ID_HERE && pnpm oxfmt ./.webstudio/"
```
4. **Sync with the correct environment**
diff --git a/fixtures/react-router-cloudflare/package.json b/fixtures/react-router-cloudflare/package.json
index 97950786d1..81f3714831 100644
--- a/fixtures/react-router-cloudflare/package.json
+++ b/fixtures/react-router-cloudflare/package.json
@@ -42,7 +42,7 @@
"devDependencies": {
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
- "typescript": "5.8.2"
+ "typescript": "7.0.2"
},
"engines": {
"node": ">=22"
diff --git a/fixtures/react-router-docker/package.json b/fixtures/react-router-docker/package.json
index 1f290a3e8c..2ebb1dc003 100644
--- a/fixtures/react-router-docker/package.json
+++ b/fixtures/react-router-docker/package.json
@@ -37,7 +37,7 @@
"devDependencies": {
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
- "typescript": "5.8.2"
+ "typescript": "7.0.2"
},
"engines": {
"node": ">=22"
diff --git a/fixtures/react-router-netlify/package.json b/fixtures/react-router-netlify/package.json
index 09840aeae3..ec470c398f 100644
--- a/fixtures/react-router-netlify/package.json
+++ b/fixtures/react-router-netlify/package.json
@@ -39,7 +39,7 @@
"devDependencies": {
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
- "typescript": "5.8.2"
+ "typescript": "7.0.2"
},
"engines": {
"node": ">=22"
diff --git a/fixtures/react-router-vercel/package.json b/fixtures/react-router-vercel/package.json
index b2c9bb30ef..3a3b6cade0 100644
--- a/fixtures/react-router-vercel/package.json
+++ b/fixtures/react-router-vercel/package.json
@@ -39,7 +39,7 @@
"devDependencies": {
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
- "typescript": "5.8.2"
+ "typescript": "7.0.2"
},
"engines": {
"node": ">=22"
diff --git a/fixtures/ssg-cloudflare-pages/package.json b/fixtures/ssg-cloudflare-pages/package.json
index 41d0445921..211cef7f7f 100644
--- a/fixtures/ssg-cloudflare-pages/package.json
+++ b/fixtures/ssg-cloudflare-pages/package.json
@@ -4,7 +4,7 @@
"description": "",
"scripts": {
"build": "vite build && vike prerender",
- "postbuild": "prettier --write \"dist/**/*.html\" || true",
+ "postbuild": "cd dist && oxfmt '**/*.html'",
"dev": "vite dev",
"typecheck": "tsc --noEmit",
"cli": "NODE_OPTIONS='--conditions=webstudio --import=tsx' webstudio",
@@ -27,8 +27,7 @@
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
"@vitejs/plugin-react": "^4.4.1",
- "prettier": "3.5.3",
- "typescript": "5.8.2",
+ "typescript": "7.0.2",
"vite": "^6.3.4",
"webstudio": "workspace:*"
},
diff --git a/fixtures/ssg-netlify-by-project-id/package.json b/fixtures/ssg-netlify-by-project-id/package.json
index 9430dd724f..38f26001f8 100644
--- a/fixtures/ssg-netlify-by-project-id/package.json
+++ b/fixtures/ssg-netlify-by-project-id/package.json
@@ -4,7 +4,7 @@
"description": "",
"scripts": {
"build": "vite build && vike prerender",
- "postbuild": "prettier --write \"dist/**/*.html\" || true",
+ "postbuild": "cd dist && oxfmt '**/*.html'",
"dev": "vite dev",
"typecheck": "tsc --noEmit",
"cli": "NODE_OPTIONS='--conditions=webstudio --import=tsx' webstudio",
@@ -27,8 +27,7 @@
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
"@vitejs/plugin-react": "^4.4.1",
- "prettier": "3.5.3",
- "typescript": "5.8.2",
+ "typescript": "7.0.2",
"vite": "^6.3.4",
"webstudio": "workspace:*"
},
diff --git a/fixtures/webstudio-cloudflare-template/package.json b/fixtures/webstudio-cloudflare-template/package.json
index 77c202c880..f8a39ec1ca 100644
--- a/fixtures/webstudio-cloudflare-template/package.json
+++ b/fixtures/webstudio-cloudflare-template/package.json
@@ -54,7 +54,7 @@
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
"fast-glob": "^3.3.2",
- "typescript": "5.8.2",
+ "typescript": "7.0.2",
"vite": "^6.3.4",
"wrangler": "^3.63.2"
}
diff --git a/fixtures/webstudio-features/package.json b/fixtures/webstudio-features/package.json
index 919b088b0d..e9a01b8d78 100644
--- a/fixtures/webstudio-features/package.json
+++ b/fixtures/webstudio-features/package.json
@@ -38,7 +38,7 @@
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
"fast-glob": "^3.3.2",
- "typescript": "5.8.2",
+ "typescript": "7.0.2",
"webstudio": "workspace:*"
},
"engines": {
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 8fe7505e73..32e0e5df7a 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -19,7 +19,8 @@
"typecheck": "tsc --noEmit",
"generate-docs": "tsx scripts/generate-docs.ts && oxfmt src/docs.generated.ts",
"build": "pnpm generate-docs && rm -rf lib && vite build",
- "test": "vitest run"
+ "test": "vitest run",
+ "test:release-smoke": "pnpm build && tsx --conditions=webstudio scripts/release-smoke.ts"
},
"license": "AGPL-3.0-or-later",
"engines": {
@@ -32,7 +33,6 @@
"@webstudio-is/http-client": "workspace:*",
"@webstudio-is/project-migrations": "workspace:*",
"@webstudio-is/protocol": "workspace:*",
- "@webstudio-is/sdk-components-registry": "workspace:*",
"@webstudio-is/sync-client": "workspace:*",
"acorn": "^8.14.1",
"acorn-jsx": "^5.3.2",
@@ -85,6 +85,7 @@
"@webstudio-is/sdk-components-react-radix": "workspace:*",
"@webstudio-is/sdk-components-react-remix": "workspace:*",
"@webstudio-is/sdk-components-react-router": "workspace:*",
+ "@webstudio-is/sdk-components-registry": "workspace:*",
"@webstudio-is/tsconfig": "workspace:*",
"@webstudio-is/wsauth": "workspace:*",
"h3": "^1.15.1",
@@ -94,7 +95,7 @@
"mdast-util-from-markdown": "^2.0.3",
"mdast-util-to-string": "^4.0.0",
"micromark-extension-directive": "^4.0.0",
- "prettier": "3.5.3",
+ "oxfmt": "0.58.0",
"react": "18.3.0-canary-14898b6a9-20240318",
"react-dom": "18.3.0-canary-14898b6a9-20240318",
"react-router": "^7.5.3",
diff --git a/packages/cli/scripts/release-smoke.ts b/packages/cli/scripts/release-smoke.ts
new file mode 100644
index 0000000000..daa87abb3f
--- /dev/null
+++ b/packages/cli/scripts/release-smoke.ts
@@ -0,0 +1,1304 @@
+import { execFile, spawn, type ChildProcess } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import { createServer, type Server } from "node:http";
+import {
+ cp,
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ writeFile,
+} from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { promisify } from "node:util";
+import {
+ bundleVersion,
+ publicApiContractVersion,
+ publicApiOperationRequiresServerSupport,
+ publicApiOperations,
+} from "@webstudio-is/protocol";
+import type { Instance } from "@webstudio-is/sdk";
+import type { BuilderState } from "@webstudio-is/project-build/state/builder-state";
+import type { BuilderPatchTransaction } from "@webstudio-is/project-build/contracts/patch";
+import type { BuilderRuntimeMutation } from "@webstudio-is/project-build/runtime/mutation";
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import React from "react";
+import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
+
+const execFileAsync = promisify(execFile);
+const projectId = "release-smoke-project";
+const buildId = "release-smoke-build";
+const projectVersion = 1;
+const sessionVersion = "cli-project-session-v1";
+const releaseVersionPlaceholder = "0.0.0-webstudio-version";
+
+const reportPhase = (phase: string, startedAt = Date.now()) => {
+ process.stderr.write(
+ `[release-smoke] ${phase} (${Date.now() - startedAt}ms)\n`
+ );
+};
+
+const replaceReleaseVersion = async (
+ directory: string,
+ releaseVersion: string,
+ workspaceVersions: ReadonlyMap<string, string>
+) => {
+ const entries = await readdir(directory, { withFileTypes: true });
+ await Promise.all(
+ entries.map(async (entry) => {
+ const entryPath = join(directory, entry.name);
+ if (entry.isDirectory()) {
+ await replaceReleaseVersion(
+ entryPath,
+ releaseVersion,
+ workspaceVersions
+ );
+ return;
+ }
+ if (/\.(?:js|mjs|json)$/.test(entry.name) === false) {
+ return;
+ }
+ const source = await readFile(entryPath, "utf8");
+ let releaseSource = source.replaceAll(
+ releaseVersionPlaceholder,
+ releaseVersion
+ );
+ if (entry.name === "package.json") {
+ const manifest = JSON.parse(releaseSource) as Record<string, unknown>;
+ for (const field of [
+ "dependencies",
+ "devDependencies",
+ "optionalDependencies",
+ "peerDependencies",
+ ]) {
+ const dependencies = manifest[field];
+ if (
+ typeof dependencies !== "object" ||
+ dependencies === null ||
+ Array.isArray(dependencies)
+ ) {
+ continue;
+ }
+ const dependencyVersions = dependencies as Record<string, unknown>;
+ for (const [name, version] of Object.entries(dependencyVersions)) {
+ if (
+ typeof version === "string" &&
+ version.startsWith("workspace:")
+ ) {
+ const workspaceVersion = workspaceVersions.get(name);
+ if (workspaceVersion === undefined) {
+ throw new Error(
+ `Cannot resolve workspace dependency ${name} in ${entryPath}.`
+ );
+ }
+ dependencyVersions[name] = workspaceVersion;
+ }
+ }
+ }
+ releaseSource = JSON.stringify(manifest, undefined, 2);
+ }
+ if (releaseSource !== source) {
+ await writeFile(entryPath, releaseSource, "utf8");
+ }
+ })
+ );
+};
+
+const packReleaseShapedCli = async ({
+ stagingDirectory,
+ packDirectory,
+}: {
+ stagingDirectory: string;
+ packDirectory: string;
+}) => {
+ const cliDirectory = join(import.meta.dirname, "..");
+ await Promise.all(
+ ["bin.js", "package.json", "lib", "templates"].map((entry) =>
+ cp(join(cliDirectory, entry), join(stagingDirectory, entry), {
+ recursive: true,
+ })
+ )
+ );
+ const releaseVersion =
+ process.env.WEBSTUDIO_RELEASE_SMOKE_VERSION ??
+ JSON.parse(
+ (await execFileAsync("npm", ["view", "webstudio", "version", "--json"]))
+ .stdout
+ );
+ if (typeof releaseVersion !== "string" || releaseVersion.length === 0) {
+ throw new Error("Could not resolve a published Webstudio release version.");
+ }
+ const packagesDirectory = join(import.meta.dirname, "../..");
+ const workspaceVersions = new Map<string, string>();
+ for (const entry of await readdir(packagesDirectory, {
+ withFileTypes: true,
+ })) {
+ if (entry.isDirectory() === false) {
+ continue;
+ }
+ try {
+ const manifest = JSON.parse(
+ await readFile(
+ join(packagesDirectory, entry.name, "package.json"),
+ "utf8"
+ )
+ ) as { name?: string; version?: string };
+ if (manifest.name !== undefined && manifest.version !== undefined) {
+ workspaceVersions.set(
+ manifest.name,
+ manifest.version.replace(releaseVersionPlaceholder, releaseVersion)
+ );
+ }
+ } catch (error) {
+ if (
+ error instanceof Error &&
+ "code" in error &&
+ error.code === "ENOENT"
+ ) {
+ continue;
+ }
+ throw error;
+ }
+ }
+ await replaceReleaseVersion(
+ stagingDirectory,
+ releaseVersion,
+ workspaceVersions
+ );
+ await execFileAsync("npm", ["pack", "--pack-destination", packDirectory], {
+ cwd: stagingDirectory,
+ });
+ return releaseVersion;
+};
+
+const createFixture = () => {
+ const assets = [
+ {
+ id: "asset-hero",
+ projectId,
+ name: "release-hero.png",
+ filename: "release-hero.png",
+ type: "image" as const,
+ size: 128,
+ format: "png",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ description: "Release smoke hero",
+ meta: { width: 1200, height: 800 },
+ },
+ ];
+ const basePages = [
+ {
+ id: "home",
+ name: "Home",
+ title: "Home",
+ path: "",
+ rootInstanceId: "home-root",
+ meta: {},
+ },
+ {
+ id: "pricing",
+ name: "Pricing",
+ title: "Pricing",
+ path: "/pricing",
+ rootInstanceId: "pricing-root",
+ meta: {},
+ },
+ ];
+ const extraPageCount =
+ process.env.WEBSTUDIO_RELEASE_SMOKE_LARGE_AUDIT === "1" ? 120 : 0;
+ const pages = [
+ ...basePages,
+ ...Array.from({ length: extraPageCount }, (_, index) => {
+ const number = index + 3;
+ return {
+ id: `audit-${number}`,
+ name: `Audit ${number}`,
+ title: `Audit ${number}`,
+ path: `/audit-${number}`,
+ rootInstanceId: `audit-${number}-root`,
+ meta: {},
+ };
+ }),
+ ];
+ const persistedPages = {
+ meta: { siteName: "Release Smoke", contactEmail: "" },
+ compiler: { atomicStyles: true },
+ redirects: [],
+ homePageId: "home",
+ rootFolderId: "root-folder",
+ pages,
+ folders: [
+ {
+ id: "root-folder",
+ name: "Root",
+ slug: "",
+ children: pages.map((page) => page.id),
+ },
+ ],
+ };
+ const instances: Array<[string, Instance]> = pages.map((page) => [
+ page.rootInstanceId,
+ {
+ type: "instance",
+ id: page.rootInstanceId,
+ component: "Box",
+ children:
+ page.id === "home"
+ ? [
+ { type: "text", value: `Release smoke ${page.name}` },
+ { type: "id", value: "home-image" },
+ ]
+ : [{ type: "text", value: `Release smoke ${page.name}` }],
+ },
+ ]);
+ instances.push([
+ "home-image",
+ {
+ type: "instance",
+ id: "home-image",
+ component: "Image",
+ children: [],
+ },
+ ]);
+ const props = [
+ {
+ id: "home-image-src",
+ instanceId: "home-image",
+ name: "src",
+ type: "asset" as const,
+ value: "asset-hero",
+ },
+ ];
+ const build = {
+ id: buildId,
+ projectId,
+ version: projectVersion,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ pages: persistedPages,
+ props: props.map((prop) => [prop.id, prop]) as never,
+ instances: instances as never,
+ dataSources: [],
+ resources: [],
+ styleSources: [],
+ styleSourceSelections: [],
+ styles: [],
+ breakpoints: [],
+ projectSettings: { meta: {}, compiler: {} },
+ };
+ return {
+ data: {
+ bundleVersion,
+ origin: "https://assets.example",
+ projectDomain: "example.com",
+ projectTitle: "Release Smoke",
+ page: pages[0],
+ pages,
+ assets,
+ build,
+ },
+ build,
+ persistedPages,
+ instances,
+ assets,
+ props,
+ };
+};
+
+const waitForUrl = async (url: string, child: ChildProcess) => {
+ const deadline = Date.now() + 60_000;
+ while (Date.now() < deadline) {
+ if (child.exitCode !== null) {
+ throw new Error(`Preview exited with code ${child.exitCode}.`);
+ }
+ try {
+ const response = await fetch(url);
+ if (response.ok) {
+ return;
+ }
+ } catch {}
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ }
+ throw new Error(`Preview did not become ready at ${url}.`);
+};
+
+const stopProcessTree = async (child: ChildProcess | undefined) => {
+ if (child?.pid === undefined) {
+ return;
+ }
+ const pid = child.pid;
+ const usesProcessGroup = process.platform !== "win32";
+ const signal = (value: NodeJS.Signals) => {
+ try {
+ if (usesProcessGroup) {
+ process.kill(-pid, value);
+ } else {
+ child.kill(value);
+ }
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") {
+ throw error;
+ }
+ }
+ };
+ const isRunning = () => {
+ try {
+ process.kill(usesProcessGroup ? -pid : pid, 0);
+ return true;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ESRCH") {
+ return false;
+ }
+ throw error;
+ }
+ };
+ const waitUntilStopped = async (timeoutMs: number) => {
+ const deadline = Date.now() + timeoutMs;
+ while (isRunning() && Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ return isRunning() === false;
+ };
+
+ signal("SIGTERM");
+ if (await waitUntilStopped(5_000)) {
+ return;
+ }
+ signal("SIGKILL");
+ if ((await waitUntilStopped(5_000)) === false) {
+ throw new Error(`Preview process group ${pid} did not stop.`);
+ }
+};
+
+const readTrpcInput = async (request: import("node:http").IncomingMessage) => {
+ const url = new URL(request.url ?? "", "http://127.0.0.1");
+ const source =
+ request.method === "GET"
+ ? (url.searchParams.get("input") ?? "{}")
+ : await new Promise<string>((resolve, reject) => {
+ let body = "";
+ request.setEncoding("utf8");
+ request.on("data", (chunk) => {
+ body += chunk;
+ });
+ request.on("end", () => resolve(body || "{}"));
+ request.on("error", reject);
+ });
+ const batch = JSON.parse(source) as Record<string, unknown>;
+ const first = batch["0"];
+ if (typeof first !== "object" || first === null || Array.isArray(first)) {
+ return {};
+ }
+ return "json" in first ? ((first as { json?: unknown }).json ?? {}) : first;
+};
+
+const startFixtureApi = async (
+ fixture: ReturnType<typeof createFixture>,
+ {
+ initialState,
+ executeRuntime,
+ applyTransactions,
+ serializeFixturePages,
+ }: {
+ initialState: BuilderState;
+ executeRuntime: (input: {
+ id: string;
+ state: BuilderState;
+ input: unknown;
+ context: {
+ createId: () => string;
+ projectId: string;
+ projectVersion: number;
+ };
+ }) => unknown | Promise<unknown>;
+ applyTransactions: (
+ state: BuilderState,
+ transactions: readonly BuilderPatchTransaction[]
+ ) => { state: BuilderState };
+ serializeFixturePages: (
+ pages: NonNullable<BuilderState["pages"]>
+ ) => ReturnType<
+ typeof import("@webstudio-is/project-migrations/pages").serializePages
+ >;
+ }
+) => {
+ let version = projectVersion;
+ let state = initialState;
+ let generatedId = 0;
+ const server = createServer(async (request, response) => {
+ try {
+ const requestUrl = request.url ?? "";
+ if (
+ new URL(requestUrl, "http://127.0.0.1").pathname.endsWith(
+ "/release-hero.png"
+ )
+ ) {
+ response.writeHead(200, { "content-type": "image/png" });
+ response.end(
+ Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
+ "base64"
+ )
+ );
+ return;
+ }
+ const operationPath = new URL(
+ requestUrl,
+ "http://127.0.0.1"
+ ).pathname.replace(/^\/trpc\/api\./, "");
+ let data: unknown;
+ if (operationPath === "build.patch") {
+ const input = (await readTrpcInput(request)) as {
+ transactions?: BuilderPatchTransaction[];
+ };
+ state = applyTransactions(state, input.transactions ?? []).state;
+ version += 1;
+ data = { version };
+ } else if (operationPath === "build.get") {
+ const pages = serializeFixturePages(state.pages!);
+ data = {
+ ...fixture.build,
+ buildId,
+ version,
+ pages: pages.pages,
+ pageTemplates: pages.pageTemplates,
+ folders: pages.folders,
+ homePageId: pages.homePageId,
+ rootFolderId: pages.rootFolderId,
+ meta: pages.meta,
+ compiler: pages.compiler,
+ redirects: pages.redirects,
+ assets: Array.from(state.assets?.values() ?? []),
+ instances: Array.from(state.instances?.values() ?? []),
+ props: Array.from(state.props?.values() ?? []),
+ dataSources: Array.from(state.dataSources?.values() ?? []),
+ resources: Array.from(state.resources?.values() ?? []),
+ breakpoints: Array.from(state.breakpoints?.values() ?? []),
+ styles: Array.from(state.styles?.values() ?? []),
+ styleSources: Array.from(state.styleSources?.values() ?? []),
+ styleSourceSelections: Array.from(
+ state.styleSourceSelections?.values() ?? []
+ ),
+ marketplaceProduct: state.marketplaceProduct,
+ projectSettings: state.projectSettings,
+ };
+ } else if (
+ operationPath !== "projects.permissions" &&
+ operationPath !== ""
+ ) {
+ const input = await readTrpcInput(request);
+ const result = await executeRuntime({
+ id: operationPath,
+ state,
+ input,
+ context: {
+ createId: () => `fixture-${generatedId++}`,
+ projectId,
+ projectVersion: version,
+ },
+ });
+ if (
+ typeof result === "object" &&
+ result !== null &&
+ "kind" in result &&
+ (result as BuilderRuntimeMutation).kind === "mutation"
+ ) {
+ const mutation = result as BuilderRuntimeMutation;
+ state = applyTransactions(state, [
+ {
+ id: `fixture-transaction-${generatedId++}`,
+ payload: mutation.payload,
+ },
+ ]).state;
+ version += 1;
+ data = mutation.result;
+ } else {
+ data = result;
+ }
+ } else {
+ data = {
+ canView: true,
+ canEdit: true,
+ canBuild: true,
+ canAdmin: true,
+ canUseApi: true,
+ apiContract: {
+ version: publicApiContractVersion,
+ operationIds: publicApiOperations.flatMap((operation) =>
+ publicApiOperationRequiresServerSupport(operation)
+ ? [operation.id]
+ : []
+ ),
+ },
+ };
+ }
+ response.writeHead(200, { "content-type": "application/json" });
+ response.end(JSON.stringify([{ result: { data } }]));
+ } catch (error) {
+ response.writeHead(500, { "content-type": "application/json" });
+ response.end(
+ JSON.stringify([
+ {
+ error: {
+ message: error instanceof Error ? error.message : String(error),
+ code: -32603,
+ data: { code: "INTERNAL_SERVER_ERROR", httpStatus: 500 },
+ },
+ },
+ ])
+ );
+ }
+ });
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", resolve);
+ });
+ const address = server.address();
+ if (address === null || typeof address === "string") {
+ throw new Error("Fixture API address is unavailable.");
+ }
+ return { server, origin: `http://127.0.0.1:${address.port}` };
+};
+
+const closeServer = async (server: Server | undefined) => {
+ if (server === undefined) {
+ return;
+ }
+ server.closeAllConnections();
+ await new Promise<void>((resolve, reject) => {
+ server.close((error) => (error === undefined ? resolve() : reject(error)));
+ });
+};
+
+const assertJsonStdout = async (stdout: string, label: string) => {
+ try {
+ JSON.parse(stdout);
+ } catch (error) {
+ throw new Error(`${label} did not print valid JSON.`, { cause: error });
+ }
+};
+
+const getRecord = (value: unknown, label: string) => {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
+ throw new Error(`${label} is not an object.`);
+ }
+ return value as Record<string, unknown>;
+};
+
+const assertScreenshotEvidence = async ({
+ payload,
+ label,
+ path,
+ status,
+ viewport,
+ projectDirectory,
+ generatedSite = true,
+ origin = "http://127.0.0.1:5190",
+}: {
+ payload: Record<string, unknown>;
+ label: string;
+ path: string;
+ status: number;
+ viewport: { width: number; height: number };
+ projectDirectory: string;
+ generatedSite?: boolean;
+ origin?: string;
+}) => {
+ const data = getRecord(payload.data, `${label} data`);
+ const navigation = getRecord(data.navigation, `${label} navigation`);
+ const finalUrl = new URL(String(navigation.finalUrl));
+ if (
+ finalUrl.origin !== origin ||
+ finalUrl.pathname !== path ||
+ navigation.status !== status ||
+ (generatedSite && navigation.generatedSiteRootPresent !== true)
+ ) {
+ throw new Error(
+ `${label} returned unexpected navigation evidence: ${JSON.stringify(navigation)}`
+ );
+ }
+ const actualViewport = getRecord(data.viewport, `${label} viewport`);
+ if (
+ actualViewport.width !== viewport.width ||
+ actualViewport.height !== viewport.height
+ ) {
+ throw new Error(
+ `${label} returned unexpected viewport: ${JSON.stringify(actualViewport)}`
+ );
+ }
+ const output = String(data.output);
+ const screenshot = await readFile(
+ output.startsWith("/") ? output : join(projectDirectory, output)
+ );
+ const isPng = screenshot
+ .subarray(0, 8)
+ .equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
+ const isWebp =
+ screenshot.subarray(0, 4).toString("ascii") === "RIFF" &&
+ screenshot.subarray(8, 12).toString("ascii") === "WEBP";
+ if (screenshot.length === 0 || (isPng === false && isWebp === false)) {
+ throw new Error(`${label} did not create a valid PNG or WebP artifact.`);
+ }
+};
+
+const run = async () => {
+ Object.assign(globalThis, {
+ React,
+ });
+ const [
+ pagesModule,
+ adapters,
+ namespaces,
+ projectSession,
+ runtimeRegistry,
+ statePatch,
+ ] = await Promise.all([
+ import("@webstudio-is/project-migrations/pages"),
+ import("@webstudio-is/project-build/state/adapters"),
+ import("@webstudio-is/project-build/contracts/namespaces"),
+ import("@webstudio-is/project-build/project-session"),
+ import("@webstudio-is/project-build/runtime/registry"),
+ import("@webstudio-is/project-build/state/patch"),
+ ]);
+ const temp = await mkdtemp(join(tmpdir(), "webstudio-release-smoke-"));
+ let preview: ChildProcess | undefined;
+ let apiServer: Server | undefined;
+ try {
+ const startedAt = Date.now();
+ const fixture = createFixture();
+ const initialState = adapters.createBuilderStateFromBuildData({
+ ...fixture.build,
+ pages: pagesModule.migratePages(fixture.persistedPages),
+ assets: fixture.assets,
+ instances: fixture.instances.map(([, instance]) => instance),
+ props: fixture.props,
+ });
+ const fixtureApi = await startFixtureApi(fixture, {
+ initialState,
+ executeRuntime: runtimeRegistry.executeBuilderRuntimeOperation,
+ applyTransactions: statePatch.applyBuilderPatchTransactions,
+ serializeFixturePages: pagesModule.serializePages,
+ });
+ fixture.data.origin = fixtureApi.origin;
+ reportPhase("fixture API ready", startedAt);
+ apiServer = fixtureApi.server;
+ const packDirectory = join(temp, "pack");
+ const stagingDirectory = join(temp, "staging");
+ const projectDirectory = join(temp, "project");
+ const configDirectory = join(temp, "config");
+ await Promise.all([
+ mkdir(packDirectory, { recursive: true }),
+ mkdir(stagingDirectory, { recursive: true }),
+ mkdir(join(projectDirectory, ".webstudio"), { recursive: true }),
+ mkdir(join(configDirectory, "webstudio-nodejs"), { recursive: true }),
+ ]);
+ const packStartedAt = Date.now();
+ const releaseVersion = await packReleaseShapedCli({
+ stagingDirectory,
+ packDirectory,
+ });
+ reportPhase("packed release-shaped CLI", packStartedAt);
+ const tarballName = (await readdir(packDirectory)).find((name) =>
+ name.endsWith(".tgz")
+ );
+ if (tarballName === undefined) {
+ throw new Error("pnpm pack did not produce a tarball.");
+ }
+ await writeFile(
+ join(projectDirectory, "package.json"),
+ JSON.stringify({ private: true }),
+ "utf8"
+ );
+ const installStartedAt = Date.now();
+ const install = await execFileAsync(
+ "npm",
+ [
+ "install",
+ join(packDirectory, tarballName),
+ "--no-audit",
+ "--no-fund",
+ "--loglevel=warn",
+ ],
+ { cwd: projectDirectory, maxBuffer: 10 * 1024 * 1024 }
+ );
+ if (/ERESOLVE|overriding peer dependency/i.test(install.stderr)) {
+ throw new Error(
+ `npm install emitted peer dependency warnings:\n${install.stderr}`
+ );
+ }
+ reportPhase("installed packed CLI", installStartedAt);
+
+ await writeFile(
+ join(projectDirectory, ".webstudio", "data.json"),
+ JSON.stringify(fixture.data),
+ "utf8"
+ );
+ await writeFile(
+ join(projectDirectory, ".webstudio", "config.json"),
+ JSON.stringify({ projectId }),
+ "utf8"
+ );
+ const state = adapters.createBuilderStateFromBuildData({
+ ...fixture.build,
+ pages: pagesModule.migratePages(fixture.persistedPages),
+ assets: fixture.assets,
+ instances: fixture.instances.map(([, instance]) => instance),
+ props: fixture.props,
+ });
+ const loadedAt = "2026-01-01T00:00:00.000Z";
+ const freshness = Object.fromEntries(
+ namespaces.builderNamespaces.map((namespace) => [
+ namespace,
+ {
+ status: "fresh",
+ version: projectVersion,
+ source: "remote",
+ loadedAt,
+ },
+ ])
+ );
+ await writeFile(
+ join(projectDirectory, ".webstudio", "project-session.json"),
+ JSON.stringify({
+ projectId,
+ buildId,
+ version: projectVersion,
+ state: adapters.createSerializedBuilderStateSnapshotFromState(state),
+ freshness,
+ compatibilityVersion: sessionVersion,
+ compatibility: {
+ ...projectSession.createDefaultProjectSessionCompatibility(
+ sessionVersion
+ ),
+ apiCompatibilityVersion: releaseVersion,
+ },
+ revision: randomUUID(),
+ }),
+ "utf8"
+ );
+ const globalConfigPath = join(configDirectory, "webstudio-config.json");
+ await mkdir(dirname(globalConfigPath), { recursive: true });
+ await writeFile(
+ globalConfigPath,
+ JSON.stringify({
+ [projectId]: { origin: fixtureApi.origin, token: "fixture" },
+ }),
+ "utf8"
+ );
+
+ const bin = join(projectDirectory, "node_modules", ".bin", "webstudio");
+ const env = {
+ ...process.env,
+ WEBSTUDIO_CONFIG_DIR: configDirectory,
+ };
+ const invoke = async (label: string, args: string[]) => {
+ const result = await execFileAsync(bin, args, {
+ cwd: projectDirectory,
+ env,
+ maxBuffer: 20 * 1024 * 1024,
+ });
+ await assertJsonStdout(result.stdout, label);
+ return JSON.parse(result.stdout) as Record<string, unknown>;
+ };
+
+ const docs = await readFile(
+ join(import.meta.dirname, "../src/docs/api-use-cases.md"),
+ "utf8"
+ );
+ const documentedAuditCommands = docs
+ .split("\n")
+ .filter((line) => line.startsWith("- webstudio audit "))
+ .map((line) =>
+ line
+ .slice("- webstudio ".length)
+ .trim()
+ .split(/\s+/)
+ .filter((arg) => arg !== "--json")
+ );
+ if (documentedAuditCommands.length === 0) {
+ throw new Error("No documented audit CLI examples were found.");
+ }
+ const helpStartedAt = Date.now();
+ for (const args of documentedAuditCommands) {
+ const result = await execFileAsync(bin, [...args, "--help"], {
+ cwd: projectDirectory,
+ env,
+ });
+ if (!result.stdout.includes("webstudio audit")) {
+ throw new Error(
+ `Packed audit help is not audit-specific: ${result.stdout}`
+ );
+ }
+ }
+ reportPhase("validated packed audit help examples", helpStartedAt);
+
+ const previewStartedAt = Date.now();
+ preview = spawn(bin, ["preview", "--port", "5190"], {
+ cwd: projectDirectory,
+ env,
+ detached: process.platform !== "win32",
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ await waitForUrl("http://127.0.0.1:5190/", preview);
+ const previewManifest = JSON.parse(
+ await readFile(
+ join(projectDirectory, ".webstudio/preview/package.json"),
+ "utf8"
+ )
+ ) as { dependencies?: Record<string, string> };
+ if (
+ previewManifest.dependencies?.ipx !== undefined ||
+ previewManifest.dependencies?.h3 !== undefined
+ ) {
+ throw new Error(
+ "Generic React Router preview unexpectedly includes Docker-only image proxy dependencies."
+ );
+ }
+ reportPhase("started packed preview", previewStartedAt);
+ const commandsStartedAt = Date.now();
+ const assertLocalDryRun = async (
+ label: string,
+ command: string,
+ input: Record<string, unknown>
+ ) => {
+ const payload = await invoke(label, [
+ command,
+ JSON.stringify(input),
+ "--dry-run",
+ ]);
+ const meta = getRecord(payload.meta, `${label} meta`);
+ const session = getRecord(meta.session, `${label} session`);
+ if (
+ payload.ok !== true ||
+ session.source !== "dry-run" ||
+ session.committed !== false ||
+ typeof session.transaction !== "object"
+ ) {
+ throw new Error(
+ `${label} did not produce a local dry-run transaction: ${JSON.stringify(payload)}`
+ );
+ }
+ };
+ await invoke("packed list pages", ["list-pages"]);
+ await assertLocalDryRun("plain page metadata update", "update-page", {
+ pageId: "home",
+ values: {
+ title: "My title: seven pages & more",
+ meta: { description: "Ordinary prose, punctuation included." },
+ },
+ });
+ await assertLocalDryRun("cold page duplicate", "duplicate-page", {
+ pageId: "home",
+ name: "Home copy",
+ path: "/home-copy",
+ });
+ await assertLocalDryRun("local fragment insertion", "insert-fragment", {
+ parentInstanceId: "home-root",
+ fragment: '<ws.element ws:tag="p">Release smoke</ws.element>',
+ });
+ await assertLocalDryRun("local component insertion", "insert-component", {
+ parentInstanceId: "home-root",
+ component: "ws:element",
+ tag: "p",
+ });
+
+ await stopProcessTree(preview);
+ preview = undefined;
+ await rm(join(projectDirectory, ".webstudio", "project-session.json"), {
+ force: true,
+ });
+ const stdioStartedAt = Date.now();
+ const stdioTransport = new StdioClientTransport({
+ command: bin,
+ args: ["mcp"],
+ cwd: projectDirectory,
+ env: Object.fromEntries(
+ Object.entries(env).filter(
+ (entry): entry is [string, string] => typeof entry[1] === "string"
+ )
+ ),
+ stderr: "pipe",
+ });
+ let stdioLogs = "";
+ stdioTransport.stderr?.on("data", (chunk) => {
+ stdioLogs += String(chunk);
+ });
+ const stdioClient = new Client({
+ name: "webstudio-release-smoke",
+ version: "1.0.0",
+ });
+ const callTool = async (
+ name: string,
+ args: Record<string, unknown> = {}
+ ) => {
+ const result = await stdioClient.callTool({ name, arguments: args });
+ const structured = getRecord(
+ result.structuredContent,
+ `${name} structured content`
+ );
+ if (result.isError === true || structured.ok !== true) {
+ throw new Error(
+ `${name} failed over packed stdio MCP: ${JSON.stringify(structured)}`
+ );
+ }
+ return getRecord(structured.data, `${name} data`);
+ };
+ await stdioClient.connect(stdioTransport);
+ try {
+ const initialPages = await callTool("list-pages", {
+ includeFolders: true,
+ });
+ if (
+ Array.isArray(initialPages.pages) === false ||
+ initialPages.pages.length !== 2
+ ) {
+ throw new Error(
+ `Cold stdio discovery returned unexpected pages: ${JSON.stringify(initialPages)}`
+ );
+ }
+ await callTool("refresh", {
+ namespaces: ["pages", "instances", "props", "assets"],
+ });
+ const assets = await callTool("list-assets");
+ if (Array.isArray(assets.items) === false || assets.items.length !== 1) {
+ throw new Error(
+ `Cold stdio asset discovery failed: ${JSON.stringify(assets)}`
+ );
+ }
+
+ const createdPages: Array<{
+ pageId: string;
+ name: string;
+ path: string;
+ }> = [];
+ const duplicate = await callTool("duplicate-page", {
+ pageId: "home",
+ name: "About",
+ path: "/about",
+ });
+ createdPages.push({
+ pageId: String(duplicate.pageId),
+ name: "About",
+ path: "/about",
+ });
+ for (const page of [
+ { name: "Services", path: "/services" },
+ { name: "Work", path: "/work" },
+ { name: "Blog", path: "/blog" },
+ { name: "Contact", path: "/contact" },
+ ]) {
+ const created = await callTool("create-page", page);
+ createdPages.push({ pageId: String(created.pageId), ...page });
+ }
+
+ for (const page of createdPages) {
+ await callTool("update-page", {
+ pageId: page.pageId,
+ values: {
+ title: `${page.name}: release smoke & verification`,
+ meta: { description: `A plain-text description for ${page.name}.` },
+ },
+ });
+ const details = await callTool("get-page", { pageId: page.pageId });
+ const inserted = await callTool("insert-component", {
+ parentInstanceId: String(details.rootInstanceId),
+ component: "ws:element",
+ tag: "section",
+ });
+ const sectionId = String(
+ (inserted.rootInstanceIds as unknown[] | undefined)?.[0]
+ );
+ await callTool("update-props", {
+ updates: [
+ {
+ instanceId: sectionId,
+ name: "data-imported-page",
+ type: "string",
+ value: page.name,
+ },
+ ],
+ });
+ }
+
+ await callTool("update-text", {
+ instanceId: "pricing-root",
+ childIndex: 0,
+ text: "Pricing imported content",
+ mode: "text",
+ });
+
+ for (let index = 0; index < 10; index += 1) {
+ await callTool("list-pages");
+ await callTool("update-page", {
+ pageId: "pricing",
+ values: { title: `Pricing session check ${index}` },
+ });
+ }
+
+ const usage = await callTool("find-asset-usage", {
+ assetId: "asset-hero",
+ });
+ if (Array.isArray(usage.usages) === false || usage.usages.length < 2) {
+ throw new Error(
+ `Duplicated page lost its image asset reference: ${JSON.stringify(usage)}`
+ );
+ }
+
+ await callTool("preview.start", {
+ host: "127.0.0.1",
+ port: 5191,
+ source: "session",
+ });
+ const workflowScreenshot = await callTool("screenshot", {
+ path: "/work",
+ output: ".webstudio/workflow-work.png",
+ viewport: { width: 1280, height: 800 },
+ waitUntil: "load",
+ });
+ await assertScreenshotEvidence({
+ payload: { data: workflowScreenshot },
+ label: "seven-page stdio workflow screenshot",
+ path: "/work",
+ status: 200,
+ viewport: { width: 1280, height: 800 },
+ projectDirectory,
+ origin: "http://127.0.0.1:5191",
+ });
+ await callTool("preview.stop");
+
+ const finalPages = await callTool("list-pages");
+ const finalPageNames = Array.isArray(finalPages.pages)
+ ? finalPages.pages.map((page) => getRecord(page, "final page").name)
+ : [];
+ if (
+ finalPageNames.length !== 7 ||
+ createdPages.some(
+ (page) => finalPageNames.includes(page.name) === false
+ )
+ ) {
+ throw new Error(
+ `Seven-page workflow verification failed: ${JSON.stringify(finalPages)}`
+ );
+ }
+ } finally {
+ await stdioClient.close();
+ }
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ if (
+ stdioLogs.includes("API contract negotiated") === false ||
+ stdioLogs.includes('"event":"stdio_connection_closed"') === false ||
+ stdioLogs.includes('"event":"stdio_transport_error"')
+ ) {
+ throw new Error(`Unexpected packed stdio lifecycle logs:\n${stdioLogs}`);
+ }
+ reportPhase(
+ "completed packed seven-page stdio MCP workflow",
+ stdioStartedAt
+ );
+
+ preview = spawn(bin, ["preview", "--port", "5190"], {
+ cwd: projectDirectory,
+ env,
+ detached: process.platform !== "win32",
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ await waitForUrl("http://127.0.0.1:5190/", preview);
+
+ const pricingScreenshot = await invoke("standalone screenshot", [
+ "screenshot",
+ "http://127.0.0.1:5190/pricing",
+ "--output",
+ ".webstudio/pricing.png",
+ "--width",
+ "1440",
+ "--height",
+ "900",
+ "--json",
+ ]);
+ await assertScreenshotEvidence({
+ payload: pricingScreenshot,
+ label: "standalone pricing screenshot",
+ path: "/pricing",
+ status: 200,
+ viewport: { width: 1440, height: 900 },
+ projectDirectory,
+ });
+ const homeScreenshot = await invoke("MCP screenshot", [
+ "mcp",
+ "single-op-call",
+ "screenshot",
+ JSON.stringify({
+ baseUrl: "http://127.0.0.1:5190",
+ path: "/",
+ viewport: { width: 375, height: 812 },
+ }),
+ ]);
+ await assertScreenshotEvidence({
+ payload: homeScreenshot,
+ label: "MCP home screenshot",
+ path: "/",
+ status: 200,
+ viewport: { width: 375, height: 812 },
+ projectDirectory,
+ });
+ await invoke("MCP run", [
+ "mcp",
+ "run",
+ JSON.stringify([
+ {
+ tool: "screenshot",
+ input: {
+ baseUrl: "http://127.0.0.1:5190",
+ path: "/pricing",
+ viewport: { width: 1440, height: 900 },
+ },
+ },
+ ]),
+ ]);
+ const missingScreenshot = await invoke("missing route screenshot", [
+ "screenshot",
+ "http://127.0.0.1:5190/missing",
+ "--output",
+ ".webstudio/missing.png",
+ "--width",
+ "375",
+ "--height",
+ "812",
+ "--json",
+ ]);
+ await assertScreenshotEvidence({
+ payload: missingScreenshot,
+ label: "missing route screenshot",
+ path: "/missing",
+ status: 404,
+ viewport: { width: 375, height: 812 },
+ projectDirectory,
+ generatedSite: false,
+ });
+ const renderedAudit = await invoke("rendered audit", [
+ "audit",
+ "--rendered",
+ "--page-path",
+ "/",
+ "--json",
+ ]);
+ const renderedAuditData = getRecord(
+ renderedAudit.data,
+ "rendered audit data"
+ );
+ const renderedAuditSummary = getRecord(
+ renderedAuditData.renderedCaptureSummary,
+ "rendered audit capture summary"
+ );
+ if (
+ renderedAudit.ok !== true ||
+ renderedAuditData.renderedCheckCount !== 1 ||
+ renderedAuditSummary.planned !== 1 ||
+ renderedAuditSummary.failed !== 0 ||
+ renderedAuditSummary.skipped !== 0
+ ) {
+ throw new Error(
+ `Rendered audit was incomplete: ${JSON.stringify(renderedAuditData)}`
+ );
+ }
+ if (process.env.WEBSTUDIO_RELEASE_SMOKE_LARGE_AUDIT === "1") {
+ const planPayload = await invoke("large rendered audit plan", [
+ "audit",
+ "--rendered",
+ "--scopes",
+ "performance",
+ "--json",
+ ]);
+ const planData = getRecord(planPayload.data, "large audit plan data");
+ const plan = getRecord(planData.renderedPlan, "large rendered plan");
+ if (
+ plan.captureCount !== 122 ||
+ typeof plan.confirmationToken !== "string"
+ ) {
+ throw new Error(
+ `Large rendered audit did not return the expected 122-capture confirmation plan: ${JSON.stringify(plan)}`
+ );
+ }
+ const confirmedAuditStartedAt = Date.now();
+ const confirmedPayload = await invoke("confirmed large rendered audit", [
+ "audit",
+ "--rendered",
+ "--scopes",
+ "performance",
+ "--confirm-large-run",
+ "--confirmation-token",
+ plan.confirmationToken,
+ "--json",
+ ]);
+ const confirmedData = getRecord(
+ confirmedPayload.data,
+ "confirmed large audit data"
+ );
+ const summary = getRecord(
+ confirmedData.renderedCaptureSummary,
+ "confirmed large audit capture summary"
+ );
+ const manifestSummary = getRecord(
+ confirmedData.renderedArtifactManifest,
+ "confirmed large audit artifact manifest"
+ );
+ const manifestPath = String(manifestSummary.path);
+ const manifest = JSON.parse(
+ await readFile(
+ manifestPath.startsWith("/")
+ ? manifestPath
+ : join(projectDirectory, manifestPath),
+ "utf8"
+ )
+ ) as { failures?: unknown[]; performance?: unknown };
+ if (
+ confirmedPayload.ok !== true ||
+ confirmedData.renderedCheckCount !== 122 ||
+ summary.planned !== 122 ||
+ summary.failed !== 0 ||
+ summary.skipped !== 0
+ ) {
+ throw new Error(
+ `Confirmed large rendered audit was incomplete: ${JSON.stringify({ summary, failures: manifest.failures })}`
+ );
+ }
+ reportPhase(
+ `validated confirmed 122-capture packaged audit ${JSON.stringify({ performance: manifest.performance })}`,
+ confirmedAuditStartedAt
+ );
+ const confirmedAuditDuration = Date.now() - confirmedAuditStartedAt;
+ if (confirmedAuditDuration > 90_000) {
+ throw new Error(
+ `Confirmed 122-capture packaged audit took ${confirmedAuditDuration}ms; expected at most 90000ms.`
+ );
+ }
+ const cachedAuditStartedAt = Date.now();
+ await invoke("cached rendered audit", [
+ "audit",
+ "--rendered",
+ "--page-path",
+ "/",
+ "--scopes",
+ "performance",
+ "--json",
+ ]);
+ reportPhase("validated cached rendered audit", cachedAuditStartedAt);
+ const cachedAuditDuration = Date.now() - cachedAuditStartedAt;
+ if (cachedAuditDuration > 20_000) {
+ throw new Error(
+ `Cached rendered audit took ${cachedAuditDuration}ms; expected at most 20000ms.`
+ );
+ }
+ }
+ reportPhase("validated structured commands", commandsStartedAt);
+ } finally {
+ await stopProcessTree(preview);
+ await closeServer(apiServer);
+ await rm(temp, { recursive: true, force: true });
+ reportPhase("cleaned temporary release smoke files");
+ }
+};
+
+await run();
diff --git a/packages/cli/src/cli-bundle-externals.test.ts b/packages/cli/src/cli-bundle-externals.test.ts
index 3eeb62dd8a..3c7718da08 100644
--- a/packages/cli/src/cli-bundle-externals.test.ts
+++ b/packages/cli/src/cli-bundle-externals.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, test } from "vitest";
import { isExternal } from "../vite.config";
+import packageJson from "../package.json";
describe("CLI bundle externals", () => {
test("loads esbuild and Node builtins from the installed environment", () => {
@@ -7,4 +8,16 @@ describe("CLI bundle externals", () => {
expect(isExternal("esbuild/lib/main.js")).toBe(true);
expect(isExternal("node:fs")).toBe(true);
});
+
+ test("bundles the component registry without publishing its React dependency tree", () => {
+ expect(isExternal("@webstudio-is/sdk-components-registry/framework")).toBe(
+ false
+ );
+ expect(packageJson.dependencies).not.toHaveProperty(
+ "@webstudio-is/sdk-components-registry"
+ );
+ expect(packageJson.devDependencies).toHaveProperty(
+ "@webstudio-is/sdk-components-registry"
+ );
+ });
});
diff --git a/packages/cli/src/cli.test.ts b/packages/cli/src/cli.test.ts
index 179e1534a3..f5f7454098 100644
--- a/packages/cli/src/cli.test.ts
+++ b/packages/cli/src/cli.test.ts
@@ -1,3 +1,4 @@
+import { readFile } from "node:fs/promises";
import { describe, expect, test, vi } from "vitest";
import makeCLI from "yargs";
import {
@@ -163,9 +164,47 @@ describe("registerCommands", () => {
'{"goal":"design-system-page"}',
]);
expect(getTopLevelMcpToolForwardArgs(["permissions"])).toBeUndefined();
+ expect(getTopLevelMcpToolForwardArgs(["audit"])).toBeUndefined();
+ for (const command of [
+ "get-marketplace-product",
+ "update-marketplace-product",
+ "set-redirects",
+ ]) {
+ expect(
+ getTopLevelMcpToolForwardArgs([command, "--help"])
+ ).toBeUndefined();
+ }
expect(getTopLevelMcpToolForwardArgs(["unknown-command"])).toBeUndefined();
});
+ test.each([
+ "get-marketplace-product",
+ "update-marketplace-product",
+ "set-redirects",
+ ])("shows registered top-level help for %s", async (command) => {
+ const output = await getHelpOutput([command, "--help"]);
+
+ expect(output).toContain(`webstudio ${command}`);
+ expect(output).not.toContain("single-op-call <tool>");
+ });
+
+ test("forwards screenshot JSON input without treating it as a URL", () => {
+ expect(
+ getTopLevelMcpToolForwardArgs([
+ "screenshot",
+ '{"path":"/pricing","viewport":{"width":1440,"height":900}}',
+ ])
+ ).toEqual([
+ "mcp",
+ "single-op-call",
+ "screenshot",
+ '{"path":"/pricing","viewport":{"width":1440,"height":900}}',
+ ]);
+ expect(
+ getTopLevelMcpToolForwardArgs(["screenshot", "https://example.com"])
+ ).toBeUndefined();
+ });
+
test("suggests mcp single-op-call for top-level dotted tool names", () => {
expect(getTopLevelMcpToolHint(["meta.index"])).toContain(
"webstudio meta.index"
@@ -209,7 +248,9 @@ describe("registerCommands", () => {
expect(commandNames(commands)).toEqual(
expect.arrayContaining([
"preview",
+ "connect [client]",
"screenshot [url]",
+ "audit",
"import",
"permissions",
"publish",
@@ -277,6 +318,43 @@ describe("registerCommands", () => {
expect(domainsHelp).toContain("webstudio domains create");
});
+ test("shows audit-specific flags and examples", async () => {
+ const output = await getHelpOutput(["audit", "--help"]);
+
+ expect(output).toContain("webstudio audit");
+ expect(output).toContain("--scopes");
+ expect(output).toContain("--severities");
+ expect(output).toContain("--page-path");
+ expect(output).toContain("--page-id");
+ expect(output).toContain("--limit");
+ expect(output).toContain("--cursor");
+ expect(output).toContain("--verbose");
+ expect(output).toContain("--rendered");
+ expect(output).toContain("--route-example");
+ expect(output).toContain("--image-domain");
+ expect(output).toContain("--confirm-large-run");
+ expect(output).not.toContain("single-op-call <tool>");
+ });
+
+ test("keeps every documented audit CLI example compatible with audit help", async () => {
+ const docs = await readFile(
+ new URL("./docs/api-use-cases.md", import.meta.url),
+ "utf8"
+ );
+ const commands = docs
+ .split("\n")
+ .filter((line) => line.startsWith("- webstudio audit "))
+ .map((line) => line.slice("- webstudio ".length).trim());
+
+ expect(commands.length).toBeGreaterThan(0);
+ for (const command of commands) {
+ const args = command.split(/\s+/).filter((arg) => arg !== "--json");
+ const output = await getHelpOutput([...args, "--help"]);
+ expect(output).toContain("webstudio audit");
+ expect(output).not.toContain("single-op-call <tool>");
+ }
+ });
+
test("documents registry inspection as a read-only nested command", async () => {
const output = await getHelpOutput(["registry", "inspect", "--help"]);
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index 8f96e58902..52806f94eb 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -12,6 +12,7 @@ import { man, manOptions } from "./commands/man";
import { mcp, mcpOptions } from "./commands/mcp";
import { screenshot, screenshotOptions } from "./commands/screenshot";
import { preview, previewOptions } from "./commands/preview";
+import { connect, connectOptions } from "./commands/connect";
import { apiCommand } from "./commands/api-command";
import {
cliCommandGroupMetadata,
@@ -23,6 +24,7 @@ import {
import { schema, schemaOptions } from "./commands/schema";
import { initFlow, initOptions } from "./commands/init-flow";
import { registryInspect, registryInspectOptions } from "./commands/registry";
+import { audit, auditOptions } from "./commands/audit";
import makeCLI from "yargs";
import packageJson from "../package.json" with { type: "json" };
import type { CommonYargsArgv } from "./commands/yargs-types";
@@ -66,9 +68,12 @@ const registerApiCommand = (
);
};
-const topLevelCommandNames: ReadonlySet<string> = new Set(
- topLevelCliCommandMetadata.map((command) => command.command)
-);
+const topLevelCommandNames: ReadonlySet<string> = new Set([
+ ...topLevelCliCommandMetadata.map((command) => command.command),
+ ...cliCommandMetadata.map(
+ (command) => command.cliCommand.split(" ")[0] ?? command.cliCommand
+ ),
+]);
const mcpOnlyToolNames = new Set(
listProjectSessionMcpTools(publicApiOperations)
@@ -135,6 +140,9 @@ export const getTopLevelMcpToolForwardArgs = (args: readonly string[]) => {
if (tool === undefined) {
return;
}
+ if (tool === "screenshot" && rest[0]?.trimStart().startsWith("{")) {
+ return ["mcp", "single-op-call", tool, ...rest];
+ }
if (
/^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/i.test(tool) ||
mcpOnlyToolNames.has(tool)
@@ -190,12 +198,24 @@ export const registerCommands = (cmd: CommonYargsArgv) => {
previewOptions,
preview
);
+ cmd.command(
+ ["connect [client]"],
+ "Generate the MCP client configuration for Claude Code, Codex, Cursor, or VS Code",
+ connectOptions,
+ connect
+ );
cmd.command(
["screenshot [url]"],
"Capture a PNG screenshot of a URL or local generated project route",
screenshotOptions,
screenshot
);
+ cmd.command(
+ ["audit"],
+ "Audit project accessibility, SEO, security, assets, styles, and performance",
+ auditOptions,
+ audit
+ );
cmd.command(
["registry"],
"Inspect external component registries without installing items",
@@ -212,6 +232,9 @@ export const registerCommands = (cmd: CommonYargsArgv) => {
);
const { direct, grouped } = getGroupedCommands(cliCommandMetadata);
for (const metadata of direct) {
+ if (metadata.operation === "audit") {
+ continue;
+ }
registerApiCommand(cmd, metadata.cliCommand, metadata);
}
for (const [group, commands] of grouped) {
diff --git a/packages/cli/src/commands/api-command-metadata.ts b/packages/cli/src/commands/api-command-metadata.ts
index 688f3a1faf..b12a5b61bb 100644
--- a/packages/cli/src/commands/api-command-metadata.ts
+++ b/packages/cli/src/commands/api-command-metadata.ts
@@ -77,6 +77,12 @@ export const topLevelCliCommandMetadata = [
"Regenerate project files, build them, and run the generated project production preview server for visual verification; dependencies must already be installed",
examples: ["webstudio preview --port 5173"],
},
+ {
+ command: "connect",
+ description:
+ "Generate the MCP client configuration for Claude Code, Codex, Cursor, or VS Code",
+ examples: ["webstudio connect claude", "webstudio connect codex"],
+ },
{
command: "screenshot",
description:
diff --git a/packages/cli/src/commands/api-command.test.ts b/packages/cli/src/commands/api-command.test.ts
index d286e98bb6..3cbcb962e7 100644
--- a/packages/cli/src/commands/api-command.test.ts
+++ b/packages/cli/src/commands/api-command.test.ts
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, expect, test, vi } from "vitest";
import makeCLI from "yargs";
import {
getPublicApiOperation,
+ publicApiContractVersion,
publicApiOperations,
} from "@webstudio-is/protocol";
import { apiCompatibilityHeaders } from "./api";
@@ -17,6 +18,7 @@ const apiCalls = new Proxy({} as Record<string, ReturnType<typeof vi.fn>>, {
});
const isFileExists = vi.fn();
const readFile = vi.fn();
+const getServerApiContract = vi.fn();
const apiClientByOperationId = new Map(
publicApiOperations.map((operation) => [operation.id, operation.client])
);
@@ -84,10 +86,12 @@ const dependencies = new Proxy(
isFileExists,
readFile,
createCliProjectSession,
+ getServerApiContract,
} as typeof apiCalls & {
isFileExists: typeof isFileExists;
readFile: typeof readFile;
createCliProjectSession: typeof createCliProjectSession;
+ getServerApiContract: typeof getServerApiContract;
},
{
get(target, property: string) {
@@ -255,6 +259,16 @@ beforeEach(() => {
isFileExists.mockResolvedValue(false);
readFile.mockReset();
createCliProjectSession.mockClear();
+ getServerApiContract.mockReset();
+ getServerApiContract.mockResolvedValue({
+ clientVersion: publicApiContractVersion,
+ serverVersion: publicApiContractVersion,
+ supportedOperationIds: new Set(
+ publicApiOperations.map((operation) => operation.id)
+ ),
+ missingServerOperationIds: [],
+ negotiated: true,
+ });
vi.spyOn(console, "info").mockImplementation(() => undefined);
vi.spyOn(console, "error").mockImplementation(() => undefined);
});
@@ -427,7 +441,7 @@ test("passes refresh to local-capable command session", async () => {
);
const session = createCliProjectSession.mock.results[0]?.value;
- expect(session.refresh).toHaveBeenCalledWith(["pages", "projectSettings"]);
+ expect(session.refresh).toHaveBeenCalledWith(["pages"]);
expect(session.read).toHaveBeenCalledWith(
"pages.list",
{ projectId: "project-1", includeFolders: undefined },
diff --git a/packages/cli/src/commands/api-command.ts b/packages/cli/src/commands/api-command.ts
index ca7a1b4fce..4b56911b06 100644
--- a/packages/cli/src/commands/api-command.ts
+++ b/packages/cli/src/commands/api-command.ts
@@ -9,7 +9,10 @@ import {
createLocalUploadAssetsInput,
LOCAL_ASSETS_DIR,
} from "../asset-files";
-import { createCliProjectSession } from "../project-session";
+import {
+ createCliProjectSession,
+ getCliServerApiContract,
+} from "../project-session";
import {
getCliErrorMessage,
getStableErrorCode,
@@ -32,6 +35,7 @@ type ApiCommandDependencies = typeof apiCommandHttpClient & {
isFileExists: typeof isFileExists;
readFile: typeof readFile;
createCliProjectSession: typeof createCliProjectSession;
+ getServerApiContract: typeof getCliServerApiContract;
};
const defaultDependencies: ApiCommandDependencies = {
@@ -39,6 +43,7 @@ const defaultDependencies: ApiCommandDependencies = {
isFileExists,
readFile,
createCliProjectSession,
+ getServerApiContract: getCliServerApiContract,
};
export type ApiCommandName = ProjectSessionApiCommand;
@@ -1261,7 +1266,7 @@ export const deleteAssetCommandOptions = (yargs: CommonYargsArgv) =>
"Required. Confirm deleting asset records"
);
-type ApiCommandOptions = {
+export type ApiCommandOptions = {
command: ApiCommandName;
json?: boolean;
include?: string[];
@@ -1356,7 +1361,9 @@ type ApiCommandOptions = {
sort?: "name" | "usage" | "size" | "createdAt";
cursor?: string;
limit?: number;
- scopes?: Array<"accessibility" | "security" | "seo" | "assets" | "styles">;
+ scopes?: Array<
+ "accessibility" | "security" | "seo" | "assets" | "styles" | "performance"
+ >;
severities?: Array<"error" | "warning" | "info">;
pageId?: string;
pagePath?: string;
@@ -1781,6 +1788,7 @@ const runProjectSessionCommand = async (
input,
connection,
createProjectSession: dependencies.createCliProjectSession,
+ getServerApiContract: dependencies.getServerApiContract,
dryRun: options.dryRun ?? activeApiCommandDryRun,
refresh: activeApiCommandRefresh,
});
@@ -1791,7 +1799,7 @@ type ApiCommandHandler = (
dependencies: ApiCommandDependencies
) => Promise<unknown>;
-const printAuditReport = (value: unknown) => {
+export const printAuditReport = (value: unknown) => {
if (typeof value !== "object" || value === null) {
console.info("Audit completed.");
return;
@@ -1813,6 +1821,20 @@ const printAuditReport = (value: unknown) => {
manualChecks?: unknown[];
skippedCheckCount?: number;
manualCheckCount?: number;
+ renderedCheckCount?: number;
+ renderedIssueCount?: number;
+ renderedIssueSummaries?: Array<{
+ kind?: string;
+ count?: number;
+ captureCount?: number;
+ pagePaths?: string[];
+ }>;
+ renderedFailureCount?: number;
+ renderedPlan?: {
+ captureCount?: number;
+ confirmationToken?: string;
+ confirmationExpiresAt?: string;
+ } | null;
nextCursor?: string | null;
};
const severity = result.summary?.bySeverity ?? {};
@@ -1845,6 +1867,30 @@ const printAuditReport = (value: unknown) => {
if (manualCheckCount > 0) {
console.info(`${manualCheckCount} manual checks recommended.`);
}
+ if (result.renderedCheckCount !== undefined) {
+ console.info(
+ `Rendered: ${result.renderedCheckCount} checks, ${result.renderedIssueCount ?? 0} issues, ${result.renderedFailureCount ?? 0} failures.`
+ );
+ for (const summary of result.renderedIssueSummaries ?? []) {
+ const pages = summary.pagePaths?.join(", ");
+ console.info(
+ ` ${summary.kind ?? "rendered-issue"}: ${summary.count ?? 0} occurrences across ${summary.captureCount ?? 0} captures${pages === undefined || pages === "" ? "" : ` (${pages})`}.`
+ );
+ }
+ }
+ if (result.renderedPlan?.confirmationToken !== undefined) {
+ console.info(
+ `Rendered plan: ${result.renderedPlan.captureCount ?? 0} captures require confirmation.`
+ );
+ console.info(
+ `Retry with --confirm-large-run --confirmation-token '${result.renderedPlan.confirmationToken}'.`
+ );
+ if (result.renderedPlan.confirmationExpiresAt !== undefined) {
+ console.info(
+ `Confirmation expires at ${result.renderedPlan.confirmationExpiresAt}.`
+ );
+ }
+ }
if (result.nextCursor != null) {
console.info(`More findings: rerun with --cursor '${result.nextCursor}'.`);
}
@@ -2974,7 +3020,7 @@ export const apiCommand = async (
});
}
} catch (error) {
- const message = getCliErrorMessage(error);
+ const message = getCliErrorMessage(error, options.command);
if (options.json === true) {
const code = getErrorCode(error);
printJson({
diff --git a/packages/cli/src/commands/audit.test.ts b/packages/cli/src/commands/audit.test.ts
new file mode 100644
index 0000000000..bc15c0fe0c
--- /dev/null
+++ b/packages/cli/src/commands/audit.test.ts
@@ -0,0 +1,135 @@
+import { describe, expect, test, vi } from "vitest";
+import makeCLI from "yargs";
+import {
+ audit,
+ auditOptions,
+ getRenderedAuditToolInput,
+ parseRouteExamples,
+} from "./audit";
+import type { CommonYargsArgv } from "./yargs-types";
+
+describe("audit CLI input", () => {
+ test("allows static audit pagination without enabling rendered mode", async () => {
+ const parsed = await auditOptions(
+ makeCLI([]).exitProcess(false) as unknown as CommonYargsArgv
+ ).parseAsync(["--cursor", "next-page"]);
+
+ expect(parsed).toMatchObject({ cursor: "next-page" });
+ expect(parsed.rendered).toBeUndefined();
+ });
+
+ test("maps rendered audit flags to the MCP audit input", () => {
+ expect(
+ getRenderedAuditToolInput({
+ scopes: ["accessibility", "seo", "performance"],
+ severities: ["error", "warning"],
+ pagePath: "/pricing",
+ limit: 25,
+ cursor: undefined,
+ pageId: undefined,
+ verbose: true,
+ rendered: true,
+ confirmLargeRun: true,
+ confirmationToken: "confirmation-token",
+ imageDomain: ["storage.example.com"],
+ routeExample: ["post=/blog/hello"],
+ json: true,
+ dryRun: undefined,
+ refresh: undefined,
+ })
+ ).toEqual({
+ scopes: ["accessibility", "seo", "performance"],
+ severities: ["error", "warning"],
+ pagePath: "/pricing",
+ limit: 25,
+ verbose: true,
+ rendered: true,
+ confirmLargeRun: true,
+ confirmationToken: "confirmation-token",
+ imageDomains: ["storage.example.com"],
+ routeExamples: [{ pageId: "post", path: "/blog/hello" }],
+ });
+ });
+
+ test("rejects unresolved dynamic route examples", () => {
+ expect(() => parseRouteExamples(["post=/blog/:slug"])).toThrow(
+ "--route-example must use <pageId>=<concretePath>"
+ );
+ });
+
+ test("forwards shared execution flags to rendered audit", async () => {
+ const apiCommand = vi.fn();
+ const mcpSingleOpCall = vi.fn(async () => undefined);
+
+ await audit(
+ {
+ rendered: true,
+ dryRun: true,
+ refresh: true,
+ json: true,
+ },
+ { apiCommand, mcpSingleOpCall }
+ );
+
+ expect(apiCommand).not.toHaveBeenCalled();
+ expect(mcpSingleOpCall).toHaveBeenCalledWith({
+ tool: "audit",
+ input: JSON.stringify({ rendered: true }),
+ dryRun: true,
+ refresh: true,
+ json: true,
+ });
+ });
+
+ test("prints rendered audits as a concise report unless --json is set", async () => {
+ const apiCommand = vi.fn();
+ const mcpSingleOpCall = vi.fn(async (options) => {
+ options.printSuccess?.({
+ summary: { total: 0 },
+ findings: [],
+ renderedCheckCount: 2,
+ renderedIssueCount: 1,
+ renderedIssueSummaries: [
+ {
+ kind: "oversized-image",
+ count: 1,
+ captureCount: 1,
+ pagePaths: ["/"],
+ },
+ ],
+ renderedFailureCount: 0,
+ renderedPlan: {
+ captureCount: 121,
+ confirmationToken: "confirmation-token",
+ },
+ });
+ });
+ const info = vi.spyOn(console, "info").mockImplementation(() => undefined);
+
+ await audit(
+ { rendered: true, json: false },
+ { apiCommand, mcpSingleOpCall }
+ );
+
+ expect(mcpSingleOpCall).toHaveBeenCalledWith(
+ expect.objectContaining({
+ tool: "audit",
+ json: false,
+ printSuccess: expect.any(Function),
+ })
+ );
+ expect(info).toHaveBeenCalledWith(
+ "Audit: 0 findings (0 errors, 0 warnings, 0 info)"
+ );
+ expect(info).toHaveBeenCalledWith(
+ "Rendered: 2 checks, 1 issues, 0 failures."
+ );
+ expect(info).toHaveBeenCalledWith(
+ " oversized-image: 1 occurrences across 1 captures (/)."
+ );
+ expect(info).toHaveBeenCalledWith(
+ "Retry with --confirm-large-run --confirmation-token 'confirmation-token'."
+ );
+ info.mockRestore();
+ });
+});
diff --git a/packages/cli/src/commands/audit.ts b/packages/cli/src/commands/audit.ts
new file mode 100644
index 0000000000..bff01fc72f
--- /dev/null
+++ b/packages/cli/src/commands/audit.ts
@@ -0,0 +1,112 @@
+import {
+ apiCommand,
+ auditCommandOptions,
+ printAuditReport,
+ type ApiCommandOptions,
+} from "./api-command";
+import { mcpSingleOpCall } from "./mcp";
+import type { CommonYargsArgv } from "./yargs-types";
+
+export const auditOptions = (yargs: CommonYargsArgv) =>
+ auditCommandOptions(yargs)
+ .option("rendered", {
+ type: "boolean",
+ describe:
+ "Build and inspect rendered pages at responsive viewport widths",
+ })
+ .option("confirm-large-run", {
+ type: "boolean",
+ describe:
+ "Confirm a rendered plan above the capture threshold; requires --confirmation-token",
+ })
+ .option("confirmation-token", {
+ type: "string",
+ describe: "Short-lived token returned by an unconfirmed large audit plan",
+ })
+ .option("image-domain", {
+ type: "string",
+ array: true,
+ describe:
+ "External image hostname allowed during rendered audit; repeat for multiple hosts",
+ })
+ .option("route-example", {
+ type: "string",
+ array: true,
+ describe:
+ "Concrete dynamic route as <pageId>=<path>; repeat for multiple pages",
+ })
+ .conflicts("page-id", "page-path")
+ .conflicts("cursor", "rendered")
+ .implies("confirm-large-run", "confirmation-token")
+ .implies("confirmation-token", "rendered")
+ .implies("image-domain", "rendered")
+ .implies("route-example", "rendered")
+ .example(
+ "$0 audit --rendered --verbose --json",
+ "Include responsive rendered checks"
+ );
+
+type AuditOptions = Omit<ApiCommandOptions, "command"> & {
+ rendered?: boolean;
+ confirmLargeRun?: boolean;
+ confirmationToken?: string;
+ imageDomain?: string[];
+ routeExample?: string[];
+};
+
+export const parseRouteExamples = (values: string[] | undefined) =>
+ values?.map((value) => {
+ const separator = value.indexOf("=");
+ const pageId = value.slice(0, separator);
+ const path = value.slice(separator + 1);
+ if (
+ separator < 1 ||
+ /^\/(?!\/)/.test(path) === false ||
+ path.includes(":") ||
+ path.includes("*")
+ ) {
+ throw new Error(
+ "--route-example must use <pageId>=<concretePath>, for example post=/blog/hello."
+ );
+ }
+ return { pageId, path };
+ });
+
+export const getRenderedAuditToolInput = (options: AuditOptions) => ({
+ ...(options.scopes === undefined ? {} : { scopes: options.scopes }),
+ ...(options.severities === undefined
+ ? {}
+ : { severities: options.severities }),
+ ...(options.pagePath === undefined ? {} : { pagePath: options.pagePath }),
+ ...(options.pageId === undefined ? {} : { pageId: options.pageId }),
+ ...(options.limit === undefined ? {} : { limit: options.limit }),
+ ...(options.verbose === true ? { verbose: true } : {}),
+ ...(options.confirmLargeRun === true ? { confirmLargeRun: true } : {}),
+ ...(options.confirmationToken === undefined
+ ? {}
+ : { confirmationToken: options.confirmationToken }),
+ ...(options.imageDomain === undefined
+ ? {}
+ : { imageDomains: options.imageDomain }),
+ ...(options.routeExample === undefined
+ ? {}
+ : { routeExamples: parseRouteExamples(options.routeExample) }),
+ rendered: true,
+});
+
+export const audit = async (
+ options: AuditOptions,
+ dependencies = { apiCommand, mcpSingleOpCall }
+) => {
+ if (options.rendered !== true) {
+ return dependencies.apiCommand({ ...options, command: "audit" });
+ }
+ return dependencies.mcpSingleOpCall({
+ tool: "audit",
+ input: JSON.stringify(getRenderedAuditToolInput(options)),
+ dryRun: options.dryRun,
+ refresh: options.refresh,
+ json: options.json,
+ ...(options.json === true ? {} : { printSuccess: printAuditReport }),
+ });
+};
diff --git a/packages/cli/src/commands/connect.test.ts b/packages/cli/src/commands/connect.test.ts
new file mode 100644
index 0000000000..5c8416b38e
--- /dev/null
+++ b/packages/cli/src/commands/connect.test.ts
@@ -0,0 +1,247 @@
+import { join } from "node:path";
+import { cwd } from "node:process";
+import { expect, test, vi } from "vitest";
+import {
+ connect,
+ createCodexSnippet,
+ defaultServerCommand,
+ mergeServerConfig,
+ type ConnectDependencies,
+} from "./connect";
+import { HandledCliError } from "../errors";
+
+const createDependencies = (
+ files: Record<string, string> = {}
+): ConnectDependencies => ({
+ createFolderIfNotExists: vi.fn(async () => undefined),
+ isFileExists: vi.fn(async (path: string) => {
+ const relativePath = path.startsWith(cwd())
+ ? path.slice(cwd().length + 1)
+ : path;
+ return relativePath in files;
+ }),
+ readFile: vi.fn(async (path: string) => {
+ const relativePath = path.startsWith(cwd())
+ ? path.slice(cwd().length + 1)
+ : path;
+ const content = files[relativePath];
+ if (content === undefined) {
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ }
+ return content;
+ }),
+ writeFileAtomic: vi.fn(async () => undefined),
+});
+
+const linkedProject = { ".webstudio/config.json": "{}" };
+
+test("creates .mcp.json for claude with the default server command", async () => {
+ const dependencies = createDependencies(linkedProject);
+
+ await connect({ client: "claude", print: false }, dependencies);
+
+ expect(dependencies.writeFileAtomic).toHaveBeenCalledWith(
+ join(cwd(), ".mcp.json"),
+ `${JSON.stringify(
+ {
+ mcpServers: {
+ webstudio: {
+ command: "npx",
+ args: ["-y", "webstudio@latest", "mcp"],
+ },
+ },
+ },
+ null,
+ 2
+ )}\n`
+ );
+});
+
+test("merges the webstudio entry into an existing config preserving user fields", async () => {
+ const dependencies = createDependencies({
+ ...linkedProject,
+ ".mcp.json": JSON.stringify({
+ mcpServers: { other: { command: "other-server", args: [] } },
+ customField: true,
+ }),
+ });
+
+ await connect({ client: "claude", print: false }, dependencies);
+
+ const [, content] = vi.mocked(dependencies.writeFileAtomic).mock.calls[0];
+ expect(JSON.parse(content)).toEqual({
+ mcpServers: {
+ other: { command: "other-server", args: [] },
+ webstudio: {
+ command: "npx",
+ args: ["-y", "webstudio@latest", "mcp"],
+ },
+ },
+ customField: true,
+ });
+});
+
+test("does not rewrite an already configured client", async () => {
+ const dependencies = createDependencies({
+ ...linkedProject,
+ ".mcp.json": JSON.stringify({
+ mcpServers: {
+ webstudio: {
+ command: "npx",
+ args: ["-y", "webstudio@latest", "mcp"],
+ },
+ },
+ }),
+ });
+
+ await connect({ client: "claude", print: false }, dependencies);
+
+ expect(dependencies.writeFileAtomic).not.toHaveBeenCalled();
+});
+
+test("blocks on invalid json without touching the file", async () => {
+ const dependencies = createDependencies({
+ ...linkedProject,
+ ".mcp.json": "not json",
+ });
+
+ await expect(
+ connect({ client: "claude", print: false }, dependencies)
+ ).rejects.toThrow(HandledCliError);
+ expect(dependencies.writeFileAtomic).not.toHaveBeenCalled();
+});
+
+test("writes the vscode schema with servers root key and stdio type", async () => {
+ const dependencies = createDependencies(linkedProject);
+
+ await connect({ client: "vscode", print: false }, dependencies);
+
+ expect(dependencies.writeFileAtomic).toHaveBeenCalledWith(
+ join(cwd(), ".vscode", "mcp.json"),
+ `${JSON.stringify(
+ {
+ servers: {
+ webstudio: {
+ type: "stdio",
+ command: "npx",
+ args: ["-y", "webstudio@latest", "mcp"],
+ },
+ },
+ },
+ null,
+ 2
+ )}\n`
+ );
+});
+
+test("writes the cursor config into .cursor/mcp.json", async () => {
+ const dependencies = createDependencies(linkedProject);
+
+ await connect({ client: "cursor", print: false }, dependencies);
+
+ expect(dependencies.writeFileAtomic).toHaveBeenCalledWith(
+ join(cwd(), ".cursor", "mcp.json"),
+ expect.stringContaining('"mcpServers"')
+ );
+});
+
+test("prints codex snippet without writing files", async () => {
+ const dependencies = createDependencies(linkedProject);
+
+ await connect({ client: "codex", print: false }, dependencies);
+
+ expect(dependencies.writeFileAtomic).not.toHaveBeenCalled();
+});
+
+test("prints configuration without writing when print is requested", async () => {
+ const dependencies = createDependencies(linkedProject);
+
+ await connect({ client: "claude", print: true }, dependencies);
+
+ expect(dependencies.writeFileAtomic).not.toHaveBeenCalled();
+});
+
+test("lists supported clients when no client is provided", async () => {
+ const dependencies = createDependencies(linkedProject);
+
+ await connect({ client: undefined, print: false }, dependencies);
+
+ expect(dependencies.writeFileAtomic).not.toHaveBeenCalled();
+ expect(dependencies.isFileExists).not.toHaveBeenCalled();
+});
+
+test("uses a custom server command", async () => {
+ const dependencies = createDependencies(linkedProject);
+
+ await connect(
+ {
+ client: "claude",
+ print: false,
+ command: "node packages/cli/local.js mcp",
+ },
+ dependencies
+ );
+
+ const [, content] = vi.mocked(dependencies.writeFileAtomic).mock.calls[0];
+ expect(JSON.parse(content).mcpServers.webstudio).toEqual({
+ command: "node",
+ args: ["packages/cli/local.js", "mcp"],
+ });
+});
+
+test("rejects an empty server command", async () => {
+ const dependencies = createDependencies(linkedProject);
+
+ await expect(
+ connect({ client: "claude", print: false, command: " " }, dependencies)
+ ).rejects.toThrow("--command must not be empty.");
+});
+
+test("renders the codex toml snippet", () => {
+ expect(createCodexSnippet(defaultServerCommand)).toBe(
+ [
+ "[mcp_servers.webstudio]",
+ 'command = "npx"',
+ 'args = ["-y", "webstudio@latest", "mcp"]',
+ ].join("\n")
+ );
+});
+
+test("merge keeps result unchanged only for a deep-equal server entry", () => {
+ const serverEntry = {
+ command: "npx",
+ args: ["-y", "webstudio@latest", "mcp"],
+ };
+ expect(
+ mergeServerConfig({
+ current: JSON.stringify({
+ mcpServers: {
+ webstudio: { command: "npx", args: ["-y", "webstudio"] },
+ },
+ }),
+ rootKey: "mcpServers",
+ serverEntry,
+ }).result
+ ).toBe("updated");
+ expect(
+ mergeServerConfig({
+ current: JSON.stringify({ mcpServers: { webstudio: serverEntry } }),
+ rootKey: "mcpServers",
+ serverEntry,
+ }).result
+ ).toBe("unchanged");
+ expect(
+ mergeServerConfig({
+ current: JSON.stringify([1, 2]),
+ rootKey: "mcpServers",
+ serverEntry,
+ }).result
+ ).toBe("blocked-by-invalid-json");
+ expect(
+ mergeServerConfig({
+ current: undefined,
+ rootKey: "mcpServers",
+ serverEntry,
+ }).result
+ ).toBe("created");
+});
diff --git a/packages/cli/src/commands/connect.ts b/packages/cli/src/commands/connect.ts
new file mode 100644
index 0000000000..b42694422b
--- /dev/null
+++ b/packages/cli/src/commands/connect.ts
@@ -0,0 +1,276 @@
+import { readFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { cwd } from "node:process";
+import { log } from "@clack/prompts";
+import {
+ createFolderIfNotExists,
+ isFileExists,
+ writeFileAtomic,
+} from "../fs-utils";
+import { LOCAL_CONFIG_FILE } from "../config";
+import { HandledCliError } from "../errors";
+import type {
+ CommonYargsArgv,
+ StrictYargsOptionsToInterface,
+} from "./yargs-types";
+
+export const connectClients = ["claude", "codex", "cursor", "vscode"] as const;
+export type ConnectClient = (typeof connectClients)[number];
+
+export const defaultServerCommand = "npx -y webstudio@latest mcp";
+
+export const mcpServerName = "webstudio";
+
+export type ConnectFileResult =
+ | "created"
+ | "updated"
+ | "unchanged"
+ | "blocked-by-invalid-json";
+
+type JsonClientTarget = {
+ /**
+ * Config file path relative to the project root.
+ */
+ path: string;
+ /**
+ * Root object key holding server entries in the client config schema.
+ */
+ rootKey: "mcpServers" | "servers";
+ /**
+ * Extra fields required by the client config schema.
+ */
+ extraServerFields?: Record<string, unknown>;
+ /**
+ * One-line reload hint printed after the config is written.
+ */
+ hint: string;
+};
+
+const jsonClientTargets: Record<
+ Exclude<ConnectClient, "codex">,
+ JsonClientTarget
+> = {
+ claude: {
+ path: ".mcp.json",
+ rootKey: "mcpServers",
+ hint: "Restart Claude Code in this directory and approve the webstudio server.",
+ },
+ cursor: {
+ path: join(".cursor", "mcp.json"),
+ rootKey: "mcpServers",
+ hint: "Reload Cursor and enable the webstudio server in MCP settings.",
+ },
+ vscode: {
+ path: join(".vscode", "mcp.json"),
+ rootKey: "servers",
+ extraServerFields: { type: "stdio" },
+ hint: "Reload VS Code and start the webstudio server from the MCP view.",
+ },
+};
+
+const parseServerCommand = (serverCommand: string) => {
+ const [command, ...args] = serverCommand.trim().split(/\s+/);
+ if (command === undefined || command === "") {
+ throw new Error("--command must not be empty.");
+ }
+ return { command, args };
+};
+
+export const createServerEntry = (
+ serverCommand: string,
+ extraServerFields?: Record<string, unknown>
+) => {
+ const { command, args } = parseServerCommand(serverCommand);
+ return { ...extraServerFields, command, args };
+};
+
+export const createCodexSnippet = (serverCommand: string) => {
+ const { command, args } = parseServerCommand(serverCommand);
+ return [
+ `[mcp_servers.${mcpServerName}]`,
+ `command = ${JSON.stringify(command)}`,
+ `args = [${args.map((arg) => JSON.stringify(arg)).join(", ")}]`,
+ ].join("\n");
+};
+
+const isJsonObject = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && Array.isArray(value) === false;
+
+/**
+ * Merge the webstudio server entry into an existing client config while
+ * preserving every user-owned field and other configured servers. Only the
+ * `<rootKey>.webstudio` entry is ever created or replaced.
+ */
+export const mergeServerConfig = ({
+ current,
+ rootKey,
+ serverEntry,
+}: {
+ current: string | undefined;
+ rootKey: string;
+ serverEntry: Record<string, unknown>;
+}): { content?: string; result: ConnectFileResult } => {
+ let config: Record<string, unknown> = {};
+ if (current !== undefined) {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(current);
+ } catch {
+ return { result: "blocked-by-invalid-json" };
+ }
+ if (isJsonObject(parsed) === false) {
+ return { result: "blocked-by-invalid-json" };
+ }
+ config = parsed;
+ }
+ const servers = isJsonObject(config[rootKey]) ? config[rootKey] : {};
+ if (JSON.stringify(servers[mcpServerName]) === JSON.stringify(serverEntry)) {
+ return { result: "unchanged" };
+ }
+ const content = `${JSON.stringify(
+ { ...config, [rootKey]: { ...servers, [mcpServerName]: serverEntry } },
+ null,
+ 2
+ )}\n`;
+ return { content, result: current === undefined ? "created" : "updated" };
+};
+
+export type ConnectDependencies = {
+ createFolderIfNotExists: typeof createFolderIfNotExists;
+ isFileExists: typeof isFileExists;
+ readFile: (path: string, encoding: "utf8") => Promise<string>;
+ writeFileAtomic: typeof writeFileAtomic;
+};
+
+const defaultDependencies: ConnectDependencies = {
+ createFolderIfNotExists,
+ isFileExists,
+ readFile,
+ writeFileAtomic,
+};
+
+export const connectOptions = (yargs: CommonYargsArgv) =>
+ yargs
+ .positional("client", {
+ type: "string",
+ choices: connectClients,
+ describe: "Agent client to generate the MCP configuration for",
+ })
+ .option("command", {
+ type: "string",
+ default: defaultServerCommand,
+ describe:
+ "Command used by the client to start the Webstudio MCP server over stdio",
+ })
+ .option("print", {
+ type: "boolean",
+ default: false,
+ describe: "Print the configuration instead of writing the config file",
+ })
+ .example(
+ "webstudio connect claude",
+ "Write .mcp.json so Claude Code can operate the linked project"
+ )
+ .example(
+ "webstudio connect codex",
+ "Print the Codex config.toml snippet and the codex mcp add command"
+ )
+ .example(
+ "webstudio connect cursor --print",
+ "Print the Cursor MCP configuration without writing .cursor/mcp.json"
+ )
+ .epilogue(
+ [
+ "Connect generates the exact MCP client configuration for the current project directory.",
+ "Existing config files are merged: only the webstudio server entry is created or replaced.",
+ "Run webstudio link and webstudio sync first so the MCP server can operate the project.",
+ ].join("\n")
+ );
+
+type ConnectOptions = Partial<
+ StrictYargsOptionsToInterface<typeof connectOptions>
+>;
+
+export const connect = async (
+ options: ConnectOptions,
+ dependencies: ConnectDependencies = defaultDependencies
+) => {
+ const serverCommand = options.command ?? defaultServerCommand;
+ const client = options.client;
+
+ if (client === undefined) {
+ log.message(
+ [
+ "Specify the agent client to connect:",
+ ...connectClients.map((name) => ` webstudio connect ${name}`),
+ ].join("\n")
+ );
+ return;
+ }
+
+ if ((await dependencies.isFileExists(LOCAL_CONFIG_FILE)) === false) {
+ log.warn(
+ "This directory has no linked Webstudio project. The MCP server needs one at runtime: run `webstudio link` and `webstudio sync` before using the agent."
+ );
+ }
+
+ if (client === "codex") {
+ const snippet = createCodexSnippet(serverCommand);
+ log.message(
+ [
+ "Codex reads MCP servers from ~/.codex/config.toml. Add the server with:",
+ "",
+ ` codex mcp add ${mcpServerName} -- ${serverCommand}`,
+ "",
+ "or append this snippet to ~/.codex/config.toml:",
+ "",
+ snippet,
+ ].join("\n")
+ );
+ return;
+ }
+
+ const target = jsonClientTargets[client];
+ const serverEntry = createServerEntry(
+ serverCommand,
+ target.extraServerFields
+ );
+
+ if (options.print === true) {
+ const { content } = mergeServerConfig({
+ current: undefined,
+ rootKey: target.rootKey,
+ serverEntry,
+ });
+ log.message(`${target.path}\n\n${content}`);
+ return;
+ }
+
+ const path = join(cwd(), target.path);
+ const current = (await dependencies.isFileExists(path))
+ ? await dependencies.readFile(path, "utf8")
+ : undefined;
+ const { content, result } = mergeServerConfig({
+ current,
+ rootKey: target.rootKey,
+ serverEntry,
+ });
+
+ if (result === "blocked-by-invalid-json") {
+ log.error(
+ `${target.path} exists but is not a valid JSON object. Fix or remove it, then run webstudio connect ${client} again.`
+ );
+ throw new HandledCliError();
+ }
+
+ if (result === "unchanged") {
+ log.success(`${target.path} is already configured. ${target.hint}`);
+ return;
+ }
+
+ await dependencies.createFolderIfNotExists(dirname(path));
+ await dependencies.writeFileAtomic(path, content ?? "");
+ log.success(
+ `${result === "created" ? "Created" : "Updated"} ${target.path} with the ${mcpServerName} MCP server. ${target.hint}`
+ );
+};
diff --git a/packages/cli/src/commands/link.ts b/packages/cli/src/commands/link.ts
index 05d3a43e01..006c55f68c 100644
--- a/packages/cli/src/commands/link.ts
+++ b/packages/cli/src/commands/link.ts
@@ -156,5 +156,7 @@ export const link = async (
const { projectId } = await saveShareLink(shareLink);
log.info(`Saved credentials for project ${projectId}.
You can find your config at ${GLOBAL_CONFIG_FILE}`);
- log.step("The project is linked successfully");
+ log.step(
+ "The project is linked successfully. Next run `webstudio sync`, then `webstudio connect` to configure an agent."
+ );
};
diff --git a/packages/cli/src/commands/man.test.ts b/packages/cli/src/commands/man.test.ts
index f70b98e6b4..849e19933f 100644
--- a/packages/cli/src/commands/man.test.ts
+++ b/packages/cli/src/commands/man.test.ts
@@ -145,6 +145,7 @@ test("prints api manual as json", () => {
"import",
"build",
"preview",
+ "connect",
"screenshot",
"permissions",
"publish",
diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.ts
index d8945652af..d6530c78cf 100644
--- a/packages/cli/src/commands/mcp.test.ts
+++ b/packages/cli/src/commands/mcp.test.ts
@@ -2,7 +2,6 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, expect, test, vi } from "vitest";
-import { builderNamespaces } from "@webstudio-is/project-build/contracts/namespaces";
import { __testing__, mcpOptions, prepareMcpProjectSession } from "./mcp";
const {
@@ -20,10 +19,41 @@ const {
parseMcpRunCalls,
parseMcpRunInput,
parseMcpSingleOpCallInput,
+ validateSingleOpCallInput,
+ isMcpToolCallFailure,
+ getMcpToolCallError,
readPersistedMcpCheckpoint,
updatePersistedMcpCheckpoint,
} = __testing__;
+test("classifies structured MCP tool failures for nonzero CLI exit", () => {
+ expect(
+ isMcpToolCallFailure({
+ isError: true,
+ structuredContent: { ok: false },
+ })
+ ).toBe(true);
+ expect(
+ isMcpToolCallFailure({
+ structuredContent: { ok: false },
+ })
+ ).toBe(true);
+ expect(
+ isMcpToolCallFailure({
+ structuredContent: { ok: true },
+ })
+ ).toBe(false);
+ expect(
+ getMcpToolCallError({
+ isError: true,
+ structuredContent: {
+ ok: false,
+ error: { code: "AUDIT_FAILED", message: "Capture failed." },
+ },
+ })
+ ).toEqual({ code: "AUDIT_FAILED", message: "Capture failed." });
+});
+
const tempDirs: string[] = [];
type CommandBuilder = (yargs: unknown) => unknown;
type CommandCall = [readonly string[], string, CommandBuilder, unknown];
@@ -150,9 +180,9 @@ test("documents MCP stdio startup and discovery tools", () => {
);
});
-test("marks cached namespaces stale before serving MCP tools", async () => {
+test("preserves an existing local snapshot before serving MCP tools", async () => {
const session = {
- snapshot: undefined,
+ snapshot: { version: 42 } as never,
initialize: vi.fn(async () => undefined),
markStale: vi.fn(async () => undefined),
};
@@ -160,7 +190,7 @@ test("marks cached namespaces stale before serving MCP tools", async () => {
await prepareMcpProjectSession(session);
expect(session.initialize).toHaveBeenCalled();
- expect(session.markStale).toHaveBeenCalledWith(builderNamespaces);
+ expect(session.markStale).not.toHaveBeenCalled();
});
test("preview session materialization uses the loaded local snapshot", () => {
@@ -191,12 +221,24 @@ test("reports sparse MCP startup status lines for agents", () => {
reporter.starting();
reporter.sessionReady();
+ reporter.apiContract({
+ clientVersion: "public-api:client",
+ serverVersion: "public-api:server",
+ supportedOperationIds: new Set(),
+ missingServerOperationIds: ["assets.upload"],
+ negotiated: true,
+ });
reporter.ready(12);
+ reporter.connectionError(new Error("connection reset"));
+ reporter.connectionClosed();
expect(lines).toEqual([
`[webstudio mcp] starting stdio server from ${process.cwd()}`,
- "[webstudio mcp] project session initialized; cached namespaces marked stale",
+ "[webstudio mcp] project session initialized; existing local snapshot preserved",
+ "[webstudio mcp] API contract negotiated: CLI 0.0.0-webstudio-version (public-api:client); server public-api:server; unavailable server procedures: assets.upload",
"[webstudio mcp] ready with 12 tools; use tools/list, meta.index, or webstudio://project/guide; waiting for JSON-RPC on stdin",
+ '[webstudio mcp] lifecycle {"event":"stdio_transport_error","message":"connection reset","recovery":"Reconnect the MCP client. If the error repeats, restart the CLI with npx webstudio@latest mcp."}',
+ '[webstudio mcp] lifecycle {"event":"stdio_connection_closed","recovery":"Reconnect the MCP client if this was unexpected."}',
]);
});
@@ -275,6 +317,58 @@ test("rejects long-lived preview tools in MCP single-op-call", () => {
expect(() => assertSingleOpCallToolSupported("preview.status")).not.toThrow();
});
+test("rejects audit input conflicts before creating a project session", () => {
+ for (const input of [
+ { pageId: "home", pagePath: "/" },
+ { rendered: true, cursor: "next" },
+ ]) {
+ expect(() => validateSingleOpCallInput("audit", input)).toThrow(
+ "Audit input is invalid."
+ );
+ try {
+ validateSingleOpCallInput("audit", input);
+ } catch (error) {
+ expect(error).toMatchObject({
+ code: "INVALID_INPUT",
+ issues: [
+ expect.objectContaining({
+ path: expect.any(Array),
+ message: expect.any(String),
+ }),
+ ],
+ });
+ }
+ }
+});
+
+test("preserves structured input issues in MCP shell errors", () => {
+ expect(
+ createMcpSingleOpCallErrorPayload({
+ error: Object.assign(new Error("Audit input is invalid."), {
+ code: "INVALID_INPUT",
+ issues: [
+ {
+ path: ["pagePath"],
+ message: "pageId and pagePath are mutually exclusive.",
+ },
+ ],
+ }),
+ elapsedMs: 1,
+ })
+ ).toMatchObject({
+ ok: false,
+ error: {
+ code: "INVALID_INPUT",
+ issues: [
+ {
+ path: ["pagePath"],
+ message: "pageId and pagePath are mutually exclusive.",
+ },
+ ],
+ },
+ });
+});
+
test("parses MCP run call arrays", () => {
expect(
parseMcpRunCalls([
@@ -860,6 +954,36 @@ test("passes explicit preview source to preview preparation", async () => {
]);
});
+test("rejects invalid external image domains before preparing preview", async () => {
+ const preview = {
+ status: vi.fn(() => ({ url: "", running: false })),
+ startAndWait: vi.fn(),
+ resolveUrl: vi.fn(),
+ };
+ const preparePreview = vi.fn();
+ const handlers = createMcpPreviewHandlers({ preview, preparePreview });
+
+ await expect(
+ handlers.startPreview({
+ imageDomains: ["https://images.example.com/path"],
+ })
+ ).rejects.toThrow(
+ "Image domains must be hostnames without a protocol or path"
+ );
+ await expect(
+ handlers.captureScreenshot({
+ path: "/",
+ imageDomains: ["https://images.example.com/path"],
+ viewport: { width: 1440, height: 900 },
+ })
+ ).rejects.toThrow(
+ "Image domains must be hostnames without a protocol or path"
+ );
+
+ expect(preparePreview).not.toHaveBeenCalled();
+ expect(preview.startAndWait).not.toHaveBeenCalled();
+});
+
test("captures fresh path screenshots through the running preview server", async () => {
const events: string[] = [];
const preview = {
@@ -911,6 +1035,129 @@ test("captures fresh path screenshots through the running preview server", async
]);
});
+test("reuses and closes one browser capture session for session screenshots", async () => {
+ const preview = {
+ status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),
+ startAndWait: vi.fn(),
+ resolveUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),
+ stop: vi.fn(async () => ({ url: "", running: false })),
+ };
+ const capture = createCaptureScreenshotMock([]);
+ const close = vi.fn(async () => undefined);
+ const capturePage = vi.fn(async () => []);
+ const createCaptureSession = vi.fn(() => ({ capture, capturePage, close }));
+ const handlers = createMcpPreviewHandlers({
+ preview,
+ isStale: () => false,
+ createCaptureSession,
+ });
+
+ await handlers.captureScreenshot({
+ path: "/one",
+ source: "session",
+ viewport: { width: 1440, height: 900 },
+ });
+ await handlers.captureScreenshot({
+ path: "/two",
+ source: "session",
+ viewport: { width: 390, height: 844 },
+ });
+
+ expect(createCaptureSession).toHaveBeenCalledOnce();
+ expect(capture).toHaveBeenCalledTimes(2);
+ expect(close).not.toHaveBeenCalled();
+
+ await handlers.stopPreview();
+
+ expect(close).toHaveBeenCalledOnce();
+ expect(preview.stop).toHaveBeenCalledOnce();
+});
+
+test("stops the owned preview when browser capture cleanup fails", async () => {
+ const preview = {
+ status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),
+ startAndWait: vi.fn(),
+ resolveUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),
+ stop: vi.fn(async () => ({ url: "", running: false })),
+ };
+ const cleanupError = new Error("browser cleanup failed");
+ const createCaptureSession = vi.fn(() => ({
+ capture: createCaptureScreenshotMock([]),
+ capturePage: vi.fn(async () => []),
+ close: vi.fn(async () => {
+ throw cleanupError;
+ }),
+ }));
+ const handlers = createMcpPreviewHandlers({
+ preview,
+ isStale: () => false,
+ createCaptureSession,
+ });
+
+ await handlers.captureScreenshot({
+ path: "/one",
+ source: "session",
+ viewport: { width: 1440, height: 900 },
+ });
+
+ await expect(handlers.stopPreview()).rejects.toBe(cleanupError);
+ expect(preview.stop).toHaveBeenCalledOnce();
+});
+
+test("captures one session page across multiple viewports through resize", async () => {
+ const preview = {
+ status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),
+ startAndWait: vi.fn(),
+ resolveUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),
+ };
+ const capture = createCaptureScreenshotMock([]);
+ const capturePage = vi.fn(
+ async (optionsList) => await Promise.all(optionsList.map(capture))
+ );
+ const close = vi.fn(async () => undefined);
+ const createCaptureSession = vi.fn(() => ({
+ capture,
+ capturePage,
+ close,
+ }));
+ const handlers = createMcpPreviewHandlers({
+ preview,
+ isStale: () => false,
+ createCaptureSession,
+ });
+
+ const results = await handlers.capturePageScreenshots([
+ {
+ path: "/responsive",
+ source: "session",
+ viewport: { width: 375, height: 812 },
+ waitForTimeout: 0,
+ },
+ {
+ path: "/responsive",
+ source: "session",
+ viewport: { width: 1440, height: 900 },
+ waitForTimeout: 0,
+ },
+ ]);
+
+ expect(results.map((result) => result.viewport.width)).toEqual([375, 1440]);
+ expect(createCaptureSession).toHaveBeenCalledOnce();
+ expect(capturePage).toHaveBeenCalledWith([
+ expect.objectContaining({
+ url: "http://127.0.0.1:3000/responsive",
+ width: 375,
+ waitForTimeout: 0,
+ }),
+ expect.objectContaining({
+ url: "http://127.0.0.1:3000/responsive",
+ width: 1440,
+ waitForTimeout: 0,
+ }),
+ ]);
+ expect(preview.startAndWait).not.toHaveBeenCalled();
+});
+
test("captures path screenshots through an existing base URL without preview", async () => {
const events: string[] = [];
const preview = {
@@ -954,6 +1201,34 @@ test("captures path screenshots through an existing base URL without preview", a
]);
});
+test("rejects authenticated Builder URLs as generated preview targets", async () => {
+ const preview = {
+ status: vi.fn(),
+ startAndWait: vi.fn(),
+ resolveUrl: vi.fn(),
+ };
+ const captureScreenshot = vi.fn();
+ const handlers = createMcpPreviewHandlers({ preview, captureScreenshot });
+
+ await expect(
+ handlers.captureScreenshot({
+ url: "https://p-project.wstd.dev:5173/?authToken=secret&mode=design",
+ viewport: { width: 1440, height: 900 },
+ })
+ ).rejects.toMatchObject({ code: "BUILDER_URL_IS_NOT_SITE_PREVIEW" });
+ await expect(
+ handlers.captureScreenshot({
+ baseUrl:
+ "https://p-project.apps.webstudio.is/?authToken=secret&mode=preview",
+ path: "/pricing",
+ viewport: { width: 1440, height: 900 },
+ })
+ ).rejects.toMatchObject({ code: "BUILDER_URL_IS_NOT_SITE_PREVIEW" });
+
+ expect(captureScreenshot).not.toHaveBeenCalled();
+ expect(preview.startAndWait).not.toHaveBeenCalled();
+});
+
test("captures path screenshots through an explicit preview target", async () => {
const events: string[] = [];
const preview = {
diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.ts
index 75e9f6ed32..9bcca31199 100644
--- a/packages/cli/src/commands/mcp.ts
+++ b/packages/cli/src/commands/mcp.ts
@@ -6,13 +6,14 @@ import {
createProjectSessionMcpCore,
createMcpStdioTransport,
} from "@webstudio-is/project-build/mcp";
-import {
- builderNamespaces,
- type BuilderNamespace,
-} from "@webstudio-is/project-build/contracts/namespaces";
+import type { BuilderNamespace } from "@webstudio-is/project-build/contracts/namespaces";
import { diffPngFiles } from "@webstudio-is/project-build/visual/screenshot-diff";
-import { publicApiOperations } from "@webstudio-is/protocol";
+import {
+ publicApiOperationRequiresServerSupport,
+ publicApiOperations,
+} from "@webstudio-is/protocol";
import { importProjectBundleWithAssets } from "@webstudio-is/http-client";
+import packageJson from "../../package.json" with { type: "json" };
import type { ProjectSessionSnapshot } from "@webstudio-is/project-build/project-session";
import { resolveApiConnection } from "../api-connection";
import {
@@ -23,13 +24,18 @@ import {
import { HandledCliError, isHandledCliError } from "../errors";
import { loadJSONFile } from "../fs-utils";
import {
+ assertCliServerOperationSupported,
createCliProjectSession,
+ getCliServerApiContract,
+ getSupportedPublicApiOperations,
+ type CliServerApiContract,
writeCliProjectSessionDataFile,
} from "../project-session";
import { executeProjectSessionApiOperation } from "../project-session-api";
import { createPreviewController } from "../preview-server";
import {
captureScreenshotWithBrowserInstall,
+ createScreenshotCaptureSession,
installTesseractForOcr,
} from "../screenshot";
import {
@@ -65,12 +71,14 @@ type StartableProjectSession = {
type McpPreviewController = Pick<
ReturnType<typeof createPreviewController>,
"startAndWait" | "status" | "resolveUrl"
->;
+> &
+ Partial<Pick<ReturnType<typeof createPreviewController>, "stop">>;
type McpPreviewInput = {
host?: string;
port?: number;
source?: PreviewSource;
+ imageDomains?: string[];
};
type CaptureScreenshotInput = Parameters<
@@ -84,6 +92,7 @@ type McpScreenshotInput = {
output?: string;
host?: string;
port?: number;
+ imageDomains?: string[];
viewport: { width: number; height: number };
fullPage?: boolean;
includeImageMetrics?: boolean;
@@ -95,6 +104,9 @@ type McpScreenshotInput = {
waitForTimeout?: number;
timeout?: number;
source?: PreviewSource;
+ format?: "png" | "jpeg" | "webp";
+ quality?: number;
+ scale?: number;
};
type McpToolProgress = {
@@ -116,11 +128,11 @@ export const prepareMcpProjectSession = async (
session: StartableProjectSession
) => {
await session.initialize();
- await session.markStale(builderNamespaces);
};
const mcpStatusPrefix = "[webstudio mcp]";
const mcpCheckpointFile = ".webstudio/mcp-checkpoint.json";
+const renderedAuditArtifactDirectory = ".webstudio/audits";
export const formatMcpStatusLine = (message: string) =>
`${mcpStatusPrefix} ${message}`;
@@ -137,7 +149,7 @@ export const createMcpStatusReporter = (
sessionReady() {
write(
formatMcpStatusLine(
- "project session initialized; cached namespaces marked stale"
+ "project session initialized; existing local snapshot preserved"
)
);
},
@@ -148,6 +160,29 @@ export const createMcpStatusReporter = (
)
);
},
+ apiContract(contract: CliServerApiContract) {
+ const serverVersion = contract.serverVersion ?? "legacy/unavailable";
+ const unavailable = contract.missingServerOperationIds.join(", ") || "none";
+ write(
+ formatMcpStatusLine(
+ `API contract negotiated: CLI ${packageJson.version} (${contract.clientVersion}); server ${serverVersion}; unavailable server procedures: ${unavailable}`
+ )
+ );
+ },
+ connectionClosed() {
+ write(
+ formatMcpStatusLine(
+ `lifecycle ${JSON.stringify({ event: "stdio_connection_closed", recovery: "Reconnect the MCP client if this was unexpected." })}`
+ )
+ );
+ },
+ connectionError(error: Error) {
+ write(
+ formatMcpStatusLine(
+ `lifecycle ${JSON.stringify({ event: "stdio_transport_error", message: getCliErrorMessage(error), recovery: "Reconnect the MCP client. If the error repeats, restart the CLI with npx webstudio@latest mcp." })}`
+ )
+ );
+ },
});
const isRecord = (value: unknown): value is Record<string, unknown> =>
@@ -311,6 +346,7 @@ const prepareDefaultPreviewProject = (
generate: true,
source,
syncIfMissing: true,
+ silent: true,
prepareSessionDataFile,
});
@@ -331,6 +367,7 @@ const createMcpPreviewHandlers = ({
preparePreview = prepareDefaultPreviewProject,
prepareSessionDataFile,
captureScreenshot = captureScreenshotWithBrowserInstall,
+ createCaptureSession,
}: {
preview: McpPreviewController;
isStale?: () => boolean;
@@ -338,91 +375,217 @@ const createMcpPreviewHandlers = ({
preparePreview?: typeof prepareDefaultPreviewProject;
prepareSessionDataFile?: () => Promise<void>;
captureScreenshot?: typeof captureScreenshotWithBrowserInstall;
-}) => ({
- async startPreview(input: McpPreviewInput, progress?: McpToolProgress) {
- validatePreviewServerOptions({
- host: input.host ?? "127.0.0.1",
- port: input.port ?? 5173,
- });
- progress?.report("tool preview.start preparing generated preview project");
- const previewProject = await preparePreview(
- input.source,
- prepareSessionDataFile
- );
- progress?.report("tool preview.start starting production preview server");
- const result = await preview.startAndWait({
- ...input,
- cwd: previewProject.cwd,
- restart: true,
- });
- markFresh();
- return result;
- },
- async captureScreenshot(
+ createCaptureSession?: typeof createScreenshotCaptureSession;
+}) => {
+ let captureSession:
+ | ReturnType<typeof createScreenshotCaptureSession>
+ | undefined;
+ const closeCaptureSession = async () => {
+ try {
+ await captureSession?.close();
+ } finally {
+ captureSession = undefined;
+ }
+ };
+ const rejectBuilderUrl = (value: string) => {
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ return;
+ }
+ const isProjectHost =
+ url.hostname.startsWith("p-") &&
+ (url.hostname.endsWith(".wstd.dev") ||
+ url.hostname.endsWith(".apps.webstudio.is"));
+ if (
+ isProjectHost &&
+ url.searchParams.has("authToken") &&
+ url.searchParams.has("mode")
+ ) {
+ throw Object.assign(
+ new Error(
+ "This is an authenticated Builder/share URL, not a generated-site preview. Use the share URL with webstudio init --link, then capture a generated route with screenshot { path }, or pass an intentional standalone site URL without Builder authentication parameters."
+ ),
+ { code: "BUILDER_URL_IS_NOT_SITE_PREVIEW" }
+ );
+ }
+ };
+ const resolveScreenshotUrl = async (
input: McpScreenshotInput,
progress?: McpToolProgress
- ) {
- const captureResolvedScreenshot = async (url: string) => {
+ ) => {
+ if (input.url !== undefined) {
+ rejectBuilderUrl(input.url);
+ return input.url;
+ }
+ if (input.path === undefined) {
+ throw new Error("MCP screenshot requires url or path.");
+ }
+ if (input.baseUrl !== undefined) {
+ rejectBuilderUrl(input.baseUrl);
+ return new URL(input.path, input.baseUrl).toString();
+ }
+ const hasExplicitPreviewTarget =
+ input.host !== undefined || input.port !== undefined;
+ if (
+ preview.status().running === false ||
+ isStale() ||
+ hasExplicitPreviewTarget
+ ) {
+ await closeCaptureSession();
+ validatePreviewServerOptions({
+ host: input.host ?? "127.0.0.1",
+ port: input.port ?? 5173,
+ imageDomains: input.imageDomains,
+ });
+ progress?.report("tool screenshot preparing generated preview project");
+ const previewProject = await preparePreview(
+ input.source,
+ prepareSessionDataFile
+ );
+ progress?.report("tool screenshot starting production preview server");
+ await preview.startAndWait({
+ cwd: previewProject.cwd,
+ buildCacheKey: previewProject.buildCacheKey,
+ host: input.host,
+ port: input.port,
+ imageDomains: input.imageDomains,
+ restart: true,
+ });
+ markFresh();
+ }
+ return preview.resolveUrl(input.path);
+ };
+ const getCaptureOptions = (input: McpScreenshotInput, url: string) => ({
+ url,
+ output: input.output,
+ width: input.viewport.width,
+ height: input.viewport.height,
+ fullPage: input.fullPage,
+ includeImageMetrics: input.includeImageMetrics,
+ includeResourceMetrics: input.includeResourceMetrics,
+ browser: input.browser ?? "auto",
+ browserPath: input.browserPath,
+ waitUntil: input.waitUntil,
+ waitForSelector: input.waitForSelector,
+ waitForTimeout: input.waitForTimeout,
+ timeout: input.timeout,
+ format: input.format,
+ quality: input.quality,
+ scale: input.scale,
+ });
+ return {
+ async startPreview(input: McpPreviewInput, progress?: McpToolProgress) {
+ await closeCaptureSession();
+ validatePreviewServerOptions({
+ host: input.host ?? "127.0.0.1",
+ port: input.port ?? 5173,
+ imageDomains: input.imageDomains,
+ });
+ progress?.report(
+ "tool preview.start preparing generated preview project"
+ );
+ const previewProject = await preparePreview(
+ input.source,
+ prepareSessionDataFile
+ );
+ progress?.report("tool preview.start starting production preview server");
+ const result = await preview.startAndWait({
+ ...input,
+ cwd: previewProject.cwd,
+ buildCacheKey: previewProject.buildCacheKey,
+ restart: true,
+ });
+ markFresh();
+ return result;
+ },
+ async captureScreenshot(
+ input: McpScreenshotInput,
+ progress?: McpToolProgress
+ ) {
+ const url = await resolveScreenshotUrl(input, progress);
progress?.report(`tool screenshot capturing ${url}`);
+ const captureOptions = getCaptureOptions(input, url);
+ if (input.source === "session" && createCaptureSession !== undefined) {
+ captureSession ??= createCaptureSession();
+ return await captureSession.capture(captureOptions);
+ }
return await captureScreenshot({
- url,
- output: input.output,
- width: input.viewport.width,
- height: input.viewport.height,
- fullPage: input.fullPage,
- includeImageMetrics: input.includeImageMetrics,
- includeResourceMetrics: input.includeResourceMetrics,
- browser: input.browser ?? "auto",
- browserPath: input.browserPath,
- waitUntil: input.waitUntil,
- waitForSelector: input.waitForSelector,
- waitForTimeout: input.waitForTimeout,
- timeout: input.timeout,
+ ...captureOptions,
isJson: false,
isMcp: true,
isInteractive: false,
confirmInstall: async () => false,
});
- };
- let url = input.url;
- if (url === undefined) {
- if (input.path === undefined) {
- throw new Error("MCP screenshot requires url or path.");
- }
- if (input.baseUrl !== undefined) {
- url = new URL(input.path, input.baseUrl).toString();
- return await captureResolvedScreenshot(url);
+ },
+ async capturePageScreenshots(
+ inputs: readonly McpScreenshotInput[],
+ progress?: McpToolProgress
+ ) {
+ const firstInput = inputs[0];
+ if (firstInput === undefined) {
+ return [];
}
- const hasExplicitPreviewTarget =
- input.host !== undefined || input.port !== undefined;
if (
- preview.status().running === false ||
- isStale() ||
- hasExplicitPreviewTarget
+ createCaptureSession === undefined ||
+ firstInput.source !== "session" ||
+ inputs.some((input) => input.source !== firstInput.source)
) {
- validatePreviewServerOptions({
- host: input.host ?? "127.0.0.1",
- port: input.port ?? 5173,
- });
- progress?.report("tool screenshot preparing generated preview project");
- const previewProject = await preparePreview(
- input.source,
- prepareSessionDataFile
+ throw new Error(
+ "Resized screenshot capture requires session preview pages."
);
- progress?.report("tool screenshot starting production preview server");
- await preview.startAndWait({
- cwd: previewProject.cwd,
- host: input.host,
- port: input.port,
- restart: true,
- });
- markFresh();
}
- url = preview.resolveUrl(input.path);
- }
- return await captureResolvedScreenshot(url);
- },
-});
+ const urls: string[] = [];
+ for (const input of inputs) {
+ urls.push(await resolveScreenshotUrl(input, progress));
+ }
+ progress?.report(
+ `tool screenshot capturing ${new Set(urls).size} pages across ${inputs.length} viewport widths`
+ );
+ captureSession ??= createCaptureSession();
+ return await captureSession.capturePage(
+ inputs.map((input, index) => {
+ const url = urls[index];
+ if (url === undefined) {
+ throw new Error("Screenshot URL resolution was incomplete.");
+ }
+ return getCaptureOptions(input, url);
+ })
+ );
+ },
+ async stopPreview() {
+ const errors: unknown[] = [];
+ try {
+ await closeCaptureSession();
+ } catch (error) {
+ errors.push(error);
+ }
+ let result;
+ try {
+ if (preview.stop === undefined) {
+ throw new Error("Preview controller cannot stop its owned preview.");
+ }
+ result = await preview.stop();
+ } catch (error) {
+ errors.push(error);
+ }
+ if (errors.length === 1) {
+ throw errors[0];
+ }
+ if (errors.length > 1) {
+ throw new AggregateError(
+ errors,
+ "Could not clean up screenshot capture or stop the owned preview."
+ );
+ }
+ if (result === undefined) {
+ throw new Error("Preview controller did not return its stopped state.");
+ }
+ return result;
+ },
+ };
+};
export const mcpOptions = (yargs: CommonYargsArgv) =>
yargs
@@ -559,12 +722,14 @@ const mcpSingleOpCallOptions = (yargs: CommonYargsArgv) =>
default: false,
});
-type McpSingleOpCallOptions = StrictYargsOptionsToInterface<
- typeof mcpSingleOpCallOptions
-> & {
+type McpSingleOpCallOptions = {
tool?: string;
input?: string;
- inputFile?: string;
+ inputFile?: string | undefined;
+ dryRun?: boolean;
+ refresh?: boolean;
+ json?: boolean;
+ printSuccess?: (data: unknown) => void;
};
const mcpRunOptions = (yargs: CommonYargsArgv) =>
@@ -740,6 +905,7 @@ const getMcpRunError = (error: unknown) => {
? "UNAUTHORIZED"
: (error.code ?? "MCP_TOOL_FAILED"),
message: getCliErrorMessage(error),
+ ...(Array.isArray(error.issues) ? { issues: error.issues } : {}),
};
}
const code = isMissingApiAccessError(error)
@@ -749,6 +915,31 @@ const getMcpRunError = (error: unknown) => {
return { code, message };
};
+const validateSingleOpCallInput = (tool: string, input: unknown) => {
+ if (tool !== "audit" || isRecord(input) === false) {
+ return;
+ }
+ const issues: Array<{ path: string[]; message: string }> = [];
+ if (input.pageId !== undefined && input.pagePath !== undefined) {
+ issues.push({
+ path: ["pagePath"],
+ message: "pageId and pagePath are mutually exclusive.",
+ });
+ }
+ if (input.rendered === true && input.cursor !== undefined) {
+ issues.push({
+ path: ["cursor"],
+ message: "cursor cannot be combined with rendered audit.",
+ });
+ }
+ if (issues.length > 0) {
+ throw Object.assign(new Error("Audit input is invalid."), {
+ code: "INVALID_INPUT",
+ issues,
+ });
+ }
+};
+
const createMcpSingleOpCallErrorPayload = ({
error,
elapsedMs,
@@ -815,6 +1006,23 @@ const reportMcpRunPreflightFailure = ({
printJson(payload);
};
+const isMcpToolCallFailure = (result: {
+ isError?: boolean;
+ structuredContent: { ok?: boolean };
+}) => result.isError === true || result.structuredContent.ok === false;
+
+const getMcpToolCallError = (result: {
+ isError?: boolean;
+ structuredContent: { ok?: boolean; error?: unknown };
+}) => {
+ if (isMcpToolCallFailure(result) === false) {
+ return;
+ }
+ return isRecord(result.structuredContent.error)
+ ? result.structuredContent.error
+ : { code: "MCP_TOOL_FAILED", message: "MCP tool call failed." };
+};
+
const assertSingleOpCallToolSupported = (tool: string) => {
if (tool === "preview.start") {
throw Object.assign(
@@ -856,6 +1064,9 @@ export const __testing__ = {
getResultCheckpoint,
getMcpOperationInput,
parseMcpSingleOpCallInput,
+ validateSingleOpCallInput,
+ isMcpToolCallFailure,
+ getMcpToolCallError,
applyMcpRunOptions,
parseMcpRunCalls,
parseMcpRunInput,
@@ -879,6 +1090,8 @@ const createCliMcpHost = async () => {
}
},
};
+ const apiContract = await getCliServerApiContract(apiConnection);
+ const operations = getSupportedPublicApiOperations(apiContract);
const session = createCliProjectSession({ connection: apiConnection });
await prepareMcpProjectSession(session);
const preview = createPreviewController({ host: "127.0.0.1", port: 5173 });
@@ -888,6 +1101,7 @@ const createCliMcpHost = async () => {
};
const previewHandlers = createMcpPreviewHandlers({
preview,
+ createCaptureSession: createScreenshotCaptureSession,
isStale: () => isPreviewStale,
markFresh: () => {
isPreviewStale = false;
@@ -900,8 +1114,22 @@ const createCliMcpHost = async () => {
);
},
});
+ const toProjectSessionScreenshotResult = (
+ result: Awaited<ReturnType<typeof previewHandlers.captureScreenshot>>
+ ) => ({
+ output: result.output,
+ browserPath: result.browser.path,
+ browser: result.browser.browser,
+ viewport: result.viewport,
+ fullPage: result.fullPage,
+ elapsedMs: result.elapsedMs,
+ warnings: result.warnings,
+ navigation: result.navigation,
+ layout: result.layout,
+ timings: result.timings,
+ });
const host: CliMcpHost = {
- operations: publicApiOperations,
+ operations,
createProjectSession: () => session,
executeOperation: async ({ command, input, dryRun }) => {
const result = await executeProjectSessionApiOperation({
@@ -951,21 +1179,14 @@ const createCliMcpHost = async () => {
async getPreviewStatus() {
return preview.status();
},
- async stopPreview() {
- return preview.stop();
- },
+ stopPreview: previewHandlers.stopPreview,
async captureScreenshot(input) {
const result = await previewHandlers.captureScreenshot(input);
- return {
- output: result.output,
- browserPath: result.browser.path,
- browser: result.browser.browser,
- viewport: result.viewport,
- fullPage: result.fullPage,
- elapsedMs: result.elapsedMs,
- warnings: result.warnings,
- layout: result.layout,
- };
+ return toProjectSessionScreenshotResult(result);
+ },
+ async capturePageScreenshots(inputs) {
+ const results = await previewHandlers.capturePageScreenshots(inputs);
+ return results.map(toProjectSessionScreenshotResult);
},
async diffScreenshots(input) {
return diffPngFiles(input);
@@ -973,6 +1194,20 @@ const createCliMcpHost = async () => {
async installOcr() {
return installTesseractForOcr();
},
+ async storeRenderedAuditArtifacts(manifest) {
+ const directory = path.join(cwd(), renderedAuditArtifactDirectory);
+ await mkdir(directory, { recursive: true });
+ const artifactPath = path.join(
+ directory,
+ `rendered-${manifest.projectId}-${manifest.projectVersion}.json`
+ );
+ await writeFile(
+ artifactPath,
+ JSON.stringify(manifest, undefined, 2),
+ "utf8"
+ );
+ return artifactPath;
+ },
guidance: {
visualVerificationRule,
getVisionVerificationLoop,
@@ -982,7 +1217,8 @@ const createCliMcpHost = async () => {
return {
session,
host,
- toolCount: publicApiOperations.length,
+ apiContract,
+ toolCount: operations.length,
reportLog(message: string) {
if (message.startsWith("ready with ")) {
return;
@@ -1005,18 +1241,40 @@ export const mcpSingleOpCall = async (options: McpSingleOpCallOptions) => {
try {
assertSingleOpCallToolSupported(options.tool);
const input = await parseMcpSingleOpCallInput(options);
- const { host } = await createCliMcpHost();
+ validateSingleOpCallInput(options.tool, input);
+ const { host, apiContract } = await createCliMcpHost();
+ const operation = publicApiOperations.find(
+ (candidate) => candidate.command === options.tool
+ );
+ if (
+ operation !== undefined &&
+ publicApiOperationRequiresServerSupport(operation)
+ ) {
+ assertCliServerOperationSupported(operation.id, apiContract);
+ }
const core = createProjectSessionMcpCore(host);
const persistedCheckpoint =
options.tool === "checkpoint.ack"
? await readPersistedMcpCheckpoint()
: undefined;
await assertPersistedMcpCheckpointAcknowledged(options.tool);
+ if (options.refresh === true && options.tool !== "refresh") {
+ await core.callTool({ name: "refresh" });
+ }
const result = await core.callTool({
name: options.tool,
input,
dryRun: options.dryRun,
});
+ if (isMcpToolCallFailure(result)) {
+ stderr.write(
+ `${formatMcpStatusLine(
+ `single-op-call ${options.tool} failed in ${Date.now() - startedAt}ms`
+ )}\n`
+ );
+ printJson(result.structuredContent);
+ throw new HandledCliError();
+ }
if (
options.tool === "checkpoint.ack" &&
persistedCheckpoint?.nextCommand !== undefined &&
@@ -1037,8 +1295,15 @@ export const mcpSingleOpCall = async (options: McpSingleOpCallOptions) => {
`single-op-call ${options.tool} succeeded in ${Date.now() - startedAt}ms${committed}`
)}\n`
);
- printJson(result.structuredContent);
+ if (options.printSuccess === undefined) {
+ printJson(result.structuredContent);
+ } else {
+ options.printSuccess(result.structuredContent.data);
+ }
} catch (error) {
+ if (isHandledCliError(error)) {
+ throw error;
+ }
const payload = createMcpSingleOpCallErrorPayload({
error,
elapsedMs: Date.now() - startedAt,
@@ -1077,7 +1342,18 @@ export const mcpRun = async (options: McpRunOptions) => {
const results: unknown[] = [];
let core: ReturnType<typeof createProjectSessionMcpCore<PublicApiCommand>>;
try {
- const { host } = await createCliMcpHost();
+ const { host, apiContract } = await createCliMcpHost();
+ for (const call of calls) {
+ const operation = publicApiOperations.find(
+ (candidate) => candidate.command === call.tool
+ );
+ if (
+ operation !== undefined &&
+ publicApiOperationRequiresServerSupport(operation)
+ ) {
+ assertCliServerOperationSupported(operation.id, apiContract);
+ }
+ }
core = createProjectSessionMcpCore(host);
if (calls.length > 0) {
await assertPersistedMcpCheckpointAcknowledged(calls[0]!.tool);
@@ -1103,6 +1379,10 @@ export const mcpRun = async (options: McpRunOptions) => {
input: call.input,
dryRun: call.dryRun,
});
+ const toolError = getMcpToolCallError(result);
+ if (toolError !== undefined) {
+ throw toolError;
+ }
const checkpoint = getResultCheckpoint(
call.tool,
result.structuredContent
@@ -1236,11 +1516,22 @@ export const mcpReadResource = async (options: McpReadResourceOptions) => {
export const mcp = async () => {
const status = createMcpStatusReporter();
+ let didReportClose = false;
+ const reportClose = () => {
+ if (didReportClose) {
+ return;
+ }
+ didReportClose = true;
+ status.connectionClosed();
+ };
+ stdin.once("end", reportClose);
+ stdin.once("close", reportClose);
status.starting();
- const { host, toolCount, reportLog } = await createCliMcpHost();
+ const { host, toolCount, reportLog, apiContract } = await createCliMcpHost();
status.sessionReady();
+ status.apiContract(apiContract);
status.ready(toolCount);
- await connectProjectSessionMcpServer({
+ const server = await connectProjectSessionMcpServer({
...host,
getErrorCode: getStableErrorCode,
reportLog: (_level, message) => {
@@ -1248,4 +1539,8 @@ export const mcp = async () => {
},
transport: await createMcpStdioTransport({ stdin, stdout }),
});
+ server.onclose = reportClose;
+ server.onerror = (error) => {
+ status.connectionError(error);
+ };
};
diff --git a/packages/cli/src/commands/preview.test.ts b/packages/cli/src/commands/preview.test.ts
index 95f51a866f..e464e2b05b 100644
--- a/packages/cli/src/commands/preview.test.ts
+++ b/packages/cli/src/commands/preview.test.ts
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
-import { mkdir, rm, writeFile } from "node:fs/promises";
+import { mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { chdir, cwd } from "node:process";
@@ -7,6 +7,9 @@ import { expect, test, vi } from "vitest";
import { createPublishedProjectBundleFixture } from "@webstudio-is/protocol/fixtures";
import {
ensurePreviewDependencies,
+ buildPreparedPreview,
+ getNodeModulesSearchPaths,
+ getPreviewBuildCacheKey,
getPreviewProjectDir,
preparePreviewProject,
preview,
@@ -24,6 +27,8 @@ test("rejects empty preview host", async () => {
assets: true,
template: [],
source: "local",
+ imageDomain: undefined,
+ "image-domain": undefined,
})
).rejects.toThrow("--host must not be empty.");
});
@@ -32,6 +37,88 @@ test("defaults preview generation to the app template", () => {
expect(previewDefaultTemplate).toEqual(["defaults", "react-router"]);
});
+test("uses Node module search paths to discover installed dependencies", () => {
+ expect(
+ getNodeModulesSearchPaths(
+ "file:///tmp/app/node_modules/webstudio/lib/cli.js"
+ )
+ ).toContain("/tmp/app/node_modules");
+});
+
+test("builds only uncached prepared previews and records the cache key", async () => {
+ const runPreviewBuild = vi.fn(async () => undefined);
+ const writeFile = vi.fn(async () => undefined);
+
+ await expect(
+ buildPreparedPreview(
+ {
+ cwd: "/tmp/preview",
+ buildCacheKey: "cache-key",
+ buildRequired: true,
+ },
+ { runPreviewBuild, writeFile }
+ )
+ ).resolves.toBe(true);
+ expect(runPreviewBuild).toHaveBeenCalledWith(undefined, "/tmp/preview");
+ expect(writeFile).toHaveBeenCalledWith(
+ "/tmp/preview/.webstudio-preview-build",
+ "cache-key"
+ );
+
+ runPreviewBuild.mockClear();
+ writeFile.mockClear();
+ await expect(
+ buildPreparedPreview(
+ { cwd: "/tmp/preview", buildRequired: false },
+ { runPreviewBuild, writeFile }
+ )
+ ).resolves.toBe(false);
+ expect(runPreviewBuild).not.toHaveBeenCalled();
+ expect(writeFile).not.toHaveBeenCalled();
+});
+
+test("keys packaged preview builds to project inputs and asset metadata", async () => {
+ const projectDir = join(tmpdir(), `webstudio-preview-key-${randomUUID()}`);
+ await mkdir(join(projectDir, ".webstudio", "assets"), { recursive: true });
+ await writeFile(join(projectDir, ".webstudio", "data.json"), "first");
+ await writeFile(join(projectDir, ".webstudio", "config.json"), "config");
+ await writeFile(join(projectDir, ".webstudio", "assets", "hero.png"), "a");
+ try {
+ const first = await getPreviewBuildCacheKey({
+ projectDir,
+ assets: true,
+ template: [],
+ cliVersion: "1.2.3",
+ });
+ const same = await getPreviewBuildCacheKey({
+ projectDir,
+ assets: true,
+ template: [],
+ cliVersion: "1.2.3",
+ });
+ await writeFile(join(projectDir, ".webstudio", "data.json"), "second");
+ const changed = await getPreviewBuildCacheKey({
+ projectDir,
+ assets: true,
+ template: [],
+ cliVersion: "1.2.3",
+ });
+
+ expect(first).toBe(same);
+ expect(changed).not.toBe(first);
+ await expect(
+ getPreviewBuildCacheKey({
+ projectDir,
+ assets: true,
+ template: [],
+ cliVersion: "0.0.0-webstudio-version",
+ })
+ ).resolves.toBeUndefined();
+ } finally {
+ await rm(projectDir, { recursive: true, force: true });
+ }
+});
+
test("prepares preview by syncing missing data and generating the app template", async () => {
const syncDependencies = {
createFileIfNotExists: vi.fn(async () => undefined),
@@ -67,6 +154,7 @@ test("prepares preview by syncing missing data and generating the app template",
syncDependencies,
accessLocalDataFile,
prebuildProject,
+ ensureDependencies: vi.fn(async () => undefined),
});
expect(syncDependencies.loadProjectBundleByProjectId).toHaveBeenCalled();
@@ -88,6 +176,24 @@ test("generates preview project in isolated directory", async () => {
await mkdir(join(projectDir, ".webstudio"), { recursive: true });
await writeFile(join(projectDir, ".webstudio", "data.json"), "{}");
await writeFile(join(projectDir, ".webstudio", "config.json"), "{}");
+ await writeFile(
+ join(projectDir, ".webstudio", "project-session.json"),
+ "consumer session"
+ );
+ await mkdir(join(projectDir, ".temp"), { recursive: true });
+ await writeFile(join(projectDir, ".temp", "diagnostic.mjs"), "consumer file");
+ await mkdir(join(projectDir, ".webstudio", "preview", "node_modules"), {
+ recursive: true,
+ });
+ await writeFile(
+ join(projectDir, ".webstudio", "preview", "node_modules", "cached"),
+ "preserved"
+ );
+ const ensureDependencies = vi.fn(async (previewProjectDir: string) => {
+ await expect(
+ readFile(join(previewProjectDir, "node_modules", "cached"), "utf8")
+ ).resolves.toBe("preserved");
+ });
chdir(projectDir);
expectedPreviewProjectDir = getPreviewProjectDir();
try {
@@ -97,8 +203,18 @@ test("generates preview project in isolated directory", async () => {
template: [],
generate: true,
prebuildProject,
+ ensureDependencies,
})
- ).resolves.toEqual({ cwd: expectedPreviewProjectDir });
+ ).resolves.toEqual({
+ cwd: expectedPreviewProjectDir,
+ buildRequired: true,
+ });
+ await expect(
+ readFile(join(projectDir, ".webstudio", "project-session.json"), "utf8")
+ ).resolves.toBe("consumer session");
+ await expect(
+ readFile(join(projectDir, ".temp", "diagnostic.mjs"), "utf8")
+ ).resolves.toBe("consumer file");
} finally {
chdir(previousDirectory);
await rm(projectDir, { recursive: true, force: true });
@@ -108,36 +224,89 @@ test("generates preview project in isolated directory", async () => {
assets: true,
template: ["defaults", "react-router"],
});
+ expect(ensureDependencies).toHaveBeenCalledOnce();
+});
+
+test("revalidates dependencies when reusing a cached preview build", async () => {
+ const previousDirectory = cwd();
+ const projectDir = join(tmpdir(), `webstudio-preview-test-${randomUUID()}`);
+ const previewProjectDir = join(projectDir, ".webstudio", "preview");
+ const ensureDependencies = vi.fn(async () => undefined);
+ const prebuildProject = vi.fn(async () => undefined);
+
+ await mkdir(previewProjectDir, { recursive: true });
+ await writeFile(join(projectDir, ".webstudio", "data.json"), "{}");
+ await writeFile(
+ join(previewProjectDir, ".webstudio-preview-build"),
+ "cache-key"
+ );
+ chdir(projectDir);
+ try {
+ const result = await preparePreviewProject({
+ assets: true,
+ template: [],
+ generate: true,
+ prebuildProject,
+ ensureDependencies,
+ getBuildCacheKey: vi.fn(async () => "cache-key"),
+ });
+ expect(result.buildCacheKey).toBe("cache-key");
+ expect(result.buildRequired).toBe(false);
+ await expect(realpath(result.cwd)).resolves.toBe(
+ await realpath(previewProjectDir)
+ );
+ } finally {
+ chdir(previousDirectory);
+ await rm(projectDir, { recursive: true, force: true });
+ }
+
+ expect(ensureDependencies).toHaveBeenCalledOnce();
+ expect(prebuildProject).not.toHaveBeenCalled();
});
-test("links generated preview dependencies from the cli package", async () => {
+test("links local workspace preview dependencies without asking npm for placeholder versions", async () => {
const symlink = vi.fn(async () => undefined);
- const access = vi
- .fn()
- .mockRejectedValueOnce(
- Object.assign(new Error("missing"), { code: "ENOENT" })
- )
- .mockResolvedValueOnce(undefined);
+ const cliNodeModules = getNodeModulesSearchPaths(import.meta.url).find(
+ (path) => path.endsWith("/packages/cli/node_modules")
+ );
+ expect(cliNodeModules).toBeDefined();
+ const access = vi.fn(async (path: string) => {
+ if (path.startsWith(cliNodeModules!) === false) {
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ }
+ });
+ const execFile = vi.fn(async () => ({ stdout: "", stderr: "" }));
await ensurePreviewDependencies("/tmp/project/.webstudio/preview", {
access,
+ execFile,
+ lstat: vi.fn(async () => {
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ }),
+ readFile: vi.fn(
+ async () =>
+ '{"dependencies":{"@webstudio-is/image":"0.0.0-webstudio-version","vite":"1.0.0"}}'
+ ),
symlink,
platform: "linux",
});
expect(symlink).toHaveBeenCalledWith(
- expect.stringContaining("packages/cli/node_modules"),
+ cliNodeModules,
"/tmp/project/.webstudio/preview/node_modules",
"dir"
);
+ expect(execFile).not.toHaveBeenCalled();
});
test("does not relink generated preview dependencies when already present", async () => {
const symlink = vi.fn(async () => undefined);
- const access = vi.fn().mockResolvedValueOnce(undefined);
+ const access = vi.fn(async () => undefined);
await ensurePreviewDependencies("/tmp/project/.webstudio/preview", {
access,
+ lstat: vi.fn(async () => ({ isSymbolicLink: () => true })) as never,
+ readFile: vi.fn(async () => '{"dependencies":{"vite":"1.0.0"}}'),
symlink,
platform: "linux",
});
@@ -147,26 +316,109 @@ test("does not relink generated preview dependencies when already present", asyn
test("uses junctions for generated preview dependencies on windows", async () => {
const symlink = vi.fn(async () => undefined);
- const access = vi
- .fn()
- .mockRejectedValueOnce(
- Object.assign(new Error("missing"), { code: "ENOENT" })
- )
- .mockResolvedValueOnce(undefined);
+ const cliNodeModules = getNodeModulesSearchPaths(import.meta.url).find(
+ (path) => path.endsWith("/packages/cli/node_modules")
+ );
+ expect(cliNodeModules).toBeDefined();
+ const access = vi.fn(async (path: string) => {
+ if (path.startsWith(cliNodeModules!) === false) {
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ }
+ });
await ensurePreviewDependencies("C:/project/.webstudio/preview", {
access,
+ lstat: vi.fn(async () => {
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ }),
+ readFile: vi.fn(async () => '{"dependencies":{"vite":"1.0.0"}}'),
symlink,
platform: "win32",
});
expect(symlink).toHaveBeenCalledWith(
- expect.stringContaining("packages/cli/node_modules"),
+ cliNodeModules,
"C:/project/.webstudio/preview/node_modules",
"junction"
);
});
+test("installs isolated generated dependencies when the cli does not ship them", async () => {
+ let installed = false;
+ const execFile = vi.fn(async () => {
+ installed = true;
+ return { stdout: "", stderr: "" };
+ });
+ const writeFile = vi.fn(async () => undefined);
+
+ await ensurePreviewDependencies("/tmp/project/.webstudio/preview", {
+ access: vi.fn(async (path) => {
+ if (installed && path.startsWith("/tmp/project/.webstudio/preview")) {
+ return;
+ }
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ }),
+ execFile,
+ lstat: vi.fn(async () => {
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ }),
+ readFile: vi.fn(async () => '{"dependencies":{"vite":"1.0.0"}}'),
+ writeFile,
+ platform: "linux",
+ });
+
+ expect(execFile).toHaveBeenCalledWith(
+ "npm",
+ expect.arrayContaining(["install", "--legacy-peer-deps"]),
+ { cwd: "/tmp/project/.webstudio/preview" }
+ );
+ expect(writeFile).toHaveBeenCalledWith(
+ "/tmp/project/.webstudio/preview/node_modules/.webstudio-preview-dependencies",
+ expect.stringMatching(/^[a-f0-9]{64}$/)
+ );
+});
+
+test("reports an actionable error when generated dependencies cannot install", async () => {
+ const access = vi.fn(async () => {
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ });
+
+ await expect(
+ ensurePreviewDependencies("/tmp/project/.webstudio/preview", {
+ access,
+ execFile: vi.fn(async () => {
+ throw new Error("npm failed");
+ }),
+ lstat: vi.fn(async () => {
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ }),
+ readFile: vi.fn(async () => '{"dependencies":{"vite":"1.0.0"}}'),
+ symlink: vi.fn(async () => undefined),
+ platform: "linux",
+ })
+ ).rejects.toThrow(
+ "PREVIEW_DEPENDENCY_INSTALL_FAILED: Could not install the generated preview dependencies"
+ );
+});
+
+test("rejects an incomplete generated dependency tree", async () => {
+ await expect(
+ ensurePreviewDependencies("/tmp/project/.webstudio/preview", {
+ access: vi.fn(async () => {
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ }),
+ execFile: vi.fn(async () => ({ stdout: "", stderr: "" })),
+ lstat: vi.fn(async () => {
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ }),
+ readFile: vi.fn(async () => '{"dependencies":{"vite":"1.0.0"}}'),
+ platform: "linux",
+ })
+ ).rejects.toThrow(
+ "PREVIEW_DEPENDENCIES_MISSING: npm completed without installing every dependency"
+ );
+});
+
test("materializes session data before previewing from session source", async () => {
const previousDirectory = cwd();
const projectDir = join(tmpdir(), `webstudio-preview-test-${randomUUID()}`);
@@ -192,8 +444,12 @@ test("materializes session data before previewing from session source", async ()
source: "session",
prepareSessionDataFile,
prebuildProject,
+ ensureDependencies: vi.fn(async () => undefined),
})
- ).resolves.toEqual({ cwd: expectedPreviewProjectDir });
+ ).resolves.toEqual({
+ cwd: expectedPreviewProjectDir,
+ buildRequired: true,
+ });
} finally {
chdir(previousDirectory);
await rm(projectDir, { recursive: true, force: true });
@@ -240,6 +496,7 @@ test("adds defaults when previewing the direct React Router template", async ()
template: ["react-router"],
generate: true,
prebuildProject,
+ ensureDependencies: vi.fn(async () => undefined),
accessLocalDataFile: vi.fn(async () => undefined),
});
@@ -263,6 +520,7 @@ test("documents generated app dependency setup", () => {
previewOptions(yargs);
expect(epilogueText).toContain("isolated under .webstudio/preview");
+ expect(epilogueText).toContain("reused across regenerations");
expect(epilogueText).toContain("Do not add generated-preview dependencies");
- expect(epilogueText).toContain("react-router-serve");
+ expect(epilogueText).toContain("check npm and network configuration");
});
diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts
index 64c612e142..039f5e0db6 100644
--- a/packages/cli/src/commands/preview.ts
+++ b/packages/cli/src/commands/preview.ts
@@ -1,7 +1,21 @@
-import { access, copyFile, mkdir, rm, symlink } from "node:fs/promises";
-import { fileURLToPath } from "node:url";
+import { createHash } from "node:crypto";
+import { execFile } from "node:child_process";
+import {
+ access,
+ copyFile,
+ lstat,
+ mkdir,
+ readFile,
+ readdir,
+ rm,
+ stat,
+ symlink,
+ writeFile,
+} from "node:fs/promises";
+import { createRequire } from "node:module";
import { join } from "node:path";
import { chdir, cwd } from "node:process";
+import { promisify } from "node:util";
import { log } from "@clack/prompts";
import { builderNamespaces } from "@webstudio-is/project-build/contracts/namespaces";
import { prebuild } from "../prebuild";
@@ -9,6 +23,7 @@ import { LOCAL_CONFIG_FILE, LOCAL_DATA_FILE } from "../config";
import { HandledCliError } from "../errors";
import {
getPreviewUrl,
+ previewBuildCacheMarker,
runPreviewBuild,
startPreviewServer,
waitForPreviewExit,
@@ -24,6 +39,8 @@ import {
createCliProjectSession,
writeCliProjectSessionDataFile,
} from "../project-session";
+import { LOCAL_ASSETS_DIR } from "../asset-files";
+import packageJson from "../../package.json" with { type: "json" };
export const previewDefaultTemplate = ["defaults", "react-router"] as const;
export const previewSources = ["local", "session"] as const;
@@ -53,6 +70,12 @@ export const previewOptions = (yargs: CommonYargsArgv) =>
default: 5173,
describe: "Port used by the generated project production preview server",
})
+ .option("image-domain", {
+ type: "string",
+ array: true,
+ describe:
+ "External image hostname allowed by the generated preview optimizer; repeat for multiple hosts",
+ })
.option("generate", {
type: "boolean",
default: true,
@@ -81,9 +104,9 @@ export const previewOptions = (yargs: CommonYargsArgv) =>
.epilogue(
[
"Preview builds the generated app and starts its production server.",
- "Preview dependencies are isolated under .webstudio/preview by linking to the CLI package dependency tree.",
+ "Preview dependencies are isolated under .webstudio/preview and reused across regenerations.",
"Do not add generated-preview dependencies to the repository root package.json or pnpm-lock.yaml.",
- "If preview exits with a missing command/package such as react-router, react-router-serve, or vite, install dependencies for the CLI package and retry.",
+ "If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.",
].join("\n")
);
@@ -95,9 +118,11 @@ const isPositivePort = (value: number) =>
export const validatePreviewServerOptions = ({
host,
port,
+ imageDomains,
}: {
host: string;
port: number;
+ imageDomains?: string[];
}) => {
if (host.length === 0) {
throw new Error("--host must not be empty.");
@@ -105,6 +130,15 @@ export const validatePreviewServerOptions = ({
if (isPositivePort(port) === false) {
throw new Error("--port must be an integer between 1 and 65535.");
}
+ if (
+ imageDomains?.some(
+ (domain) => /^[a-z0-9.-]+(?::\d+)?$/i.test(domain) === false
+ )
+ ) {
+ throw new Error(
+ "Image domains must be hostnames without a protocol or path."
+ );
+ }
};
const createSilentSpinner = () => ({
@@ -119,38 +153,142 @@ const localPreviewFiles = [
".webstudio/auth.json",
];
-const cliPackageRoot = fileURLToPath(new URL("../../", import.meta.url));
-const cliNodeModules = join(cliPackageRoot, "node_modules");
+export const getNodeModulesSearchPaths = (moduleUrl: string) =>
+ createRequire(moduleUrl).resolve.paths("webstudio-preview") ?? [];
+
+const cliNodeModulesCandidates = getNodeModulesSearchPaths(import.meta.url);
+const execFileAsync = promisify(execFile);
+const dependencyMarker = ".webstudio-preview-dependencies";
+const developmentCliVersion = "0.0.0-webstudio-version";
+type PreviewDependencyOperations = {
+ access: (path: string) => Promise<void>;
+ execFile: (
+ file: string,
+ args: string[],
+ options: { cwd: string }
+ ) => Promise<unknown>;
+ lstat: (path: string) => Promise<{ isSymbolicLink: () => boolean }>;
+ readFile: (path: string, encoding: "utf8") => Promise<string>;
+ rm: (
+ path: string,
+ options: { recursive: true; force: true }
+ ) => Promise<void>;
+ symlink: (
+ target: string,
+ path: string,
+ type: "dir" | "junction"
+ ) => Promise<void>;
+ writeFile: (path: string, data: string) => Promise<void>;
+ platform: NodeJS.Platform;
+};
export const getPreviewProjectDir = (projectDir = cwd()) =>
join(projectDir, ".webstudio", "preview");
export const ensurePreviewDependencies = async (
previewProjectDir: string,
- dependencies = {
+ dependencies: Partial<PreviewDependencyOperations> = {}
+) => {
+ const operations: PreviewDependencyOperations = {
access,
+ execFile: execFileAsync,
+ lstat,
+ readFile,
+ rm,
symlink,
+ writeFile,
platform: process.platform,
- }
-) => {
+ ...dependencies,
+ };
const previewNodeModules = join(previewProjectDir, "node_modules");
+ const packageJson = JSON.parse(
+ await operations.readFile(join(previewProjectDir, "package.json"), "utf8")
+ ) as {
+ dependencies?: Record<string, string>;
+ devDependencies?: Record<string, string>;
+ };
+ const requiredDependencies = {
+ ...packageJson.dependencies,
+ ...packageJson.devDependencies,
+ };
+ const manifestHash = createHash("sha256")
+ .update(JSON.stringify(requiredDependencies))
+ .digest("hex");
+ const hasRequiredDependencies = async (nodeModules: string) => {
+ try {
+ await Promise.all(
+ Object.keys(requiredDependencies).map((name) =>
+ operations.access(join(nodeModules, name, "package.json"))
+ )
+ );
+ return true;
+ } catch {
+ return false;
+ }
+ };
+
try {
- await dependencies.access(previewNodeModules);
- return;
+ const previewNodeModulesStat = await operations.lstat(previewNodeModules);
+ if (
+ previewNodeModulesStat.isSymbolicLink() &&
+ (await hasRequiredDependencies(previewNodeModules))
+ ) {
+ return;
+ }
+ if (previewNodeModulesStat.isSymbolicLink() === false) {
+ const installedHash = await operations
+ .readFile(join(previewNodeModules, dependencyMarker), "utf8")
+ .catch(() => "");
+ if (
+ installedHash === manifestHash &&
+ (await hasRequiredDependencies(previewNodeModules))
+ ) {
+ return;
+ }
+ }
+ await operations.rm(previewNodeModules, { recursive: true, force: true });
} catch {
- // Continue and link the generated preview app to CLI-owned dependencies.
+ // Continue with the CLI dependency tree or an isolated install.
}
+
+ for (const cliNodeModules of cliNodeModulesCandidates) {
+ if (await hasRequiredDependencies(cliNodeModules)) {
+ await operations.symlink(
+ cliNodeModules,
+ previewNodeModules,
+ operations.platform === "win32" ? "junction" : "dir"
+ );
+ return;
+ }
+ }
+
try {
- await dependencies.access(cliNodeModules);
- } catch {
+ await operations.execFile(
+ operations.platform === "win32" ? "npm.cmd" : "npm",
+ [
+ "install",
+ "--legacy-peer-deps",
+ "--no-audit",
+ "--no-fund",
+ "--package-lock=false",
+ "--loglevel=error",
+ ],
+ { cwd: previewProjectDir }
+ );
+ } catch (error) {
+ throw new Error(
+ "PREVIEW_DEPENDENCY_INSTALL_FAILED: Could not install the generated preview dependencies. Check the npm/network configuration, then reinstall or update webstudio if the problem persists.",
+ { cause: error }
+ );
+ }
+ if ((await hasRequiredDependencies(previewNodeModules)) === false) {
throw new Error(
- `Preview dependencies are missing from the CLI package. Run pnpm install in ${cliPackageRoot}, then retry preview.`
+ "PREVIEW_DEPENDENCIES_MISSING: npm completed without installing every dependency declared by the generated preview. Reinstall or update webstudio, then retry."
);
}
- await dependencies.symlink(
- cliNodeModules,
- previewNodeModules,
- dependencies.platform === "win32" ? "junction" : "dir"
+ await operations.writeFile(
+ join(previewNodeModules, dependencyMarker),
+ manifestHash
);
};
@@ -185,7 +323,15 @@ const runExclusive = async <Result>(callback: () => Promise<Result>) => {
const preparePreviewDirectory = async (projectDir: string) => {
const previewProjectDir = getPreviewProjectDir(projectDir);
- await rm(previewProjectDir, { recursive: true, force: true });
+ await mkdir(previewProjectDir, { recursive: true });
+ const entries = await readdir(previewProjectDir);
+ await Promise.all(
+ entries
+ .filter((entry) => entry !== "node_modules")
+ .map((entry) =>
+ rm(join(previewProjectDir, entry), { recursive: true, force: true })
+ )
+ );
await mkdir(join(previewProjectDir, ".webstudio"), { recursive: true });
for (const file of localPreviewFiles) {
await copyFile(join(projectDir, file), join(previewProjectDir, file)).catch(
@@ -204,6 +350,69 @@ const preparePreviewDirectory = async (projectDir: string) => {
return previewProjectDir;
};
+const getAssetFileMetadata = async (
+ directory: string,
+ relativeDirectory = ""
+): Promise<string[]> => {
+ const entries = await readdir(join(directory, relativeDirectory), {
+ withFileTypes: true,
+ }).catch(() => []);
+ const metadata: string[] = [];
+ for (const entry of entries.sort((left, right) =>
+ left.name.localeCompare(right.name)
+ )) {
+ const relativePath = join(relativeDirectory, entry.name);
+ if (entry.isDirectory()) {
+ metadata.push(...(await getAssetFileMetadata(directory, relativePath)));
+ continue;
+ }
+ if (entry.isFile()) {
+ const file = await stat(join(directory, relativePath));
+ metadata.push(`${relativePath}:${file.size}:${file.mtimeMs}`);
+ }
+ }
+ return metadata;
+};
+
+export const getPreviewBuildCacheKey = async ({
+ projectDir,
+ assets,
+ template,
+ cliVersion = packageJson.version,
+}: {
+ projectDir: string;
+ assets: boolean;
+ template: string[];
+ cliVersion?: string;
+}) => {
+ if (cliVersion === developmentCliVersion) {
+ return;
+ }
+ const hash = createHash("sha256");
+ hash.update(
+ JSON.stringify({
+ version: 1,
+ cliVersion,
+ assets,
+ template: getPreviewTemplates(template),
+ })
+ );
+ for (const file of localPreviewFiles) {
+ hash.update(file);
+ hash.update(
+ await readFile(join(projectDir, file), "utf8").catch(() => "<missing>")
+ );
+ }
+ if (assets) {
+ hash.update(
+ JSON.stringify(
+ await getAssetFileMetadata(join(projectDir, LOCAL_ASSETS_DIR))
+ )
+ );
+ }
+ return hash.digest("hex");
+};
+
export const preparePreviewProject = async ({
assets,
template,
@@ -213,6 +422,9 @@ export const preparePreviewProject = async ({
syncDependencies = defaultSyncDependencies,
accessLocalDataFile = access,
prebuildProject = prebuild,
+ ensureDependencies = ensurePreviewDependencies,
+ getBuildCacheKey = getPreviewBuildCacheKey,
+ silent = false,
prepareSessionDataFile = async () => {
const connection = await resolveApiConnection();
const session = createCliProjectSession({ connection });
@@ -231,8 +443,15 @@ export const preparePreviewProject = async ({
syncDependencies?: SyncDependencies;
accessLocalDataFile?: typeof access;
prebuildProject?: typeof prebuild;
+ ensureDependencies?: typeof ensurePreviewDependencies;
+ getBuildCacheKey?: typeof getPreviewBuildCacheKey;
+ silent?: boolean;
prepareSessionDataFile?: () => Promise<void>;
-}) => {
+}): Promise<{
+ cwd: string;
+ buildCacheKey?: string;
+ buildRequired?: boolean;
+}> => {
const projectDir = cwd();
if (source === "session") {
await prepareSessionDataFile();
@@ -265,6 +484,22 @@ export const preparePreviewProject = async ({
return { cwd: projectDir };
}
+ const buildCacheKey = await getBuildCacheKey({
+ projectDir,
+ assets,
+ template,
+ });
+ if (buildCacheKey !== undefined) {
+ const cachedBuildKey = await readFile(
+ join(previewProjectDir, previewBuildCacheMarker),
+ "utf8"
+ ).catch(() => undefined);
+ if (cachedBuildKey === buildCacheKey) {
+ await ensureDependencies(previewProjectDir);
+ return { cwd: previewProjectDir, buildCacheKey, buildRequired: false };
+ }
+ }
+
if (generate) {
await runExclusive(async () => {
await preparePreviewDirectory(projectDir);
@@ -272,17 +507,46 @@ export const preparePreviewProject = async ({
await prebuildProject({
assets,
template: getPreviewTemplates(template),
+ ...(silent ? { silent: true } : {}),
});
});
- await ensurePreviewDependencies(previewProjectDir);
+ await ensureDependencies(previewProjectDir);
});
}
- return { cwd: previewProjectDir };
+ return {
+ cwd: previewProjectDir,
+ buildRequired: true,
+ ...(buildCacheKey === undefined ? {} : { buildCacheKey }),
+ };
+};
+
+export const buildPreparedPreview = async (
+ previewProject: {
+ cwd: string;
+ buildCacheKey?: string;
+ buildRequired?: boolean;
+ },
+ dependencies = { runPreviewBuild, writeFile }
+) => {
+ if (previewProject.buildRequired === false) {
+ return false;
+ }
+ await dependencies.runPreviewBuild(undefined, previewProject.cwd);
+ if (previewProject.buildCacheKey !== undefined) {
+ await dependencies.writeFile(
+ join(previewProject.cwd, previewBuildCacheMarker),
+ previewProject.buildCacheKey
+ );
+ }
+ return true;
};
export const preview = async (options: PreviewOptions) => {
- validatePreviewServerOptions(options);
+ validatePreviewServerOptions({
+ ...options,
+ imageDomains: options.imageDomain,
+ });
const previewProject = await preparePreviewProject({
assets: options.assets,
template: options.template,
@@ -292,11 +556,12 @@ export const preview = async (options: PreviewOptions) => {
const url = getPreviewUrl({ host: options.host, port: options.port });
log.success(`Preview production server starting at ${url}`);
- await runPreviewBuild(undefined, previewProject.cwd);
+ await buildPreparedPreview(previewProject);
const server = startPreviewServer({
host: options.host,
port: options.port,
cwd: previewProject.cwd,
+ imageDomains: options.imageDomain,
});
await waitForPreviewExit(server.process);
};
diff --git a/packages/cli/src/commands/screenshot.test.ts b/packages/cli/src/commands/screenshot.test.ts
index b1d7f5e7b0..065650bc7c 100644
--- a/packages/cli/src/commands/screenshot.test.ts
+++ b/packages/cli/src/commands/screenshot.test.ts
@@ -111,7 +111,10 @@ test("captures a project route through a temporary production preview", async ()
})),
resolveUrl: vi.fn(() => "http://127.0.0.1:5180/pricing"),
};
- const preparePreviewProject = vi.fn(async () => ({ cwd: "/tmp/preview" }));
+ const preparePreviewProject = vi.fn(async () => ({
+ cwd: "/tmp/preview",
+ buildCacheKey: "preview-cache-key",
+ }));
const createPreviewController = vi.fn(() => preview);
try {
@@ -136,6 +139,7 @@ test("captures a project route through a temporary production preview", async ()
assets: true,
template: ["defaults", "react-router"],
generate: true,
+ silent: true,
});
expect(createPreviewController).toHaveBeenCalledWith({
host: "127.0.0.1",
@@ -143,6 +147,7 @@ test("captures a project route through a temporary production preview", async ()
});
expect(preview.startAndWait).toHaveBeenCalledWith({
cwd: "/tmp/preview",
+ buildCacheKey: "preview-cache-key",
host: "127.0.0.1",
port: 5173,
restart: true,
@@ -154,6 +159,69 @@ test("captures a project route through a temporary production preview", async ()
expect(preview.stop).toHaveBeenCalledOnce();
});
+test("fails a generated project route that returns an HTTP error", async () => {
+ vi.spyOn(console, "info").mockImplementation(() => undefined);
+ const preview = {
+ startAndWait: vi.fn(async () => ({
+ url: "http://127.0.0.1:5173/",
+ running: true,
+ })),
+ stop: vi.fn(async () => ({
+ url: "http://127.0.0.1:5173/",
+ running: false,
+ })),
+ resolveUrl: vi.fn(() => "http://127.0.0.1:5173/missing"),
+ };
+
+ await expect(
+ screenshot(
+ { path: "/missing", width: 800, height: 600, json: true },
+ {
+ captureScreenshotWithBrowserInstall: vi.fn(async () => ({
+ output: "/tmp/missing.png",
+ browser: {
+ path: "/browser",
+ source: "option" as const,
+ browser: "chrome" as const,
+ },
+ viewport: { width: 800, height: 600 },
+ fullPage: false,
+ elapsedMs: 12,
+ warnings: [] as string[],
+ navigation: {
+ requestedUrl: "http://127.0.0.1:5173/missing",
+ finalUrl: "http://127.0.0.1:5173/missing",
+ status: 404,
+ statusText: "Not Found",
+ mimeType: "text/html",
+ redirects: [],
+ documentReadyState: "complete",
+ generatedSiteRootPresent: true,
+ layoutStable: true,
+ },
+ })),
+ preparePreviewProject: vi.fn(async () => ({ cwd: "/tmp/preview" })),
+ createPreviewController: vi.fn(() => preview),
+ }
+ )
+ ).rejects.toBeInstanceOf(HandledCliError);
+
+ expect(JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0])).toEqual(
+ expect.objectContaining({
+ ok: false,
+ error: {
+ code: "SCREENSHOT_HTTP_ERROR",
+ message: expect.stringContaining("HTTP 404"),
+ },
+ data: {
+ output: "/tmp/missing.png",
+ navigation: expect.objectContaining({ status: 404 }),
+ },
+ })
+ );
+ expect(preview.stop).toHaveBeenCalledOnce();
+});
+
test("stops the temporary preview when project route capture fails", async () => {
const preview = {
startAndWait: vi.fn(async () => ({
diff --git a/packages/cli/src/commands/screenshot.ts b/packages/cli/src/commands/screenshot.ts
index d9aaa93718..7f866d81a3 100644
--- a/packages/cli/src/commands/screenshot.ts
+++ b/packages/cli/src/commands/screenshot.ts
@@ -51,6 +51,12 @@ export const screenshotOptions = (yargs: CommonYargsArgv) =>
default: 5173,
describe: "Port used by the temporary project preview server",
})
+ .option("image-domain", {
+ type: "string",
+ array: true,
+ describe:
+ "External image hostname allowed when --path starts a generated preview; repeat for multiple hosts",
+ })
.option("output", {
type: "string",
alias: "o",
@@ -257,6 +263,31 @@ export const screenshot = async (
},
});
+ if (
+ options.path !== undefined &&
+ result.navigation?.status !== undefined &&
+ result.navigation.status >= 400
+ ) {
+ const message = `Generated preview returned HTTP ${result.navigation.status} for ${result.navigation.finalUrl}.`;
+ if (options.json) {
+ printJson({
+ ok: false,
+ error: {
+ code: "SCREENSHOT_HTTP_ERROR",
+ message,
+ },
+ data: {
+ output: result.output,
+ navigation: result.navigation,
+ },
+ meta: { command: "screenshot" },
+ });
+ } else {
+ log.error(message);
+ }
+ throw new HandledCliError();
+ }
+
if (options.json) {
printJson({
ok: true,
@@ -268,6 +299,8 @@ export const screenshot = async (
fullPage: result.fullPage,
elapsedMs: result.elapsedMs,
warnings: result.warnings,
+ navigation: result.navigation,
+ layout: result.layout,
},
meta: { command: "screenshot" },
});
@@ -283,13 +316,18 @@ export const screenshot = async (
const host = options.host ?? "127.0.0.1";
const port = options.port ?? 5173;
- validatePreviewServerOptions({ host, port });
+ validatePreviewServerOptions({
+ host,
+ port,
+ imageDomains: options.imageDomain,
+ });
const previewProject = await (
dependencies.preparePreviewProject ?? preparePreviewProject
)({
assets: true,
template: [...previewDefaultTemplate],
generate: true,
+ silent: options.json,
});
const preview = (
dependencies.createPreviewController ?? createPreviewController
@@ -297,8 +335,10 @@ export const screenshot = async (
try {
await preview.startAndWait({
cwd: previewProject.cwd,
+ buildCacheKey: previewProject.buildCacheKey,
host,
port,
+ imageDomains: options.imageDomain,
restart: true,
});
await capture(preview.resolveUrl(options.path));
diff --git a/packages/cli/src/commands/sync.test.ts b/packages/cli/src/commands/sync.test.ts
index b735a40769..af8b9ca86c 100644
--- a/packages/cli/src/commands/sync.test.ts
+++ b/packages/cli/src/commands/sync.test.ts
@@ -82,7 +82,7 @@ test("writes current data version after synchronizing from the API", async () =>
bundleVersion,
});
expect(indicator.stop).toHaveBeenCalledWith(
- "Project bundle synchronized successfully (AGENTS.md: unchanged)"
+ "Project bundle synchronized successfully (AGENTS.md: unchanged). Next: webstudio connect"
);
});
@@ -111,7 +111,7 @@ test("materializes project agent instructions during sync", async () => {
"Use existing design tokens."
);
expect(indicator.stop).toHaveBeenCalledWith(
- "Project bundle synchronized successfully (AGENTS.md: created)"
+ "Project bundle synchronized successfully (AGENTS.md: created). Next: webstudio connect"
);
});
diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.ts
index 3a2df8ec01..ed7a44ba22 100644
--- a/packages/cli/src/commands/sync.ts
+++ b/packages/cli/src/commands/sync.ts
@@ -201,7 +201,7 @@ export const sync = async (
syncing.stop(
agents.status === "blocked-by-user-file"
- ? `Project bundle synchronized; AGENTS.md blocked by user-owned file at ${agents.path}`
- : `Project bundle synchronized successfully (AGENTS.md: ${agents.status})`
+ ? `Project bundle synchronized; AGENTS.md blocked by user-owned file at ${agents.path}. Next: webstudio connect`
+ : `Project bundle synchronized successfully (AGENTS.md: ${agents.status}). Next: webstudio connect`
);
};
diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts
index 110b271432..17f6610907 100644
--- a/packages/cli/src/config.ts
+++ b/packages/cli/src/config.ts
@@ -3,7 +3,8 @@ import { readdirSync } from "node:fs";
import envPaths from "env-paths";
import { z } from "zod";
-const GLOBAL_CONFIG_FOLDER = envPaths("webstudio").config;
+const GLOBAL_CONFIG_FOLDER =
+ process.env.WEBSTUDIO_CONFIG_DIR ?? envPaths("webstudio").config;
const GLOBAL_CONFIG_FILE_NAME = "webstudio-config.json";
export const GLOBAL_CONFIG_FILE = join(
GLOBAL_CONFIG_FOLDER,
diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.ts
index 8c3b6b60a3..50f7692e89 100644
--- a/packages/cli/src/docs.generated.ts
+++ b/packages/cli/src/docs.generated.ts
@@ -2,17 +2,17 @@
// Edit markdown files in src/docs instead.
export const cliDocs = {
"api-use-cases":
- '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n\nNotes:\n\n- Use `webstudio schema mcp` for a tiny machine-readable MCP tool overview. Use `webstudio schema mcp --detail summary` for all tool descriptions, and `webstudio schema mcp --detail full` or focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Upload, replace, delete, and inspect asset usage.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations and after generated project files are current so a vision-capable AI can see the production-like generated site.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- After MCP mutations, path screenshots regenerate/restart preview as needed before capture; when preview is fresh, repeated path screenshots reuse the running server.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- Preview isolates generated app dependencies under `.webstudio/preview` by linking to the CLI package dependency tree.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If preview fails with a missing generated-app command/package such as react-router, react-router-serve, or vite, install dependencies for the CLI package and retry.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":"200"}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {"includePages":true}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown component ids fall back to a single-element instance when no template exists.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- Store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"includeStyles":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `includeStyles:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","force":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts?tag=\\" + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\\"Bearer \\" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n\nNotes:\n\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility,seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use existing scripts/resources for behavior, then move presentational structure into editable Webstudio instances where possible.\n- There is no dedicated semantic command yet for converting script-generated UI into editable Webstudio structure.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still requires manual resources, props, embeds, or patches.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after external design interpretation. There is no dedicated import command for Figma, screenshots, Inception output, or design.md yet.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n- webstudio permissions --json\n- webstudio mcp\n\nNotes:\n\n- Public API and CLI intentionally operate on one configured project at a time. Use an external script to loop over projects.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCreate the page, resources, variables, props, and embeds manually with existing MCP semantic tools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Dynamic script/runtime integration helpers\n\nMissing:\nCLI can manipulate props/resources/embeds, but has no semantic workflow for converting script-generated UI into editable Webstudio structures.\n\nCurrent fallback:\nUse MCP props, resources, and raw patch where necessary.\n\nSuggested commands:\n\n- integrate-runtime-ui\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nUse external generation, then apply semantic CLI commands or apply-patch.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',
+ '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a tiny machine-readable MCP tool overview. Use `webstudio schema mcp --detail summary` for all tool descriptions, and `webstudio schema mcp --detail full` or focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Upload, replace, delete, and inspect asset usage.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations and after generated project files are current so a vision-capable AI can see the production-like generated site.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- After MCP mutations, path screenshots regenerate/restart preview as needed before capture; when preview is fresh, repeated path screenshots reuse the running server.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":"200"}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {"includePages":true}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- Store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"includeStyles":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `includeStyles:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","force":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts?tag=\\" + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\\"Bearer \\" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n\nNotes:\n\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: components.get {"component":"ws:collection"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:collection"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n- MCP tool: bind-props {"bindings":[{"instanceId":"<collectionId>","name":"data","binding":{"type":"expression","value":"posts.data"}}]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Bind the Collection `data` prop to the complete array or object. Do not bind the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Insert Collection with `insert-component` so Webstudio creates its internal current-item and current-key parameters. Preserve those generated parameters; they are scoped runtime context, not public records to create, replace, or delete.\n- Collection renders its child structure once for every entry. Bind descendant text and props to the current item. Array iteration exposes the item; object iteration exposes its key and value.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use existing scripts/resources for behavior, then move presentational structure into editable Webstudio instances where possible.\n- There is no dedicated semantic command yet for converting script-generated UI into editable Webstudio structure.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still requires manual resources, props, embeds, or patches.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after external design interpretation. There is no dedicated import command for Figma, screenshots, Inception output, or design.md yet.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n- webstudio permissions --json\n- webstudio mcp\n\nNotes:\n\n- Public API and CLI intentionally operate on one configured project at a time. Use an external script to loop over projects.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCreate the page, resources, variables, props, and embeds manually with existing MCP semantic tools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Dynamic script/runtime integration helpers\n\nMissing:\nCLI can manipulate props/resources/embeds, but has no semantic workflow for converting script-generated UI into editable Webstudio structures.\n\nCurrent fallback:\nUse MCP props, resources, and raw patch where necessary.\n\nSuggested commands:\n\n- integrate-runtime-ui\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nUse external generation, then apply semantic CLI commands or apply-patch.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',
"manual-api":
- '# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand MCP tools expose it through two user-facing groups:\n\n- data variables: `list-variables`, `create-variable`, `update-variable`, and\n `delete-variable`\n- data resources: `list-resources`, `create-resource`, `update-resource`, and\n `delete-resource`\n\nFor raw `snapshot`, request the public `variables` namespace rather than the\ninternal `dataSources` name. Raw patch payloads still use `dataSources` when\napplying direct changes.\n\nVariables can be scoped to an instance. Expressions under that instance can use\nthe variable by name; nested variables with the same name mask outer variables.\nVariable values support `string`, `number`, `boolean`, `string[]`, and `json`.\nUse `string[]` for lists of strings such as tags or selected categories; use\n`json` for objects, arrays with mixed shapes, or nested API filter state.\nParameters are internal scoped runtime values provided by pages, collections,\nor components. They are not a public authoring surface: do not create, update,\nor delete parameter records. Public tools should preserve existing parameter\nrecords and may reference documented context values such as `system` in\nexpressions where they are already in scope.\n\nResource `url` accepts plain fixed URLs and paths, for example\n`https://api.example.com/posts` or `/$resources/current-date`. Dynamic URLs can\ncombine strings and variables, for example\n`"https://api.example.com/posts?tag=" + filters.tag`. Prefer `searchParams` for\nquery parameters that should be encoded separately:\n`[{ "name": "tag", "value": "filters.tag" }]`. Header values, search parameter\nvalues, and bodies are expressions for dynamic content. For fixed text, use\n`{ "type": "literal", "value": "application/json" }`; Webstudio stores the\nrequired string expression. Headers can still read variables such as\n`"Bearer " + auth.token`, and GraphQL bodies can return objects such as\n`{ query: "...", variables: { slug: system.params.slug } }`.\n\nCreate a resource with `scopeInstanceId`/`--scope-instance` when the fetched\nresource result should be available as a read data variable. Scoped resources\nare generated into the page resource `data` map and may be loaded during page\nrendering. Use this shape for read-oriented resources such as GET CMS/API data.\nUse `dataSourceName` or `--data-source-name` to choose the variable name.\n\nFor submit/write/action resources, create the resource without\n`scopeInstanceId`, then bind a component prop such as a Form `action` to the\nresource with `bind-props` and `binding.type: "resource"`. Prop-bound resources\nare generated into the page resource `action` map instead of the read `data`\nmap. Use this shape for POST, PUT, DELETE, webhook, and other resources that\nshould run only from an explicit form/action flow, not merely because the page\nrendered.\n\nResource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read\ndata. Use POST for creates, GraphQL requests, webhooks, and form submissions.\nUse PUT for full updates/replacements. Use DELETE for deletion actions.\nOptional `control` values are `graphql` and `system`: `graphql` marks a\nGraphQL-style resource, usually POST with a query body; `system` marks a\nresource intended to use the built-in `system` parameter or one of the built-in\nlocal resource URLs: `"/$resources/sitemap.xml"`,\n`"/$resources/current-date"`, and `"/$resources/assets"`. The system parameter\nfields are `system.origin`, `system.pathname`, `system.params`, and\n`system.search`.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "patch-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "patch-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',
+ '# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand MCP tools expose it through two user-facing groups:\n\n- data variables: `list-variables`, `create-variable`, `update-variable`, and\n `delete-variable`\n- data resources: `list-resources`, `create-resource`, `update-resource`, and\n `delete-resource`\n\nFor raw `snapshot`, request the public `variables` namespace rather than the\ninternal `dataSources` name. Raw patch payloads still use `dataSources` when\napplying direct changes.\n\nVariables can be scoped to an instance. Expressions under that instance can use\nthe variable by name; nested variables with the same name mask outer variables.\nVariable values support `string`, `number`, `boolean`, `string[]`, and `json`.\nUse `string[]` for lists of strings such as tags or selected categories; use\n`json` for objects, arrays with mixed shapes, or nested API filter state.\nParameters are internal scoped runtime values provided by pages, collections,\nor components. They are not a public authoring surface: do not create, update,\nor delete parameter records. Public tools should preserve existing parameter\nrecords and may reference documented context values such as `system` in\nexpressions where they are already in scope.\n\nResource `url` accepts plain fixed URLs and paths, for example\n`https://api.example.com/posts` or `/$resources/current-date`. Dynamic URLs can\ncombine strings and variables, for example\n`"https://api.example.com/posts?tag=" + filters.tag`. Prefer `searchParams` for\nquery parameters that should be encoded separately:\n`[{ "name": "tag", "value": "filters.tag" }]`. Header values, search parameter\nvalues, and bodies are expressions for dynamic content. For fixed text, use\n`{ "type": "literal", "value": "application/json" }`; Webstudio stores the\nrequired string expression. Headers can still read variables such as\n`"Bearer " + auth.token`, and GraphQL bodies can return objects such as\n`{ query: "...", variables: { slug: system.params.slug } }`.\n\nCreate a GET resource with `scopeInstanceId` when the fetched resource result\nshould be available as a read data variable. Scoped GET resources default to\n`exposeAsDataSource: true`, are generated into the page resource `data` map,\nand may be loaded during page rendering. Use `dataSourceName` to choose the\nvariable name.\n\nFor submit/write/action resources, create the resource without\n`scopeInstanceId`, then bind a component prop such as a Form `action` to the\nresource with `bind-props` and `binding.type: "resource"`. Prop-bound resources\nare generated into the page resource `action` map instead of the read `data`\nmap. Use this shape for POST, PUT, DELETE, webhook, and other resources that\nshould run only from an explicit form/action flow, not merely because the page\nrendered.\n\nPOST, PUT, and DELETE resources default to `exposeAsDataSource: false` even\nwhen a scope is supplied. Set `exposeAsDataSource: true` only when a write-method\nresource intentionally provides render-time data, such as a read-only GraphQL\nPOST query. A scope is required, and the result includes a warning because the\nrequest may execute during page rendering. Set `exposeAsDataSource: false` on\n`update-resource` to detach an existing render-time data source.\n\nResource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read\ndata. Use POST for creates, GraphQL requests, webhooks, and form submissions.\nUse PUT for full updates/replacements. Use DELETE for deletion actions.\nOptional `control` values are `graphql` and `system`: `graphql` marks a\nGraphQL-style resource, usually POST with a query body; `system` marks a\nresource intended to use the built-in `system` parameter or one of the built-in\nlocal resource URLs: `"/$resources/sitemap.xml"`,\n`"/$resources/current-date"`, and `"/$resources/assets"`. The system parameter\nfields are `system.origin`, `system.pathname`, `system.params`, and\n`system.search`.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "patch-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "patch-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',
"manual-llm":
- '# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a tiny MCP tool overview. Use `webstudio schema mcp --detail summary` for all tool descriptions, and `webstudio schema mcp --detail full` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get_more_tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe same local shortcut form is shorter and preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor this simple path, do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in the block\'s `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <ws.element\n ws:tag="section"\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. Inspect current project state with semantic reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.\n5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n4. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, `status`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`. Use `string[]` only for arrays where every item is a string; use `json` for objects, mixed arrays, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A resource created with `scopeInstanceId`/`dataSourceName` becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Use this for GET CMS/API data and read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can be expressions such as `"\\"Bearer \\" + auth.token"`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- For visual/design work, verify the rendered result with vision before finishing.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',
+ '# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a tiny MCP tool overview. Use `webstudio schema mcp --detail summary` for all tool descriptions, and `webstudio schema mcp --detail full` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get_more_tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe same local shortcut form is shorter and preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor this simple path, do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in the block\'s `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <ws.element\n ws:tag="section"\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. Inspect current project state with semantic reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.\n5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n4. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, `status`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`. Use `string[]` only for arrays where every item is a string; use `json` for objects, mixed arrays, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- POST, PUT, and DELETE resources default to `exposeAsDataSource:false`, even with a scope. Set `exposeAsDataSource:true` only for an intentional render-time read such as a GraphQL POST query; provide `scopeInstanceId` and inspect the returned warning. Set it to `false` during `update-resource` to detach existing render-time exposure.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can be expressions such as `"\\"Bearer \\" + auth.token"`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n- Whenever an array or object from a resource or data variable should render repeated UI, use Collection. Insert `ws:collection` with `insert-component`, bind its `data` prop to the complete iterable rather than the response wrapper or one indexed item, preserve the generated `item`/`itemKey` parameters, and bind descendants to the current iteration context. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.\n- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Prefer optional chaining, nullish coalescing, ternaries, property/index access, operators, and the documented string/array methods.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- For visual/design work, verify the rendered result with vision before finishing.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',
"manual-mcp":
- '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. For shell-driven agents, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. For MCP clients, start the server with `webstudio mcp`.\n5. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Prefer JSX for authored/styled content. Common `insert-fragment` inputs:\n\n```jsonl\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag="h2">Northstar Product OS</ws.element><ws.element ws:tag="p">Reusable patterns for teams.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" style={{ padding: 32, borderRadius: 16 }}><ws.element ws:tag="h2">Operations Console</ws.element><ws.element ws:tag="p">React-style object styles become editable Webstudio styles.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:tokens={[token(\\"accent\\", css`color: #0f766e;`)]}><ws.element ws:tag="button" onClick={new ActionValue([\\"event\\"], expression`console.log(event)`)}>Track launch</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\"><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n```\n\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, `mcp run` stops immediately before later calls and prints partial results with `CHECKPOINT_REQUIRED`. Stop now and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: shadcn-compatible registry items for visible components and templates\n- `components.summary`: compact structured component catalog with insertability and template hints\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: shadcn-compatible registry items for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, string list, and JSON variables.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List, upload, add, update, find usage for, replace, and delete assets.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- A mutation is durable only when `meta.session.committed` is true.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects:\n\n{{mcpArgumentExampleIndex}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',
+ '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Generate the client configuration with `webstudio connect claude`,\n `webstudio connect codex`, `webstudio connect cursor`, or\n `webstudio connect vscode`. Use `--print` to preview file-based config.\n3. Check capabilities with `webstudio permissions --json`.\n4. For shell-driven agents, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n5. For MCP clients, start the server with `webstudio mcp`.\n6. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Prefer JSX for authored/styled content. Common `insert-fragment` inputs:\n\n```jsonl\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag="h2">Northstar Product OS</ws.element><ws.element ws:tag="p">Reusable patterns for teams.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" style={{ padding: 32, borderRadius: 16 }}><ws.element ws:tag="h2">Operations Console</ws.element><ws.element ws:tag="p">React-style object styles become editable Webstudio styles.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:tokens={[token(\\"accent\\", css`color: #0f766e;`)]}><ws.element ws:tag="button" onClick={new ActionValue([\\"event\\"], expression`console.log(event)`)}>Track launch</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\"><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n```\n\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, `mcp run` stops immediately before later calls and prints partial results with `CHECKPOINT_REQUIRED`. Stop now and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: shadcn-compatible registry items for visible components and templates\n- `components.summary`: compact structured component catalog with insertability and template hints\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: shadcn-compatible registry items for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, string list, and JSON variables.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List, upload, add, update, find usage for, replace, and delete assets.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- A mutation is durable only when `meta.session.committed` is true.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects:\n\n{{mcpArgumentExampleIndex}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',
"mcp-startup-epilogue":
'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in the block\'s `ws:block-template` child. Templates themselves are protected; an editor\'s inserted copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get_more_tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, later one-shot calls fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nIf a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in the Webstudio Discord `#help` channel at https://wstd.us/community. Give the user a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n\nIf you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.\n',
"mcp-vision":
- '# MCP Vision Verification\n\n## Generated App Dependency Notes\n\n- `preview.start` and `webstudio preview` isolate generated app dependencies under `.webstudio/preview` by linking to the CLI package dependency tree.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If preview fails with a missing generated-app command/package such as react-router, react-router-serve, or vite, install dependencies for the CLI package and retry.\n\n## Visual Verification Rule\n\nFor visual/design work, use preview.start and screenshot after generated project files are current so vision can inspect the rendered result before finishing. `preview.start` is long-lived and cannot be used through one-shot `mcp single-op-call`; from a shell, use `webstudio mcp run` for preview.start/screenshot/preview.stop in one shared process, or use a long-running MCP server. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.\n\n## Vision Verification Loop\n\n- Make focused page/content/style changes with semantic MCP tools.\n- Make sure generated project files are current, then call preview.start to build the app and keep the production-like generated site running. In shell-driven workflows, run preview.start, screenshot, and preview.stop inside one `webstudio mcp run` call so they share the same preview owner.\n- {{dependency-notes}}\n- After MCP mutations, path-based screenshots regenerate/restart preview as needed before capture; when preview is fresh in the same long-running MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview without starting or restarting it. Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview; a separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.\n- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.\n- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baseUrl: "http://127.0.0.1:5177", path: "/" }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair. Add expectedText when a specific visible phrase must be present; its assertions report pass/fail plus found and missing text. Add expectedVisual to set pass/fail limits for mismatch percentage, the number of changed regions, or an overall dominant color/brightness direction.\n- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, expectedText assertions fail and textAnalysis reports why; ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.\n- Inspect every viewport PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.\n- If the screenshot does not match, apply another focused mutation and repeat screenshot verification.\n\n## Workflow Summary With Diff\n\nFor visual/design work, make sure generated project files are current, call preview.start to build and start the production-like preview server, then screenshot({ path, viewport }) for every changed page path; for responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths; use screenshot.diff on each baseline/current page or viewport pair when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing.\n\n## Workflow Summary Without Diff\n\nFor visual/design work, make sure generated project files are current, call preview.start to build and start the production-like preview server, then screenshot({ path, viewport }) for every changed page path; for responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths; inspect every PNG with vision before finishing.\n\nEach screenshot result includes rendered `layout` metrics when the local browser\nprovides them. `layout.horizontalOverflow: true` is deterministic evidence that\nthe rendered document exceeds the requested viewport width. Use vision for\nclipping, wrapping, hierarchy, and other judgments that layout dimensions alone\ncannot establish.\n\nPass `includeImageMetrics: true` when an ordinary screenshot needs\n`layout.images`; rendered audit enables it automatically. The array includes\neach rendered image\'s Webstudio instance id when available, loading mode,\ncompletion state, natural dimensions, rendered dimensions, and document\nposition. Rendered audits use this evidence to report broken images, eager\nloading below the fold, and sources more than 2x the rendered dimensions in\nboth axes. Oversized-source results are optimization evidence, not universal\nperformance conformance.\n\nPass `includeResourceMetrics: true` when an ordinary screenshot needs sanitized\nResource Timing evidence; rendered audit enables it automatically. Resource\nmetrics contain only the URL pathname, initiator type, transfer/body sizes,\nduration, and browser-provided render-blocking status. Origins and query strings\nare omitted. Rendered audits report explicitly blocking resources and legacy\n`.ttf`, `.otf`, or `.woff` font files without applying a universal byte-size\nbudget.\n\n## Screenshot Verification Summary\n\nInside a long-running MCP server, prefer preview.start plus screenshot({ path, viewport }) after generated project files are current, so a fresh production-like preview server is available for fast repeated checks across multiple pages. After MCP mutations, path screenshots restart preview as needed before capture; when preview is fresh in that same MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture viewport widths from Builder breakpoint edges plus mobile and desktop widths before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use `webstudio screenshot --path /pricing --output pricing.png` for one temporary generated preview capture, or keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot` for repeated captures.\n\n## Screenshot Diff Evidence\n\n- Pixel evidence: total mismatch, changed regions, dominant color/luminance direction, diffPath, and contextDiffPath.\n- OCR evidence: textAnalysis.status, provider, and changes for appeared/disappeared/content_changed/moved/font_changed text. expectedText adds pass/fail assertions plus found and missing current-screen text. expectedVisual adds pass/fail quantitative checks for mismatch percentage, changed-region count, and the overall dominant color/brightness direction.\n- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.\n- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.\n- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.\n',
+ '# MCP Vision Verification\n\n## Generated App Dependency Notes\n\n- `preview.start` and `webstudio preview` install generated app dependencies under `.webstudio/preview` and reuse them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n\n## Visual Verification Rule\n\nFor visual/design work, use preview.start and screenshot after generated project files are current so vision can inspect the rendered result before finishing. `preview.start` is long-lived and cannot be used through one-shot `mcp single-op-call`; from a shell, use `webstudio mcp run` for preview.start/screenshot/preview.stop in one shared process, or use a long-running MCP server. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.\n\nAn authenticated project share URL is used with `webstudio init --link`; it is\nnot a generated-site preview URL. Project screenshots and rendered audits use\nthe generated local preview owned by the current CLI/MCP process. Do not pass a\nBuilder URL containing `authToken` and `mode` to `screenshot`; use `path` after\nstarting preview, or use `baseUrl` only for an intentional generated site that\nis already running.\n\n## Vision Verification Loop\n\n- Make focused page/content/style changes with semantic MCP tools.\n- Make sure generated project files are current, then call preview.start to build the app and keep the production-like generated site running. In shell-driven workflows, run preview.start, screenshot, and preview.stop inside one `webstudio mcp run` call so they share the same preview owner.\n- {{dependency-notes}}\n- After MCP mutations, path-based screenshots regenerate/restart preview as needed before capture; when preview is fresh in the same long-running MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview without starting or restarting it. Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview; a separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.\n- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.\n- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baseUrl: "http://127.0.0.1:5177", path: "/" }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair. Add expectedText when a specific visible phrase must be present; its assertions report pass/fail plus found and missing text. Add expectedVisual to set pass/fail limits for mismatch percentage, the number of changed regions, or an overall dominant color/brightness direction.\n- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, expectedText assertions fail and textAnalysis reports why; ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.\n- Inspect every viewport PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.\n- If the screenshot does not match, apply another focused mutation and repeat screenshot verification.\n\n## Workflow Summary With Diff\n\nFor visual/design work, make sure generated project files are current, call preview.start to build and start the production-like preview server, then screenshot({ path, viewport }) for every changed page path; for responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths; use screenshot.diff on each baseline/current page or viewport pair when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing.\n\n## Workflow Summary Without Diff\n\nFor visual/design work, make sure generated project files are current, call preview.start to build and start the production-like preview server, then screenshot({ path, viewport }) for every changed page path; for responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths; inspect every PNG with vision before finishing.\n\nEach screenshot result includes rendered `layout` metrics when the local browser\nprovides them. `layout.horizontalOverflow: true` is deterministic evidence that\nthe rendered document exceeds the requested viewport width. Use vision for\nclipping, wrapping, hierarchy, and other judgments that layout dimensions alone\ncannot establish.\n\nPass `includeImageMetrics: true` when an ordinary screenshot needs\n`layout.images`; rendered audit enables it automatically. The array includes\neach rendered image\'s Webstudio instance id when available, loading mode,\ncompletion state, natural dimensions, rendered dimensions, and document\nposition. Rendered audits use this evidence to report broken images, eager\nloading below the fold, and sources more than 2x the rendered dimensions in\nboth axes. Oversized-source results are optimization evidence, not universal\nperformance conformance.\n\nPass `includeResourceMetrics: true` when an ordinary screenshot needs sanitized\nResource Timing evidence; rendered audit enables it automatically. Resource\nmetrics contain only the URL pathname, initiator type, transfer/body sizes,\nduration, and browser-provided render-blocking status. Origins and query strings\nare omitted. Rendered audits report explicitly blocking resources and legacy\n`.ttf`, `.otf`, or `.woff` font files without applying a universal byte-size\nbudget.\n\n## Screenshot Verification Summary\n\nInside a long-running MCP server, prefer preview.start plus screenshot({ path, viewport }) after generated project files are current, so a fresh production-like preview server is available for fast repeated checks across multiple pages. After MCP mutations, path screenshots restart preview as needed before capture; when preview is fresh in that same MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture one familiar device viewport inside each Builder breakpoint range before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use `webstudio screenshot --path /pricing --output pricing.png` for one temporary generated preview capture, or keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot` for repeated captures.\n\n## Screenshot Diff Evidence\n\n- Pixel evidence: total mismatch, changed regions, dominant color/luminance direction, diffPath, and contextDiffPath.\n- OCR evidence: textAnalysis.status, provider, and changes for appeared/disappeared/content_changed/moved/font_changed text. expectedText adds pass/fail assertions plus found and missing current-screen text. expectedVisual adds pass/fail quantitative checks for mismatch percentage, changed-region count, and the overall dominant color/brightness direction.\n- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.\n- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.\n- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.\n',
} as const;
export const cliDocTitles = {
@@ -82,10 +82,13 @@ export const cliDocSections = {
'Resource update example: use update-resource with {"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}.',
"Data variable values support string, number, boolean, string[], and json. Use string[] only for arrays where every item is a string; use json for objects, mixed arrays, filters, and nested data.",
"Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as system in expressions where they are already in scope.",
- "Use scoped resources for read data. A resource created with scopeInstanceId/dataSourceName becomes a scoped resource data variable, is generated into the page resource data map, and may be loaded while rendering the page. Use this for GET CMS/API data and read the loaded resource result from its wrapper, usually .data.",
+ "Use scoped resources for read data. A GET resource created with scopeInstanceId/dataSourceName defaults to exposeAsDataSource:true, becomes a scoped resource data variable, is generated into the page resource data map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually .data.",
'Use prop-bound resources for actions. A resource created without scopeInstanceId and bound to a component prop such as Form action with bind-props and binding.type: "resource" becomes an action resource in the page resource action map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.',
+ "POST, PUT, and DELETE resources default to exposeAsDataSource:false, even with a scope. Set exposeAsDataSource:true only for an intentional render-time read such as a GraphQL POST query; provide scopeInstanceId and inspect the returned warning. Set it to false during update-resource to detach existing render-time exposure.",
'For dynamic resource query parameters prefer searchParams, for example {"name":"tag","value":"filters.tag"}. Use {"type":"literal","value":"website"} for fixed request text. Header values can be expressions such as "\\"Bearer \\" + auth.token". Body can be an object expression, including GraphQL payloads such as { query: "...", variables: { slug: system.params.slug } }.',
'Resource methods are get, post, put, and delete. Optional resource controls are graphql and system. Use control:"graphql" for GraphQL POST resources with query bodies. Use control:"system" for built-in local resource URLs such as "/$resources/current-date" and for resources reading the built-in system parameter. The built-in system fields are system.origin, system.pathname, system.params, and system.search; do not use system.path.',
+ "Whenever an array or object from a resource or data variable should render repeated UI, use Collection. Insert ws:collection with insert-component, bind its data prop to the complete iterable rather than the response wrapper or one indexed item, preserve the generated item/itemKey parameters, and bind descendants to the current iteration context. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique value bindings.",
+ "Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, new, this, await, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Prefer optional chaining, nullish coalescing, ternaries, property/index access, operators, and the documented string/array methods.",
],
rules: [
"Never guess ids for existing records. Read them first.",
diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.md
index 95e3966e3f..fafab2c9e1 100644
--- a/packages/cli/src/docs/api-use-cases.md
+++ b/packages/cli/src/docs/api-use-cases.md
@@ -56,11 +56,13 @@ Commands:
- MCP tool: meta.get_more_tools {"brief":"update-styles"}
- webstudio mcp list-resources
- webstudio mcp read-resource webstudio://project/guide
+- webstudio mcp read-resource webstudio://project/expressions
Notes:
- Use `webstudio schema mcp` for a tiny machine-readable MCP tool overview. Use `webstudio schema mcp --detail summary` for all tool descriptions, and `webstudio schema mcp --detail full` or focused `meta.get_more_tools` calls only when exact input schemas are needed.
- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.
+- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.
- From a shell, call one MCP tool with the shortcut form `webstudio <tool> '<json>'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> '<json>'`. Use `--input-file` for large payloads.
## Inspect external shadcn registry items
@@ -148,9 +150,9 @@ Notes:
- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.
- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process's preview controller.
- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.
-- Preview isolates generated app dependencies under `.webstudio/preview` by linking to the CLI package dependency tree.
+- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.
- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.
-- If preview fails with a missing generated-app command/package such as react-router, react-router-serve, or vite, install dependencies for the CLI package and retry.
+- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.
- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.
- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.
- Compare the PNG, OCR text evidence, and diff artifacts against the user's intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.
@@ -381,10 +383,14 @@ Commands:
- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\"section\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\"h2\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}
- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}
+- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}
Notes:
- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.
+- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.
+- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.
+- For Webstudio's complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.
- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.
- In `insert-fragment` JSX, use `ws:style={css\`...\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.
- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.
@@ -396,7 +402,7 @@ Notes:
- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.
- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.
- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.
-- Unknown component ids fall back to a single-element instance when no template exists.
+- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.
## Make a region editable in Content mode
@@ -874,9 +880,12 @@ Notes:
Commands:
- webstudio audit --json
-- webstudio audit --scopes accessibility,seo --json
+- webstudio audit --scopes accessibility --scopes seo --json
- webstudio audit --page-path /pricing --json
- webstudio audit --scopes accessibility --verbose --json
+- webstudio audit --rendered --page-path /pricing --json
+- webstudio audit --rendered --route-example post=/blog/hello --json
+- webstudio audit --rendered --image-domain images.example.com --json
- MCP tool: audit {}
- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}
- MCP tool: audit {"scopes":["accessibility"],"verbose":true}
@@ -893,12 +902,21 @@ Notes:
- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.
- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.
- Continue paginated results with `cursor`. Restart the audit if the project version changes.
+- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.
- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.
- Focused audits return only manual checks relevant to their selected scopes.
- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot
tools to capture every static page at mobile, desktop, and Builder breakpoint
edges. Compact output reports rendered check/issue/failure counts; verbose
output includes screenshot paths and measured layout dimensions.
+- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`
+ (or MCP `routeExamples`) supplies a concrete path. The path must not contain
+ unresolved `:` or `*` parameters.
+- Plans above 120 captures return a short-lived confirmation token. Review the
+ unchanged plan, then rerun with `--confirm-large-run` and
+ `--confirmation-token`.
+- Detailed rendered evidence is stored in a versioned manifest under
+ `.webstudio/audits`; compact output includes its path and screenshot count.
- Rendered checks also report broken images, eager images below the fold, and
image sources more than 2x their rendered dimensions in both axes, including
Webstudio instance ids and measured dimensions when available.
@@ -965,6 +983,25 @@ Notes:
- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.
- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.
+## Render an array or object as repeated content
+
+Commands:
+
+- MCP tool: components.get {"component":"ws:collection"}
+- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:collection"}
+- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}
+- MCP tool: bind-props {"bindings":[{"instanceId":"<collectionId>","name":"data","binding":{"type":"expression","value":"posts.data"}}]}
+
+Notes:
+
+- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.
+- Bind the Collection `data` prop to the complete array or object. Do not bind the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result's `data` field or deeper.
+- Insert Collection with `insert-component` so Webstudio creates its internal current-item and current-key parameters. Preserve those generated parameters; they are scoped runtime context, not public records to create, replace, or delete.
+- Collection renders its child structure once for every entry. Bind descendant text and props to the current item. Array iteration exposes the item; object iteration exposes its key and value.
+- Wrap multiple repeated sibling instances in one Element inside Collection.
+- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.
+- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.
+
## Support dynamic runtime behavior
Commands:
diff --git a/packages/cli/src/docs/manual-api.md b/packages/cli/src/docs/manual-api.md
index a976381d20..720853d1e1 100644
--- a/packages/cli/src/docs/manual-api.md
+++ b/packages/cli/src/docs/manual-api.md
@@ -144,11 +144,11 @@ required string expression. Headers can still read variables such as
`"Bearer " + auth.token`, and GraphQL bodies can return objects such as
`{ query: "...", variables: { slug: system.params.slug } }`.
-Create a resource with `scopeInstanceId`/`--scope-instance` when the fetched
-resource result should be available as a read data variable. Scoped resources
-are generated into the page resource `data` map and may be loaded during page
-rendering. Use this shape for read-oriented resources such as GET CMS/API data.
-Use `dataSourceName` or `--data-source-name` to choose the variable name.
+Create a GET resource with `scopeInstanceId` when the fetched resource result
+should be available as a read data variable. Scoped GET resources default to
+`exposeAsDataSource: true`, are generated into the page resource `data` map,
+and may be loaded during page rendering. Use `dataSourceName` to choose the
+variable name.
For submit/write/action resources, create the resource without
`scopeInstanceId`, then bind a component prop such as a Form `action` to the
@@ -158,6 +158,13 @@ map. Use this shape for POST, PUT, DELETE, webhook, and other resources that
should run only from an explicit form/action flow, not merely because the page
rendered.
+POST, PUT, and DELETE resources default to `exposeAsDataSource: false` even
+when a scope is supplied. Set `exposeAsDataSource: true` only when a write-method
+resource intentionally provides render-time data, such as a read-only GraphQL
+POST query. A scope is required, and the result includes a warning because the
+request may execute during page rendering. Set `exposeAsDataSource: false` on
+`update-resource` to detach an existing render-time data source.
+
Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read
data. Use POST for creates, GraphQL requests, webhooks, and form submissions.
Use PUT for full updates/replacements. Use DELETE for deletion actions.
diff --git a/packages/cli/src/docs/manual-llm.md b/packages/cli/src/docs/manual-llm.md
index 5217a3f116..3d99bb1f0e 100644
--- a/packages/cli/src/docs/manual-llm.md
+++ b/packages/cli/src/docs/manual-llm.md
@@ -412,6 +412,8 @@ For responsive page work, use Builder breakpoints as the source of truth:
## Values vs Bindings
+Before authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.
+
- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop's direct type/value.
- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.
- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.
@@ -422,10 +424,13 @@ For responsive page work, use Builder breakpoints as the source of truth:
- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.
- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`. Use `string[]` only for arrays where every item is a string; use `json` for objects, mixed arrays, filters, and nested data.
- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.
-- Use scoped resources for read data. A resource created with `scopeInstanceId`/`dataSourceName` becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Use this for GET CMS/API data and read the loaded resource result from its wrapper, usually `.data`.
+- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.
- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.
+- POST, PUT, and DELETE resources default to `exposeAsDataSource:false`, even with a scope. Set `exposeAsDataSource:true` only for an intentional render-time read such as a GraphQL POST query; provide `scopeInstanceId` and inspect the returned warning. Set it to `false` during `update-resource` to detach existing render-time exposure.
- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can be expressions such as `"\"Bearer \" + auth.token"`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.
- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.
+- Whenever an array or object from a resource or data variable should render repeated UI, use Collection. Insert `ws:collection` with `insert-component`, bind its `data` prop to the complete iterable rather than the response wrapper or one indexed item, preserve the generated `item`/`itemKey` parameters, and bind descendants to the current iteration context. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.
+- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Prefer optional chaining, nullish coalescing, ternaries, property/index access, operators, and the documented string/array methods.
## Pick Read Command
diff --git a/packages/cli/src/docs/manual-mcp.md b/packages/cli/src/docs/manual-mcp.md
index 8c4b3f59b0..a966fc82c7 100644
--- a/packages/cli/src/docs/manual-mcp.md
+++ b/packages/cli/src/docs/manual-mcp.md
@@ -5,10 +5,13 @@
## Startup
1. Configure a project with `webstudio init --link <api-share-link> --json`.
-2. Check capabilities with `webstudio permissions --json`.
-3. For shell-driven agents, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment '<json>' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> '<json>'` when you need to force the MCP path, or `webstudio mcp run '[{"tool":"components.find","input":{"brief":"button"}}]'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.
-4. For MCP clients, start the server with `webstudio mcp`.
-5. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide '{"brief":"Create a design system page using every component"}'`.
+2. Generate the client configuration with `webstudio connect claude`,
+ `webstudio connect codex`, `webstudio connect cursor`, or
+ `webstudio connect vscode`. Use `--print` to preview file-based config.
+3. Check capabilities with `webstudio permissions --json`.
+4. For shell-driven agents, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment '<json>' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> '<json>'` when you need to force the MCP path, or `webstudio mcp run '[{"tool":"components.find","input":{"brief":"button"}}]'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.
+5. For MCP clients, start the server with `webstudio mcp`.
+6. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide '{"brief":"Create a design system page using every component"}'`.
Start MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.
@@ -242,6 +245,7 @@ Useful resources:
- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient
- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient
- `webstudio://project/guide`: concise discovery guide
+- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification
- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots
## MCP SDK Client Imports
diff --git a/packages/cli/src/docs/mcp-vision.md b/packages/cli/src/docs/mcp-vision.md
index 64df951287..ade20c5f01 100644
--- a/packages/cli/src/docs/mcp-vision.md
+++ b/packages/cli/src/docs/mcp-vision.md
@@ -2,14 +2,21 @@
## Generated App Dependency Notes
-- `preview.start` and `webstudio preview` isolate generated app dependencies under `.webstudio/preview` by linking to the CLI package dependency tree.
+- `preview.start` and `webstudio preview` install generated app dependencies under `.webstudio/preview` and reuse them across regenerations.
- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.
-- If preview fails with a missing generated-app command/package such as react-router, react-router-serve, or vite, install dependencies for the CLI package and retry.
+- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.
## Visual Verification Rule
For visual/design work, use preview.start and screenshot after generated project files are current so vision can inspect the rendered result before finishing. `preview.start` is long-lived and cannot be used through one-shot `mcp single-op-call`; from a shell, use `webstudio mcp run` for preview.start/screenshot/preview.stop in one shared process, or use a long-running MCP server. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.
+An authenticated project share URL is used with `webstudio init --link`; it is
+not a generated-site preview URL. Project screenshots and rendered audits use
+the generated local preview owned by the current CLI/MCP process. Do not pass a
+Builder URL containing `authToken` and `mode` to `screenshot`; use `path` after
+starting preview, or use `baseUrl` only for an intentional generated site that
+is already running.
+
## Vision Verification Loop
- Make focused page/content/style changes with semantic MCP tools.
@@ -57,7 +64,7 @@ budget.
## Screenshot Verification Summary
-Inside a long-running MCP server, prefer preview.start plus screenshot({ path, viewport }) after generated project files are current, so a fresh production-like preview server is available for fast repeated checks across multiple pages. After MCP mutations, path screenshots restart preview as needed before capture; when preview is fresh in that same MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture viewport widths from Builder breakpoint edges plus mobile and desktop widths before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use `webstudio screenshot --path /pricing --output pricing.png` for one temporary generated preview capture, or keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot` for repeated captures.
+Inside a long-running MCP server, prefer preview.start plus screenshot({ path, viewport }) after generated project files are current, so a fresh production-like preview server is available for fast repeated checks across multiple pages. After MCP mutations, path screenshots restart preview as needed before capture; when preview is fresh in that same MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture one familiar device viewport inside each Builder breakpoint range before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use `webstudio screenshot --path /pricing --output pricing.png` for one temporary generated preview capture, or keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot` for repeated captures.
## Screenshot Diff Evidence
diff --git a/packages/cli/src/error-codes.test.ts b/packages/cli/src/error-codes.test.ts
index 8255d87ab5..eab6304c39 100644
--- a/packages/cli/src/error-codes.test.ts
+++ b/packages/cli/src/error-codes.test.ts
@@ -22,6 +22,29 @@ describe("getStableErrorCode", () => {
});
describe("getCliErrorMessage", () => {
+ test("turns API procedure skew into actionable CLI update guidance", () => {
+ const error = {
+ data: {
+ apiCompatibility: {
+ type: "webstudioApiCompatibilityError",
+ reason: "apiProcedureNotFound",
+ target: "cli",
+ message:
+ "This version of the Webstudio CLI is incompatible with the current API.",
+ action: { type: "updateCli" },
+ },
+ },
+ };
+
+ expect(getCliErrorMessage(error)).toContain(
+ "npm install -g webstudio@latest"
+ );
+ expect(getCliErrorMessage(error)).toContain("npx webstudio@latest mcp");
+ expect(getCliErrorMessage(error, "update-page")).toContain(
+ "npx webstudio@latest update-page"
+ );
+ });
+
test("explains missing Builder API access for opaque project owner token errors", () => {
const error = Object.assign(
new Error("Project owner can't be found for token token-1"),
diff --git a/packages/cli/src/error-codes.ts b/packages/cli/src/error-codes.ts
index 31cac82460..039552a6ee 100644
--- a/packages/cli/src/error-codes.ts
+++ b/packages/cli/src/error-codes.ts
@@ -1,4 +1,7 @@
-import { getApiErrorCode } from "@webstudio-is/http-client";
+import {
+ getApiCompatibilityMessage,
+ getApiErrorCode,
+} from "@webstudio-is/http-client";
const missingProjectOwnerForTokenPattern =
/^Project owner can't be found for token\b/;
@@ -31,7 +34,14 @@ export const isMissingApiAccessError = (error: unknown) => {
return missingProjectOwnerForTokenPattern.test(message);
};
-export const getCliErrorMessage = (error: unknown) => {
+export const getCliErrorMessage = (error: unknown, command = "mcp") => {
+ const compatibilityMessage = getApiCompatibilityMessage(error, {
+ updateCommand: "npm install -g webstudio@latest",
+ runLatestCommand: `npx webstudio@latest ${command}`,
+ });
+ if (compatibilityMessage !== undefined) {
+ return compatibilityMessage;
+ }
const message = getErrorMessage(error);
if (missingProjectOwnerForTokenPattern.test(message)) {
return "This project cannot be accessed through the Builder API with the current share link/token. Enable API access in the share-link settings, then relink the project with `webstudio init --link <share-link> --json`.";
diff --git a/packages/cli/src/html-to-jsx.test.ts b/packages/cli/src/html-to-jsx.test.ts
index d7a2810092..d3f0f599d9 100644
--- a/packages/cli/src/html-to-jsx.test.ts
+++ b/packages/cli/src/html-to-jsx.test.ts
@@ -2,8 +2,7 @@ import { test, expect } from "vitest";
import * as React from "react";
import ReactDOMServer from "react-dom/server";
import esbuild from "esbuild";
-import prettier from "prettier/standalone";
-import parserHtml from "prettier/parser-html";
+import { format } from "oxfmt";
import { htmlToJsx } from "./html-to-jsx";
@@ -63,10 +62,7 @@ const convertHtmlToJsxAndRenderToHtml = async (htmlCode: string) => {
};
const formatHtml = async (htmlCode: string) => {
- return await prettier.format(htmlCode, {
- parser: "html",
- plugins: [parserHtml],
- });
+ return (await format("document.html", htmlCode)).code;
};
test("Simple conversion works", async () => {
diff --git a/packages/cli/src/mcp-guidance.test.ts b/packages/cli/src/mcp-guidance.test.ts
index d3dca8a6e4..728e2654f6 100644
--- a/packages/cli/src/mcp-guidance.test.ts
+++ b/packages/cli/src/mcp-guidance.test.ts
@@ -9,9 +9,9 @@ import {
test("documents generated app setup for visual verification", () => {
expect(generatedAppDependencyNotes).toEqual([
- expect.stringContaining("isolate generated app dependencies"),
+ expect.stringContaining("install generated app dependencies"),
expect.stringContaining("Do not add generated-preview dependencies"),
- expect.stringContaining("react-router-serve"),
+ expect.stringContaining("check npm and network configuration"),
]);
expect(visualVerificationRule).toContain(
"generated project files are current"
diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.ts
index 0c2ef3b200..b644c77e15 100644
--- a/packages/cli/src/prebuild.test.ts
+++ b/packages/cli/src/prebuild.test.ts
@@ -370,6 +370,113 @@ describe("prebuild", () => {
await expect(
readFile("app/__generated__/$resources.redirects.ts", "utf8")
).resolves.toContain("/dl.php?filename=file.pdf");
+ await expect(readFile("app/constants.mjs", "utf8")).resolves.toContain(
+ "return `/_vercel/image?${searchParams}`"
+ );
+ await expect(readFile("app/routes/[_image].$.ts", "utf8")).rejects.toThrow(
+ "ENOENT"
+ );
+ const packageJson = JSON.parse(await readFile("package.json", "utf8"));
+ expect(packageJson.dependencies).not.toHaveProperty("h3");
+ expect(packageJson.dependencies).not.toHaveProperty("ipx");
+ });
+
+ test("generates homepage, leaf, nested, dynamic, and 404 React Router routes", async () => {
+ await writeSiteData(
+ createSiteData({
+ pages: [
+ {
+ id: "home",
+ name: "Home",
+ title: "Home",
+ path: "",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ {
+ id: "pricing",
+ name: "Pricing",
+ title: "Pricing",
+ path: "/pricing",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ {
+ id: "guide",
+ name: "Guide",
+ title: "Guide",
+ path: "/docs/getting-started",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ {
+ id: "post",
+ name: "Post",
+ title: "Post",
+ path: "/blog/:slug",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ ],
+ })
+ );
+
+ await prebuild({ assets: false, template: ["react-router"] });
+
+ await expect(readFile("app/routes/_index.tsx", "utf8")).resolves.toContain(
+ "../__generated__/_index"
+ );
+ await expect(
+ readFile("app/routes/[pricing]._index.tsx", "utf8")
+ ).resolves.toContain("../__generated__/[pricing]._index");
+ await expect(
+ readFile("app/routes/[docs].[getting-started]._index.tsx", "utf8")
+ ).resolves.toContain("../__generated__/[docs].[getting-started]._index");
+ await expect(
+ readFile("app/routes/[blog].$slug._index.tsx", "utf8")
+ ).resolves.toContain("../__generated__/[blog].$slug._index");
+ await expectGeneratedRedirectFallback("app/routes/$.tsx");
+ });
+
+ test("uses pass-through images in the base react-router template", async () => {
+ await prebuild({ assets: false, template: ["react-router"] });
+
+ await expect(readFile("app/constants.mjs", "utf8")).resolves.toContain(
+ "return props.src"
+ );
+ await expect(readFile("app/routes/[_image].$.ts", "utf8")).rejects.toThrow(
+ "ENOENT"
+ );
+ const packageJson = JSON.parse(await readFile("package.json", "utf8"));
+ expect(packageJson.dependencies).not.toHaveProperty("h3");
+ expect(packageJson.dependencies).not.toHaveProperty("ipx");
+ });
+
+ test("keeps IPX image optimization in the react-router Docker overlay", async () => {
+ await prebuild({
+ assets: false,
+ template: ["react-router", "react-router-docker"],
+ });
+
+ await expect(readFile("app/constants.mjs", "utf8")).resolves.toContain(
+ "return `/_image/w_${props.width},q_${props.quality}${path}`"
+ );
+ await expect(
+ readFile("app/routes/[_image].$.ts", "utf8")
+ ).resolves.toContain("createIPXH3Handler");
+ const packageJson = JSON.parse(await readFile("package.json", "utf8"));
+ expect(packageJson.dependencies).toMatchObject({
+ h3: "^1.15.1",
+ ipx: "^3.0.3",
+ });
+ });
+
+ test("rejects the react-router-docker overlay without its base template", async () => {
+ await expect(
+ prebuild({ assets: false, template: ["react-router-docker"] })
+ ).rejects.toThrow(
+ 'requires "react-router". Use --template react-router --template react-router-docker.'
+ );
});
test("selects ssg templates and skips dynamic routes", async () => {
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index 2c2c29fd1a..a1762b60a8 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -56,7 +56,7 @@ import {
} from "./fs-utils";
import { htmlToJsx } from "./html-to-jsx";
import { compareMedia } from "@webstudio-is/css-engine";
-import { materializeAssetFiles } from "./asset-files";
+import { LOCAL_ASSETS_DIR, materializeAssetFiles } from "./asset-files";
import { formatZodIssues } from "./zod-utils";
import { createFramework as createRemixFramework } from "./framework-remix";
import { createFramework as createReactRouterFramework } from "./framework-react-router";
@@ -259,13 +259,36 @@ export const prebuild = async (options: {
* Template to use for the build in addition to defaults template
**/
template: string[];
+ /** Keep generated-project progress off stdout for JSON and MCP callers. */
+ silent?: boolean;
}) => {
+ const buildRoot = cwd();
+ const feedback = options.silent
+ ? {
+ error: () => undefined,
+ step: () => undefined,
+ }
+ : log;
+ const createProgress = options.silent
+ ? () => ({
+ start: () => undefined,
+ stop: () => undefined,
+ })
+ : spinner;
if (options.template.length === 0) {
- log.error(
+ feedback.error(
`Template is not provided\nPlease check webstudio --help for more details`
);
exit(1);
}
+ if (
+ options.template.includes("react-router-docker") &&
+ options.template.includes("react-router") === false
+ ) {
+ throw new Error(
+ 'Template "react-router-docker" is an overlay and requires "react-router". Use --template react-router --template react-router-docker.'
+ );
+ }
for (const template of options.template) {
// Template is local user template
@@ -274,14 +297,14 @@ export const prebuild = async (options: {
}
if ((await isCliTemplate(template)) === false) {
- log.error(
+ feedback.error(
`Template ${options.template} is not available\nPlease check webstudio --help for more details`
);
exit(1);
}
}
- log.step("Scaffolding the project files");
+ feedback.step("Scaffolding the project files");
const appRoot = "app";
@@ -795,16 +818,17 @@ export const prebuild = async (options: {
}
if (options.assets === true && siteData.assets.length > 0) {
- const downloading = spinner();
+ const downloading = createProgress();
downloading.start("Downloading fonts and images");
await materializeAssetFiles({
assets: siteData.assets,
continueOnError: true,
origin: siteData.origin || "",
- targetAssetsDirectory: join("public", assetBaseUrl),
+ sourceAssetsDirectory: join(buildRoot, LOCAL_ASSETS_DIR),
+ targetAssetsDirectory: join(buildRoot, "public", assetBaseUrl),
});
downloading.stop("Downloaded fonts and images");
}
- log.step("Build finished");
+ feedback.step("Build finished");
};
diff --git a/packages/cli/src/preview-server.test.ts b/packages/cli/src/preview-server.test.ts
index add4cc61a9..7d263f222a 100644
--- a/packages/cli/src/preview-server.test.ts
+++ b/packages/cli/src/preview-server.test.ts
@@ -1,3 +1,6 @@
+import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { expect, test, vi } from "vitest";
import {
createPreviewController,
@@ -5,6 +8,7 @@ import {
getPreviewCommand,
getPreviewStartArgs,
getPreviewUrl,
+ materializePreviewAssets,
runPreviewBuild,
startPreviewServer,
waitForPreviewReady,
@@ -16,7 +20,11 @@ const createDependencies = (
): PreviewServerDependencies => ({
spawn: vi.fn(),
fetch: vi.fn(async () => new Response("", { status: 200 })),
+ cp: vi.fn(async () => undefined),
+ mkdir: vi.fn(async () => undefined),
readdir: vi.fn(async () => []),
+ readFile: vi.fn(async () => "") as never,
+ writeFile: vi.fn(async () => undefined) as never,
sleep: vi.fn(async () => undefined),
platform: "linux",
...overrides,
@@ -91,6 +99,37 @@ test("runs generated project production build", async () => {
});
});
+test("materializes downloaded assets into the production client tree", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "webstudio-preview-assets-"));
+ try {
+ await mkdir(join(directory, "public", "assets"), { recursive: true });
+ await writeFile(
+ join(directory, "public", "assets", "image.png"),
+ "downloaded"
+ );
+
+ await materializePreviewAssets(directory);
+
+ await expect(
+ readFile(
+ join(directory, "build", "client", "assets", "image.png"),
+ "utf8"
+ )
+ ).resolves.toBe("downloaded");
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test("does not fail when the generated preview has no downloaded assets", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "webstudio-preview-assets-"));
+ try {
+ await expect(materializePreviewAssets(directory)).resolves.toBeUndefined();
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
test("runs generated project production build with the windows npm executable", async () => {
const process = createPreviewProcess();
const spawn = vi.fn(() => process);
@@ -132,6 +171,31 @@ test("starts generated project production server with inherited stdio", () => {
});
});
+test("passes explicit external image domains to the preview optimizer", () => {
+ const process = {} as ReturnType<typeof startPreviewServer>["process"];
+ const spawn = vi.fn(() => process);
+
+ startPreviewServer(
+ {
+ host: "127.0.0.1",
+ port: 5173,
+ cwd: "/tmp/preview",
+ imageDomains: ["storage.example.com", "images.example.org"],
+ },
+ createDependencies({ spawn: spawn as never })
+ );
+
+ expect(spawn).toHaveBeenCalledWith(
+ "npm",
+ ["run", "start"],
+ expect.objectContaining({
+ env: expect.objectContaining({
+ DOMAINS: "storage.example.com,images.example.org",
+ }),
+ })
+ );
+});
+
test("starts generated project production server with the windows npm executable", () => {
const process = {} as ReturnType<typeof startPreviewServer>["process"];
const spawn = vi.fn(() => process);
@@ -197,6 +261,37 @@ test("preview controller builds once and reuses a running server", async () => {
});
});
+test("preview controller reuses a matching persisted production build", async () => {
+ const process = createPreviewProcess();
+ const spawn = vi.fn(() => process);
+ const readFile = vi.fn(async () => "cache-key");
+ const writeFile = vi.fn(async () => undefined);
+ const controller = createPreviewController(
+ { host: "127.0.0.1", port: 5173, cwd: "/tmp/preview" },
+ createDependencies({
+ spawn: spawn as never,
+ readFile: readFile as never,
+ writeFile: writeFile as never,
+ })
+ );
+
+ await expect(
+ controller.start({ buildCacheKey: "cache-key" })
+ ).resolves.toMatchObject({ running: true });
+
+ expect(readFile).toHaveBeenCalledWith(
+ "/tmp/preview/.webstudio-preview-build",
+ "utf8"
+ );
+ expect(spawn).toHaveBeenCalledOnce();
+ expect(spawn).toHaveBeenCalledWith(
+ "npm",
+ ["run", "start"],
+ expect.any(Object)
+ );
+ expect(writeFile).not.toHaveBeenCalled();
+});
+
test("preview controller rejects incompatible start options while running", async () => {
const process = createPreviewProcess();
const buildProcess = createPreviewProcess();
@@ -219,6 +314,35 @@ test("preview controller rejects incompatible start options while running", asyn
await expect(controller.start({ cwd: "/tmp/other-preview" })).rejects.toThrow(
"Preview server is already running at http://127.0.0.1:5173/"
);
+ await expect(
+ controller.start({ imageDomains: ["images.example.com"] })
+ ).rejects.toThrow(
+ "Preview server is already running at http://127.0.0.1:5173/"
+ );
+});
+
+test("preview controller passes image domains to the managed server", async () => {
+ const process = createPreviewProcess();
+ const buildProcess = createPreviewProcess();
+ const spawn = vi
+ .fn()
+ .mockReturnValueOnce(buildProcess)
+ .mockReturnValueOnce(process);
+ resolveProcessExit(buildProcess);
+ const controller = createPreviewController(
+ { host: "127.0.0.1", port: 5173 },
+ createDependencies({ spawn: spawn as never })
+ );
+
+ await controller.start({ imageDomains: ["images.example.com"] });
+
+ expect(spawn).toHaveBeenLastCalledWith(
+ "npm",
+ ["run", "start"],
+ expect.objectContaining({
+ env: expect.objectContaining({ DOMAINS: "images.example.com" }),
+ })
+ );
});
test("preview controller stops the running server", async () => {
@@ -370,6 +494,53 @@ test("waits until the latest preview build asset is served", async () => {
expect(sleep).toHaveBeenCalledWith(5);
});
+test("requires the exact generated project even when build assets match", async () => {
+ const fetch = vi.fn(
+ async () =>
+ new Response(
+ '<html data-ws-project="other-project"><link rel="stylesheet" href="/assets/index-new.css" /></html>',
+ { status: 200 }
+ )
+ );
+
+ await expect(
+ waitForPreviewReady(
+ "http://127.0.0.1:5173/",
+ {
+ timeoutMs: 1,
+ intervalMs: 5,
+ requiredAssetNames: ["index-new.css"],
+ requiredProjectId: "expected-project",
+ },
+ createDependencies({ fetch })
+ )
+ ).rejects.toThrow(
+ "Preview server at http://127.0.0.1:5173/ did not serve the expected generated project."
+ );
+});
+
+test("accepts the generated preview with the expected project marker", async () => {
+ const fetch = vi.fn(
+ async () =>
+ new Response(
+ '<html data-ws-project="expected-project"><link rel="stylesheet" href="/assets/index-new.css" /></html>',
+ { status: 200 }
+ )
+ );
+
+ await expect(
+ waitForPreviewReady(
+ "http://127.0.0.1:5173/",
+ {
+ timeoutMs: 1000,
+ requiredAssetNames: ["index-new.css"],
+ requiredProjectId: "expected-project",
+ },
+ createDependencies({ fetch })
+ )
+ ).resolves.toBeUndefined();
+});
+
test("rejects stale preview servers that serve a previous build", async () => {
const fetch = vi.fn(
async () =>
@@ -420,6 +591,40 @@ test("preview controller waits when starting through startAndWait", async () =>
});
});
+test("preview controller derives and verifies the generated project identity", async () => {
+ const process = createPreviewProcess();
+ const buildProcess = createPreviewProcess();
+ const readFile = vi.fn(async () =>
+ JSON.stringify({ build: { projectId: "expected-project" } })
+ );
+ const fetch = vi.fn(
+ async () =>
+ new Response('<html data-ws-project="expected-project"></html>', {
+ status: 200,
+ })
+ );
+ resolveProcessExit(buildProcess);
+ const controller = createPreviewController(
+ { host: "127.0.0.1", port: 5173, cwd: "/tmp/preview" },
+ createDependencies({
+ spawn: vi
+ .fn()
+ .mockReturnValueOnce(buildProcess)
+ .mockReturnValueOnce(process) as never,
+ readFile: readFile as never,
+ fetch,
+ })
+ );
+
+ await expect(controller.startAndWait()).resolves.toMatchObject({
+ running: true,
+ });
+ expect(readFile).toHaveBeenCalledWith(
+ "/tmp/preview/.webstudio/data.json",
+ "utf8"
+ );
+});
+
test("preview controller fails immediately when the dev server exits before readiness", async () => {
const process = createPreviewProcess({
exitCode: 1,
diff --git a/packages/cli/src/preview-server.ts b/packages/cli/src/preview-server.ts
index ccfc806b91..90a0c4dcdb 100644
--- a/packages/cli/src/preview-server.ts
+++ b/packages/cli/src/preview-server.ts
@@ -3,13 +3,14 @@ import {
type ChildProcess,
type StdioOptions,
} from "node:child_process";
-import { readdir } from "node:fs/promises";
+import { cp, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
import { delimiter, dirname, join, parse } from "node:path";
export type PreviewServerOptions = {
host: string;
port: number;
cwd?: string;
+ imageDomains?: string[];
};
export type PreviewServerResult = {
@@ -20,7 +21,11 @@ export type PreviewServerResult = {
export type PreviewServerDependencies = {
spawn: typeof spawn;
fetch: typeof fetch;
+ cp: typeof cp;
+ mkdir: typeof mkdir;
readdir: typeof readdir;
+ readFile: typeof readFile;
+ writeFile: typeof writeFile;
sleep: (ms: number) => Promise<void>;
platform: typeof process.platform;
};
@@ -28,7 +33,11 @@ export type PreviewServerDependencies = {
export const defaultPreviewServerDependencies: PreviewServerDependencies = {
spawn,
fetch,
+ cp,
+ mkdir,
readdir,
+ readFile,
+ writeFile,
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
platform: process.platform,
};
@@ -92,21 +101,62 @@ export const getPreviewCommand = (
export const runPreviewBuild = async (
dependencies = defaultPreviewServerDependencies,
- cwd?: string
+ cwd?: string,
+ stdio: StdioOptions = "inherit"
) => {
const buildProcess = dependencies.spawn(
getPreviewCommand(dependencies.platform),
getPreviewBuildArgs(),
{
cwd,
- stdio: "inherit",
+ stdio,
env: getPreviewEnv(cwd, {
...processEnv(),
NODE_ENV: "production",
}),
}
);
- await waitForPreviewExit(buildProcess);
+ let output = "";
+ const appendOutput = (chunk: unknown) => {
+ output = `${output}${String(chunk)}`.slice(-4000);
+ };
+ buildProcess.stdout?.on("data", appendOutput);
+ buildProcess.stderr?.on("data", appendOutput);
+ try {
+ await waitForPreviewExit(buildProcess);
+ await materializePreviewAssets(cwd, dependencies);
+ } catch (error) {
+ if (output.length === 0) {
+ throw error;
+ }
+ throw new Error(
+ `${error instanceof Error ? error.message : String(error)}\n\nPreview build output:\n${output}`,
+ { cause: error }
+ );
+ }
+};
+
+export const materializePreviewAssets = async (
+ cwd: string | undefined,
+ dependencies = defaultPreviewServerDependencies
+) => {
+ if (cwd === undefined) {
+ return;
+ }
+ const source = join(cwd, "public", "assets");
+ const destination = join(cwd, "build", "client", "assets");
+ try {
+ await dependencies.mkdir(destination, { recursive: true });
+ await dependencies.cp(source, destination, {
+ recursive: true,
+ force: true,
+ });
+ } catch (error) {
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
+ return;
+ }
+ throw error;
+ }
};
export const startPreviewServer = (
@@ -123,6 +173,9 @@ export const startPreviewServer = (
...processEnv(),
HOST: options.host,
PORT: String(options.port),
+ ...(options.imageDomains === undefined
+ ? {}
+ : { DOMAINS: options.imageDomains.join(",") }),
NODE_ENV: "production",
}),
}
@@ -151,6 +204,49 @@ export type PreviewControllerResult = {
type PreviewControllerStartOptions = Partial<PreviewServerOptions> & {
restart?: boolean;
+ buildCacheKey?: string;
+};
+
+const areStringArraysEqual = (
+ left: string[] | undefined,
+ right: string[] | undefined
+) =>
+ left === right ||
+ (left !== undefined &&
+ right !== undefined &&
+ left.length === right.length &&
+ left.every((value, index) => value === right[index]));
+
+export const previewBuildCacheMarker = ".webstudio-preview-build";
+
+const getPreviewProjectId = async (
+ cwd: string | undefined,
+ dependencies = defaultPreviewServerDependencies
+) => {
+ if (cwd === undefined) {
+ return undefined;
+ }
+ try {
+ const data = JSON.parse(
+ await dependencies.readFile(join(cwd, ".webstudio", "data.json"), "utf8")
+ ) as { build?: { projectId?: unknown } };
+ if (typeof data.build?.projectId !== "string") {
+ throw new Error("projectId is missing");
+ }
+ return data.build.projectId;
+ } catch (error) {
+ throw new Error(
+ `Could not identify the generated preview project in ${join(cwd, ".webstudio", "data.json")}.`,
+ { cause: error }
+ );
+ }
+};
+
+const hasProjectMarker = (html: string, projectId: string) => {
+ const escapedProjectId = projectId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ return new RegExp(
+ `data-ws-project\\s*=\\s*(["'])${escapedProjectId}\\1`
+ ).test(html);
};
export const waitForPreviewReady = async (
@@ -160,16 +256,19 @@ export const waitForPreviewReady = async (
intervalMs = 250,
isRunning,
requiredAssetNames = [],
+ requiredProjectId,
}: {
timeoutMs?: number;
intervalMs?: number;
isRunning?: () => boolean;
requiredAssetNames?: string[];
+ requiredProjectId?: string;
} = {},
dependencies = defaultPreviewServerDependencies
) => {
const deadline = Date.now() + timeoutMs;
let sawStaleServer = false;
+ let sawUnexpectedProject = false;
while (Date.now() <= deadline) {
if (isRunning?.() === false) {
throw new Error(
@@ -186,20 +285,35 @@ export const waitForPreviewReady = async (
signal: AbortSignal.timeout(attemptTimeoutMs),
});
if (response.status < 500) {
- if (requiredAssetNames.length === 0) {
+ if (
+ requiredAssetNames.length === 0 &&
+ requiredProjectId === undefined
+ ) {
return;
}
const html = await response.text();
- if (requiredAssetNames.some((name) => html.includes(name))) {
+ const servesExpectedProject =
+ requiredProjectId === undefined ||
+ hasProjectMarker(html, requiredProjectId);
+ const servesLatestAssets =
+ requiredAssetNames.length === 0 ||
+ requiredAssetNames.some((name) => html.includes(name));
+ if (servesExpectedProject && servesLatestAssets) {
return;
}
- sawStaleServer = true;
+ sawUnexpectedProject ||= servesExpectedProject === false;
+ sawStaleServer ||= servesLatestAssets === false;
}
} catch {
// Server is still starting.
}
await dependencies.sleep(intervalMs);
}
+ if (sawUnexpectedProject) {
+ throw new Error(
+ `Preview server at ${url} did not serve the expected generated project. Stop the existing preview server on this port, then retry.`
+ );
+ }
if (sawStaleServer) {
throw new Error(
`Preview server at ${url} did not serve the latest build assets. Stop the existing preview server on this port, then retry.`
@@ -289,13 +403,20 @@ export const createPreviewController = (
host: options.host ?? (running ? currentOptions.host : defaults.host),
port: options.port ?? (running ? currentOptions.port : defaults.port),
cwd: options.cwd ?? (running ? currentCwd : defaults.cwd),
+ imageDomains:
+ options.imageDomains ??
+ (running ? currentOptions.imageDomains : defaults.imageDomains),
};
if (running) {
if (options.restart !== true) {
if (
nextOptions.host !== currentOptions.host ||
nextOptions.port !== currentOptions.port ||
- nextOptions.cwd !== currentCwd
+ nextOptions.cwd !== currentCwd ||
+ areStringArraysEqual(
+ nextOptions.imageDomains,
+ currentOptions.imageDomains
+ ) === false
) {
throw new Error(
`Preview server is already running at ${getPreviewUrl(currentOptions)}. Stop it before starting a different preview server.`
@@ -307,7 +428,28 @@ export const createPreviewController = (
}
currentOptions = nextOptions;
currentCwd = nextOptions.cwd;
- await runPreviewBuild(dependencies, currentCwd);
+ const cachedBuildKey =
+ options.buildCacheKey === undefined || currentCwd === undefined
+ ? undefined
+ : await dependencies
+ .readFile(join(currentCwd, previewBuildCacheMarker), "utf8")
+ .catch(() => undefined);
+ if (
+ options.buildCacheKey === undefined ||
+ cachedBuildKey !== options.buildCacheKey
+ ) {
+ await runPreviewBuild(dependencies, currentCwd, [
+ "ignore",
+ "pipe",
+ "pipe",
+ ]);
+ if (options.buildCacheKey !== undefined && currentCwd !== undefined) {
+ await dependencies.writeFile(
+ join(currentCwd, previewBuildCacheMarker),
+ options.buildCacheKey
+ );
+ }
+ }
serverOutput = "";
server = startPreviewServer(
{
@@ -328,6 +470,11 @@ export const createPreviewController = (
async startAndWait(
options: PreviewControllerStartOptions = {}
): Promise<PreviewControllerResult> {
+ const nextCwd = options.cwd ?? (isRunning() ? currentCwd : defaults.cwd);
+ const requiredProjectId = await getPreviewProjectId(
+ nextCwd,
+ dependencies
+ );
const result = await start(options);
const requiredAssetNames = await getPreviewCssAssetNames(
currentCwd,
@@ -336,7 +483,7 @@ export const createPreviewController = (
try {
await waitForPreviewReady(
result.url,
- { isRunning, requiredAssetNames },
+ { isRunning, requiredAssetNames, requiredProjectId },
dependencies
);
} catch (error) {
diff --git a/packages/cli/src/project-session-api.test.ts b/packages/cli/src/project-session-api.test.ts
index 59d25a5956..2aab261ed1 100644
--- a/packages/cli/src/project-session-api.test.ts
+++ b/packages/cli/src/project-session-api.test.ts
@@ -165,6 +165,13 @@ describe("project session api adapter", () => {
authToken: "token",
},
createProjectSession,
+ getServerApiContract: async () => ({
+ clientVersion: "public-api:client",
+ serverVersion: "public-api:server",
+ supportedOperationIds: new Set(["auth.me"]),
+ missingServerOperationIds: [],
+ negotiated: true,
+ }),
});
expect(session.executeServerOperation).toHaveBeenCalledWith(
@@ -178,6 +185,38 @@ describe("project session api adapter", () => {
expect(result.result).toEqual({ actor: "token" });
});
+ test("rejects unsupported server-only commands before dispatch", async () => {
+ const session = {
+ initialize: vi.fn(async () => undefined),
+ read: vi.fn(),
+ mutate: vi.fn(),
+ executeServerOperation: vi.fn(),
+ refresh: vi.fn(),
+ };
+
+ await expect(
+ executeProjectSessionApiOperation({
+ command: "whoami",
+ input: {},
+ connection: {
+ projectId: "project-1",
+ origin: "https://example.com",
+ authToken: "token",
+ },
+ createProjectSession: vi.fn(
+ () => session
+ ) as unknown as CreateProjectSession,
+ getServerApiContract: async () => ({
+ clientVersion: "public-api:client",
+ supportedOperationIds: new Set(),
+ missingServerOperationIds: ["auth.me"],
+ negotiated: false,
+ }),
+ })
+ ).rejects.toThrow('does not advertise server operation "auth.me"');
+ expect(session.executeServerOperation).not.toHaveBeenCalled();
+ });
+
test("refreshes local namespaces before local-capable commands when requested", async () => {
const session = {
initialize: vi.fn(async () => undefined),
@@ -214,7 +253,7 @@ describe("project session api adapter", () => {
refresh: true,
});
- expect(session.refresh).toHaveBeenCalledWith(["pages", "projectSettings"]);
+ expect(session.refresh).toHaveBeenCalledWith(["pages"]);
});
test("explains dry-run is only for local-capable mutations", async () => {
diff --git a/packages/cli/src/project-session-api.ts b/packages/cli/src/project-session-api.ts
index 458fdf6adc..3c8facb106 100644
--- a/packages/cli/src/project-session-api.ts
+++ b/packages/cli/src/project-session-api.ts
@@ -1,5 +1,6 @@
import {
getPublicApiOperation,
+ publicApiOperationRequiresServerSupport,
type PublicApiCommand,
} from "@webstudio-is/protocol";
import type { RuntimeOperationId } from "@webstudio-is/project-build/contracts/builder-runtime";
@@ -8,7 +9,11 @@ import {
serializeProjectSessionMeta,
type ProjectSessionEnvelope,
} from "@webstudio-is/project-build/project-session";
-import { createCliProjectSession } from "./project-session";
+import {
+ assertCliServerOperationSupported,
+ createCliProjectSession,
+ getCliServerApiContract,
+} from "./project-session";
export type ProjectSessionApiConnection = {
projectId: string;
@@ -69,6 +74,7 @@ export const executeProjectSessionApiOperation = async ({
input,
connection,
createProjectSession = createCliProjectSession,
+ getServerApiContract = getCliServerApiContract,
dryRun = false,
refresh = false,
}: {
@@ -76,6 +82,7 @@ export const executeProjectSessionApiOperation = async ({
input: unknown;
connection: ProjectSessionApiConnection;
createProjectSession?: CreateProjectSession;
+ getServerApiContract?: typeof getCliServerApiContract;
dryRun?: boolean;
refresh?: boolean;
}) => {
@@ -101,6 +108,13 @@ export const executeProjectSessionApiOperation = async ({
])
);
}
+ if (
+ runtimeOperationId === undefined ||
+ publicApiOperationRequiresServerSupport(operation)
+ ) {
+ const contract = await getServerApiContract(connection);
+ assertCliServerOperationSupported(operation.id, contract);
+ }
const envelope =
runtimeOperationId === undefined
? await session.executeServerOperation(
diff --git a/packages/cli/src/project-session.test.ts b/packages/cli/src/project-session.test.ts
index 8df32bf528..502bed2805 100644
--- a/packages/cli/src/project-session.test.ts
+++ b/packages/cli/src/project-session.test.ts
@@ -8,6 +8,8 @@ import {
createLocalProjectBundleFromSessionSnapshot,
createCliProjectSessionStorage,
createCliProjectSessionTransport,
+ getCliServerApiContract,
+ getSupportedPublicApiOperations,
} from "./project-session";
const temporaryDirectories: string[] = [];
@@ -125,6 +127,58 @@ describe("cli project session storage", () => {
});
});
+describe("CLI/server operation contract", () => {
+ const connection = {
+ projectId: "project-1",
+ origin: "https://example.com",
+ authToken: "token",
+ };
+
+ test("uses the server operation catalog to hide unsupported server-only operations", async () => {
+ const contract = await getCliServerApiContract(connection, async () => ({
+ apiContract: {
+ version: "public-api:server",
+ operationIds: ["auth.me"],
+ },
+ }));
+
+ expect(contract).toMatchObject({
+ serverVersion: "public-api:server",
+ negotiated: true,
+ });
+ expect(contract.supportedOperationIds.has("auth.me")).toBe(true);
+ expect(
+ getSupportedPublicApiOperations(contract).some(
+ (operation) => operation.id === "auth.me"
+ )
+ ).toBe(true);
+ expect(
+ getSupportedPublicApiOperations(contract).some(
+ (operation) => operation.serverOnly && operation.id !== "auth.me"
+ )
+ ).toBe(false);
+ });
+
+ test("keeps established local operations on legacy servers but hides new routed operations", async () => {
+ const contract = await getCliServerApiContract(connection, async () => ({
+ canView: true,
+ }));
+ const operations = getSupportedPublicApiOperations(contract);
+
+ expect(contract.negotiated).toBe(false);
+ expect(
+ operations.some((operation) => operation.command === "list-pages")
+ ).toBe(true);
+ expect(
+ operations.some((operation) => operation.command === "insert-component")
+ ).toBe(false);
+ expect(
+ operations.some((operation) => operation.command === "insert-fragment")
+ ).toBe(false);
+ expect(operations.some((operation) => operation.serverOnly)).toBe(false);
+ });
+});
+
test("creates preview bundle from project session snapshot", () => {
const marketplaceProduct = {
category: "pageTemplates" as const,
@@ -315,6 +369,85 @@ describe("cli project session transport", () => {
});
});
+ test("falls back to legacy page settings when the server rejects projectSettings", async () => {
+ const includes: unknown[] = [];
+ const transport = createCliProjectSessionTransport({
+ connection: {
+ projectId: "project-1",
+ origin: "https://example.com",
+ authToken: "token",
+ },
+ getBuildSnapshot: async (input) => {
+ includes.push(input.include);
+ if (input.include?.includes("projectSettings")) {
+ throw new Error(
+ 'invalid_enum_value: received "projectSettings", expected one of pages|folders'
+ );
+ }
+ return {
+ projectId: "project-1",
+ buildId: "build-1",
+ version: 1,
+ pages: [
+ {
+ id: "home",
+ name: "Home",
+ path: "",
+ title: "Home",
+ rootInstanceId: "body",
+ meta: {},
+ },
+ ],
+ folders: [
+ {
+ id: "root",
+ name: "Root",
+ slug: "",
+ children: ["home"],
+ },
+ ],
+ homePageId: "home",
+ rootFolderId: "root",
+ meta: { siteName: "Legacy Acme" },
+ compiler: { atomicStyles: true },
+ };
+ },
+ });
+
+ const snapshot = await transport.fetchNamespaces({
+ projectId: "project-1",
+ namespaces: ["projectSettings"],
+ });
+
+ expect(includes).toEqual([["projectSettings"], ["pages", "folders"]]);
+ expect(snapshot.state.projectSettings).toEqual({
+ meta: { siteName: "Legacy Acme" },
+ compiler: { atomicStyles: true },
+ });
+ });
+
+ test("does not hide unrelated snapshot errors", async () => {
+ const getBuildSnapshot = vi.fn(async () => {
+ throw new Error("Network unavailable");
+ });
+ const transport = createCliProjectSessionTransport({
+ connection: {
+ projectId: "project-1",
+ origin: "https://example.com",
+ authToken: "token",
+ },
+ getBuildSnapshot,
+ });
+
+ await expect(
+ transport.fetchNamespaces({
+ projectId: "project-1",
+ namespaces: ["projectSettings"],
+ })
+ ).rejects.toThrow("Network unavailable");
+ expect(getBuildSnapshot).toHaveBeenCalledTimes(1);
+ });
+
test("adapts injected permission reader to project session transport", async () => {
const transport = createCliProjectSessionTransport({
connection: {
diff --git a/packages/cli/src/project-session.ts b/packages/cli/src/project-session.ts
index bee65c8c57..b1033e66e6 100644
--- a/packages/cli/src/project-session.ts
+++ b/packages/cli/src/project-session.ts
@@ -8,6 +8,8 @@ import {
import * as httpClient from "@webstudio-is/http-client";
import {
bundleVersion,
+ publicApiContractVersion,
+ publicApiOperationRequiresServerSupport,
publicApiOperations,
type PublishedProjectBundle,
} from "@webstudio-is/protocol";
@@ -44,6 +46,81 @@ type ApiConnection = {
headers?: Record<string, string | undefined>;
};
+export type CliServerApiContract = {
+ clientVersion: string;
+ serverVersion?: string;
+ supportedOperationIds: ReadonlySet<string>;
+ missingServerOperationIds: readonly string[];
+ negotiated: boolean;
+};
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && Array.isArray(value) === false;
+
+export const getCliServerApiContract = async (
+ connection: ApiConnection,
+ getProjectPermissions = httpClient.getProjectPermissions
+): Promise<CliServerApiContract> => {
+ const permissions = (await getProjectPermissions(connection)) as unknown;
+ const apiContract = isRecord(permissions)
+ ? permissions.apiContract
+ : undefined;
+ const serverVersion =
+ isRecord(apiContract) && typeof apiContract.version === "string"
+ ? apiContract.version
+ : undefined;
+ const operationIds =
+ isRecord(apiContract) && Array.isArray(apiContract.operationIds)
+ ? apiContract.operationIds.filter(
+ (operationId): operationId is string =>
+ typeof operationId === "string"
+ )
+ : [];
+ const supportedOperationIds = new Set(operationIds);
+ const missingServerOperationIds = publicApiOperations.flatMap((operation) =>
+ publicApiOperationRequiresServerSupport(operation) &&
+ supportedOperationIds.has(operation.id) === false
+ ? [operation.id]
+ : []
+ );
+ return {
+ clientVersion: publicApiContractVersion,
+ serverVersion,
+ supportedOperationIds,
+ missingServerOperationIds,
+ negotiated: serverVersion !== undefined,
+ };
+};
+
+export const getSupportedPublicApiOperations = (
+ contract: CliServerApiContract
+) =>
+ publicApiOperations.filter((operation) => {
+ if (contract.negotiated === false) {
+ return publicApiOperationRequiresServerSupport(operation) === false;
+ }
+ return (
+ publicApiOperationRequiresServerSupport(operation) === false ||
+ contract.supportedOperationIds.has(operation.id)
+ );
+ });
+
+export const assertCliServerOperationSupported = (
+ operationId: string,
+ contract: CliServerApiContract
+) => {
+ if (contract.supportedOperationIds.has(operationId)) {
+ return;
+ }
+ const serverVersion = contract.serverVersion ?? "unavailable (legacy server)";
+ throw Object.assign(
+ new Error(
+ `The configured Webstudio API does not advertise server operation "${operationId}". CLI contract: ${contract.clientVersion}. Server contract: ${serverVersion}. Run this command with the latest CLI once; if it still appears, retry after the Webstudio API deployment is updated.`
+ ),
+ { code: "API_CONTRACT_MISMATCH" }
+ );
+};
+
type PublicBuildSnapshot = Omit<
BuilderBuildDataSnapshot,
"dataSources" | "pages"
@@ -98,6 +175,20 @@ const toPublicApiInclude = (namespaces: readonly BuilderNamespace[]) => [
),
];
+const isUnsupportedProjectSettingsIncludeError = (error: unknown) => {
+ const message = error instanceof Error ? error.message : String(error);
+ return (
+ message.includes("invalid_enum_value") &&
+ message.includes('received "projectSettings"')
+ );
+};
+
+const getLegacyPublicApiInclude = (namespaces: readonly BuilderNamespace[]) =>
+ toPublicApiInclude([
+ ...namespaces.filter((namespace) => namespace !== "projectSettings"),
+ "pages",
+ ]);
+
const toPages = (snapshot: PublicBuildSnapshot) => {
if (snapshot.pages === undefined) {
return undefined;
@@ -247,12 +338,25 @@ export const createCliProjectSessionTransport = ({
return createCliProjectSessionCompatibility(connection);
},
async fetchNamespaces({ namespaces }) {
- const snapshot = (await withMappedRemoteError(() =>
- getBuildSnapshot({
- ...connection,
- include: toPublicApiInclude(namespaces),
- })
- )) as PublicBuildSnapshot;
+ const fetchSnapshot = (include: string[]) =>
+ withMappedRemoteError(() =>
+ getBuildSnapshot({
+ ...connection,
+ include,
+ })
+ ) as Promise<PublicBuildSnapshot>;
+ let snapshot: PublicBuildSnapshot;
+ try {
+ snapshot = await fetchSnapshot(toPublicApiInclude(namespaces));
+ } catch (error) {
+ if (
+ namespaces.includes("projectSettings") === false ||
+ isUnsupportedProjectSettingsIncludeError(error) === false
+ ) {
+ throw error;
+ }
+ snapshot = await fetchSnapshot(getLegacyPublicApiInclude(namespaces));
+ }
return toRemoteSnapshot(snapshot);
},
async commitPatch({ baseVersion, transactions }) {
diff --git a/packages/cli/src/screenshot-browser-cdp.test.ts b/packages/cli/src/screenshot-browser-cdp.test.ts
index 0948fbfdcb..8472e360cf 100644
--- a/packages/cli/src/screenshot-browser-cdp.test.ts
+++ b/packages/cli/src/screenshot-browser-cdp.test.ts
@@ -2,6 +2,7 @@ import { Buffer } from "node:buffer";
import { expect, test, vi } from "vitest";
import {
captureBrowserScreenshot,
+ createBrowserScreenshotSession,
type BrowserScreenshotDependencies,
} from "./screenshot-browser-cdp";
@@ -37,8 +38,27 @@ class FakeWebSocket {
string,
Array<(event: { data?: string }) => void>
>();
+ readonly status: number;
+ readonly finalUrl?: string;
+ readonly subframeStatus?: number;
+ readonly readinessWidths?: number[];
+ readonly lifecycleFrames: string[];
+ imageInspectionFinished = false;
+ screenshotStartedBeforeImageInspectionFinished = false;
+ private currentUrl = "about:blank";
- constructor() {
+ constructor(
+ status = 200,
+ finalUrl?: string,
+ subframeStatus?: number,
+ readinessWidths?: number[],
+ lifecycleFrames = ["main"]
+ ) {
+ this.status = status;
+ this.finalUrl = finalUrl;
+ this.subframeStatus = subframeStatus;
+ this.readinessWidths = readinessWidths;
+ this.lifecycleFrames = lifecycleFrames;
setTimeout(() => this.emit("open"), 0);
}
@@ -66,6 +86,55 @@ class FakeWebSocket {
data: JSON.stringify({ id: message.id, result }),
});
};
+ if (
+ message.method === "Runtime.evaluate" &&
+ typeof message.params?.expression === "string" &&
+ message.params.expression.includes("generatedSiteRootPresent")
+ ) {
+ setTimeout(
+ () =>
+ respond({
+ result: {
+ value: {
+ documentReadyState: "complete",
+ generatedSiteRootPresent: true,
+ width: this.readinessWidths?.shift() ?? 813,
+ height: 2346,
+ },
+ },
+ }),
+ 0
+ );
+ return;
+ }
+ if (
+ message.method === "Runtime.evaluate" &&
+ message.params?.expression === "window.location.href"
+ ) {
+ setTimeout(() => respond({ result: { value: this.currentUrl } }), 0);
+ return;
+ }
+ if (
+ message.method === "Runtime.evaluate" &&
+ typeof message.params?.expression === "string" &&
+ message.params.expression.includes("document.documentElement.scrollWidth")
+ ) {
+ setTimeout(
+ () =>
+ respond({
+ result: {
+ value: {
+ scrollWidth: 813,
+ scrollHeight: 2346,
+ horizontalOverflowSuppressed: true,
+ documentType: "text/html",
+ },
+ },
+ }),
+ 0
+ );
+ return;
+ }
if (
message.method === "Runtime.evaluate" &&
typeof message.params?.expression === "string" &&
@@ -115,29 +184,33 @@ class FakeWebSocket {
typeof message.params?.expression === "string" &&
message.params.expression.includes("Array.from(document.images")
) {
- setTimeout(
- () =>
- respond({
- result: {
- value: [
- {
- instanceId: "hero-image",
- loading: "eager",
- complete: true,
- naturalWidth: 2400,
- naturalHeight: 1600,
- renderedWidth: 600,
- renderedHeight: 400,
- top: 1000,
- },
- ],
- },
- }),
- 0
- );
+ setTimeout(() => {
+ this.imageInspectionFinished = true;
+ respond({
+ result: {
+ value: [
+ {
+ instanceId: "hero-image",
+ sourcePathname: "/assets/hero.png",
+ loading: "eager",
+ complete: true,
+ naturalWidth: 2400,
+ naturalHeight: 1600,
+ selectedSourceWidth: 1200,
+ selectedSourceHeight: 800,
+ renderedWidth: 600,
+ renderedHeight: 400,
+ top: 1000,
+ },
+ ],
+ },
+ });
+ }, 0);
return;
}
if (message.method === "Page.captureScreenshot") {
+ this.screenshotStartedBeforeImageInspectionFinished =
+ this.imageInspectionFinished === false;
setTimeout(
() =>
respond({
@@ -167,14 +240,71 @@ class FakeWebSocket {
return;
}
setTimeout(() => {
- respond();
+ respond(
+ message.method === "Page.navigate"
+ ? { frameId: "main", loaderId: "main-loader" }
+ : {}
+ );
if (message.method === "Page.navigate") {
+ const requestedUrl = String(message.params?.url);
+ this.currentUrl = this.finalUrl ?? requestedUrl;
+ if (this.currentUrl !== requestedUrl) {
+ this.emit("message", {
+ data: JSON.stringify({
+ method: "Network.requestWillBeSent",
+ params: {
+ type: "Document",
+ frameId: "main",
+ redirectResponse: { url: requestedUrl },
+ },
+ }),
+ });
+ }
this.emit("message", {
data: JSON.stringify({
- method: "Page.lifecycleEvent",
- params: { name: "networkIdle" },
+ method: "Network.responseReceived",
+ params: {
+ type: "Document",
+ frameId: "main",
+ response: {
+ url: this.currentUrl,
+ status: this.status,
+ statusText: this.status === 404 ? "Not Found" : "OK",
+ mimeType: "text/html",
+ },
+ },
}),
});
+ if (this.subframeStatus !== undefined) {
+ this.emit("message", {
+ data: JSON.stringify({
+ method: "Network.responseReceived",
+ params: {
+ type: "Document",
+ frameId: "child",
+ response: {
+ url: "https://embed.example/frame",
+ status: this.subframeStatus,
+ statusText: "Forbidden",
+ mimeType: "text/html",
+ },
+ },
+ }),
+ });
+ }
+ for (const frameId of this.lifecycleFrames) {
+ this.emit("message", {
+ data: JSON.stringify({
+ method: "Page.lifecycleEvent",
+ params: {
+ name: "networkIdle",
+ frameId,
+ loaderId:
+ frameId === "main" ? "main-loader" : `${frameId}-loader`,
+ },
+ }),
+ });
+ }
}
}, 0);
};
@@ -192,6 +322,29 @@ class HangingWebSocket extends FakeWebSocket {
};
}
+class ClosingWebSocket extends FakeWebSocket {
+ send = () => {
+ setTimeout(() => this.emit("close"), 0);
+ };
+}
+
+class CrashingWebSocket extends FakeWebSocket {
+ readonly #browserProcess: FakeBrowserProcess;
+ #crashed = false;
+
+ constructor(browserProcess: FakeBrowserProcess) {
+ super();
+ this.#browserProcess = browserProcess;
+ }
+
+ send = () => {
+ if (this.#crashed === false) {
+ this.#crashed = true;
+ setTimeout(() => this.#browserProcess.emit("exit", 1), 0);
+ }
+ };
+}
+
class NavigationErrorWebSocket extends FakeWebSocket {
send = (data: string) => {
const message = JSON.parse(data) as {
@@ -236,6 +389,7 @@ const createDependencies = ({
json: async () =>
url.includes("/json/new?")
? {
+ id: "target-1",
type: "page",
webSocketDebuggerUrl: "ws://127.0.0.1:9222/page/created",
}
@@ -283,6 +437,9 @@ test("captures through DevTools with lifecycle and selector waits", async () =>
"/usr/bin/chromium",
expect.arrayContaining([
"--headless=new",
+ "--disable-background-timer-throttling",
+ "--disable-backgrounding-occluded-windows",
+ "--disable-renderer-backgrounding",
"--remote-debugging-port=0",
"--user-data-dir=/tmp/webstudio-browser-test",
"--window-size=800,600",
@@ -308,6 +465,15 @@ test("captures through DevTools with lifecycle and selector waits", async () =>
"Page.captureScreenshot",
])
);
+ expect(
+ socket.sentMessages.some(
+ (message) =>
+ message.method === "Runtime.evaluate" &&
+ String(message.params?.expression).includes(
+ 'document.documentElement.hasAttribute("data-ws-project")'
+ )
+ )
+ ).toBe(true);
expect(dependencies.writeFile).toHaveBeenCalledWith(
"/tmp/current.png",
Buffer.from("fake-png")
@@ -320,6 +486,266 @@ test("captures through DevTools with lifecycle and selector waits", async () =>
});
});
+test("ignores lifecycle readiness from child frames", async () => {
+ const socket = new FakeWebSocket(200, undefined, undefined, undefined, [
+ "child",
+ ]);
+
+ await expect(
+ captureBrowserScreenshot(
+ {
+ url: "https://example.com",
+ output: "/tmp/current.png",
+ width: 800,
+ height: 600,
+ browserPath: "/usr/bin/chromium",
+ waitUntil: "networkidle",
+ waitForTimeout: 0,
+ timeout: 10,
+ },
+ createDependencies({ socket })
+ )
+ ).rejects.toThrow("Page did not reach networkidle");
+});
+
+test("reuses one browser process across screenshot captures", async () => {
+ const browserProcess = new FakeBrowserProcess();
+ const dependencies = createDependencies({ browserProcess });
+ vi.mocked(dependencies.createWebSocket)
+ .mockImplementationOnce(() => new FakeWebSocket() as unknown as WebSocket)
+ .mockImplementationOnce(() => new FakeWebSocket() as unknown as WebSocket);
+ const session = await createBrowserScreenshotSession(
+ {
+ url: "https://example.com/one",
+ output: "/tmp/one.png",
+ width: 800,
+ height: 600,
+ browserPath: "/usr/bin/chromium",
+ waitUntil: "networkidle",
+ waitForTimeout: 0,
+ timeout: 1000,
+ },
+ dependencies
+ );
+
+ await session.capture({
+ url: "https://example.com/one",
+ output: "/tmp/one.png",
+ width: 800,
+ height: 600,
+ browserPath: "/usr/bin/chromium",
+ waitUntil: "networkidle",
+ waitForTimeout: 0,
+ timeout: 1000,
+ });
+ await session.capture({
+ url: "https://example.com/two",
+ output: "/tmp/two.png",
+ width: 390,
+ height: 844,
+ browserPath: "/usr/bin/chromium",
+ waitUntil: "networkidle",
+ waitForTimeout: 0,
+ timeout: 1000,
+ });
+
+ expect(dependencies.spawnBrowser).toHaveBeenCalledOnce();
+ expect(dependencies.createWebSocket).toHaveBeenCalledTimes(2);
+ expect(dependencies.fetch).toHaveBeenCalledWith(
+ "http://127.0.0.1:9222/json/close/target-1"
+ );
+ expect(browserProcess.kill).not.toHaveBeenCalled();
+
+ await session.close();
+
+ expect(browserProcess.kill).toHaveBeenCalledOnce();
+});
+
+test("navigates once while resizing one page through multiple viewports", async () => {
+ const socket = new FakeWebSocket();
+ const dependencies = createDependencies({ socket });
+ const baseOptions = {
+ url: "https://example.com/responsive",
+ browserPath: "/usr/bin/chromium",
+ includeImageMetrics: true,
+ waitUntil: "networkidle" as const,
+ waitForTimeout: 0,
+ timeout: 1000,
+ };
+ const session = await createBrowserScreenshotSession(
+ {
+ ...baseOptions,
+ output: "/tmp/mobile.png",
+ width: 375,
+ height: 812,
+ },
+ dependencies
+ );
+
+ const layouts = await session.capturePage([
+ {
+ ...baseOptions,
+ output: "/tmp/mobile.png",
+ width: 375,
+ height: 812,
+ },
+ {
+ ...baseOptions,
+ output: "/tmp/desktop.png",
+ width: 1440,
+ height: 900,
+ },
+ ]);
+
+ expect(layouts).toHaveLength(2);
+ expect(layouts).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ timings: expect.objectContaining({ wallMs: expect.any(Number) }),
+ }),
+ ])
+ );
+ expect(
+ socket.sentMessages.filter((message) => message.method === "Page.navigate")
+ ).toHaveLength(1);
+ expect(
+ socket.sentMessages
+ .filter(
+ (message) => message.method === "Emulation.setDeviceMetricsOverride"
+ )
+ .map((message) => message.params?.width)
+ ).toEqual([375, 1440]);
+ expect(dependencies.createWebSocket).toHaveBeenCalledOnce();
+ expect(dependencies.writeFile).toHaveBeenCalledTimes(2);
+ expect(
+ socket.sentMessages.some(
+ (message) =>
+ message.method === "Runtime.evaluate" &&
+ String(message.params?.expression).includes(
+ "__webstudioImageDimensionCache"
+ )
+ )
+ ).toBe(true);
+
+ await session.close();
+});
+
+test("reuses one target while navigating and resizing multiple pages", async () => {
+ const socket = new FakeWebSocket();
+ const dependencies = createDependencies({ socket });
+ const baseOptions = {
+ browserPath: "/usr/bin/chromium",
+ waitUntil: "networkidle" as const,
+ waitForTimeout: 0,
+ timeout: 1000,
+ };
+ const session = await createBrowserScreenshotSession(
+ {
+ ...baseOptions,
+ url: "https://example.com/one",
+ output: "/tmp/one-mobile.webp",
+ width: 375,
+ height: 812,
+ },
+ dependencies
+ );
+
+ const layouts = await session.capturePage([
+ {
+ ...baseOptions,
+ url: "https://example.com/one",
+ output: "/tmp/one-mobile.webp",
+ width: 375,
+ height: 812,
+ },
+ {
+ ...baseOptions,
+ url: "https://example.com/one",
+ output: "/tmp/one-desktop.webp",
+ width: 1440,
+ height: 900,
+ },
+ {
+ ...baseOptions,
+ url: "https://example.com/two",
+ output: "/tmp/two-mobile.webp",
+ width: 375,
+ height: 812,
+ },
+ {
+ ...baseOptions,
+ url: "https://example.com/two",
+ output: "/tmp/two-desktop.webp",
+ width: 1440,
+ height: 900,
+ },
+ ]);
+
+ expect(layouts).toHaveLength(4);
+ expect(
+ socket.sentMessages
+ .filter((message) => message.method === "Page.navigate")
+ .map((message) => message.params?.url)
+ ).toEqual(["https://example.com/one", "https://example.com/two"]);
+ expect(
+ socket.sentMessages
+ .filter(
+ (message) => message.method === "Emulation.setDeviceMetricsOverride"
+ )
+ .map((message) => message.params?.width)
+ ).toEqual([375, 1440, 375, 1440]);
+ expect(dependencies.createWebSocket).toHaveBeenCalledOnce();
+ expect(dependencies.writeFile).toHaveBeenCalledTimes(4);
+
+ await session.close();
+});
+
+test("restarts the shared browser once after an unexpected exit", async () => {
+ const firstProcess = new FakeBrowserProcess();
+ const secondProcess = new FakeBrowserProcess();
+ const dependencies = createDependencies();
+ vi.mocked(dependencies.spawnBrowser)
+ .mockReturnValueOnce(
+ firstProcess as unknown as ReturnType<
+ BrowserScreenshotDependencies["spawnBrowser"]
+ >
+ )
+ .mockReturnValueOnce(
+ secondProcess as unknown as ReturnType<
+ BrowserScreenshotDependencies["spawnBrowser"]
+ >
+ );
+ vi.mocked(dependencies.createWebSocket)
+ .mockImplementationOnce(
+ () => new CrashingWebSocket(firstProcess) as unknown as WebSocket
+ )
+ .mockImplementationOnce(() => new FakeWebSocket() as unknown as WebSocket);
+ const options = {
+ url: "https://example.com",
+ output: "/tmp/restarted.png",
+ width: 800,
+ height: 600,
+ browserPath: "/usr/bin/chromium",
+ waitUntil: "networkidle" as const,
+ waitForTimeout: 0,
+ timeout: 1000,
+ };
+ const session = await createBrowserScreenshotSession(options, dependencies);
+
+ await expect(session.capture(options)).resolves.toMatchObject({
+ viewportWidth: 800,
+ viewportHeight: 600,
+ });
+
+ expect(dependencies.spawnBrowser).toHaveBeenCalledTimes(2);
+ expect(dependencies.rm).toHaveBeenCalledTimes(1);
+
+ await session.close();
+
+ expect(secondProcess.kill).toHaveBeenCalledOnce();
+ expect(dependencies.rm).toHaveBeenCalledTimes(2);
+});
+
test("captures full page and returns DevTools layout metrics", async () => {
const browserProcess = new FakeBrowserProcess();
const socket = new FakeWebSocket();
@@ -344,18 +770,33 @@ test("captures full page and returns DevTools layout metrics", async () => {
);
expect(layout).toEqual({
+ navigation: {
+ requestedUrl: "https://example.com",
+ finalUrl: "https://example.com",
+ status: 200,
+ statusText: "OK",
+ mimeType: "text/html",
+ redirects: [],
+ documentReadyState: "complete",
+ generatedSiteRootPresent: true,
+ layoutStable: true,
+ },
+ documentType: "text/html",
viewportWidth: 800,
viewportHeight: 600,
contentWidth: 813,
contentHeight: 2346,
- horizontalOverflow: true,
+ horizontalOverflow: false,
images: [
{
instanceId: "hero-image",
+ sourcePathname: "/assets/hero.png",
loading: "eager",
complete: true,
naturalWidth: 2400,
naturalHeight: 1600,
+ selectedSourceWidth: 1200,
+ selectedSourceHeight: 800,
renderedWidth: 600,
renderedHeight: 400,
top: 1000,
@@ -380,11 +821,23 @@ test("captures full page and returns DevTools layout metrics", async () => {
duration: 40,
},
],
+ timings: {
+ wallMs: expect.any(Number),
+ targetSetupMs: expect.any(Number),
+ navigationMs: expect.any(Number),
+ readinessMs: expect.any(Number),
+ imageInspectionMs: expect.any(Number),
+ resourceInspectionMs: expect.any(Number),
+ screenshotMs: expect.any(Number),
+ artifactWriteMs: expect.any(Number),
+ targetCleanupMs: expect.any(Number),
+ },
});
expect(socket.sentMethods).toEqual(
expect.arrayContaining(["Page.getLayoutMetrics", "Page.captureScreenshot"])
);
+ expect(socket.screenshotStartedBeforeImageInspectionFinished).toBe(true);
expect(
socket.sentMessages.find(
(message) => message.method === "Page.captureScreenshot"
@@ -392,6 +845,7 @@ test("captures full page and returns DevTools layout metrics", async () => {
).toEqual({
format: "png",
captureBeyondViewport: true,
+ optimizeForSpeed: true,
clip: {
x: 0,
y: 0,
@@ -402,6 +856,82 @@ test("captures full page and returns DevTools layout metrics", async () => {
});
});
+test("returns final URL, redirects, and HTTP error status", async () => {
+ const layout = await captureBrowserScreenshot(
+ {
+ url: "https://example.com/old",
+ output: "/tmp/not-found.png",
+ width: 800,
+ height: 600,
+ browserPath: "/usr/bin/chromium",
+ waitUntil: "networkidle",
+ waitForTimeout: 0,
+ timeout: 1000,
+ },
+ createDependencies({
+ socket: new FakeWebSocket(404, "https://example.com/missing"),
+ })
+ );
+
+ expect(layout.navigation).toEqual({
+ requestedUrl: "https://example.com/old",
+ finalUrl: "https://example.com/missing",
+ status: 404,
+ statusText: "Not Found",
+ mimeType: "text/html",
+ redirects: ["https://example.com/old"],
+ documentReadyState: "complete",
+ generatedSiteRootPresent: true,
+ layoutStable: true,
+ });
+});
+
+test("ignores child-frame document responses when reporting navigation", async () => {
+ const layout = await captureBrowserScreenshot(
+ {
+ url: "https://example.com/page",
+ output: "/tmp/page-with-blocked-embed.png",
+ width: 800,
+ height: 600,
+ browserPath: "/usr/bin/chromium",
+ waitUntil: "networkidle",
+ waitForTimeout: 0,
+ timeout: 1000,
+ },
+ createDependencies({
+ socket: new FakeWebSocket(200, undefined, 403),
+ })
+ );
+
+ expect(layout.navigation).toMatchObject({
+ requestedUrl: "https://example.com/page",
+ finalUrl: "https://example.com/page",
+ status: 200,
+ statusText: "OK",
+ redirects: [],
+ });
+});
+
+test("waits for two stable layout samples after a late shift", async () => {
+ const layout = await captureBrowserScreenshot(
+ {
+ url: "https://example.com/page",
+ output: "/tmp/page-after-layout-shift.png",
+ width: 800,
+ height: 600,
+ browserPath: "/usr/bin/chromium",
+ waitUntil: "networkidle",
+ waitForTimeout: 0,
+ timeout: 1000,
+ },
+ createDependencies({
+ socket: new FakeWebSocket(200, undefined, undefined, [812, 813, 813]),
+ })
+ );
+
+ expect(layout.navigation?.layoutStable).toBe(true);
+});
+
test("times out when browser DevTools commands stop responding", async () => {
const browserProcess = new FakeBrowserProcess();
const socket = new HangingWebSocket();
@@ -430,6 +960,32 @@ test("times out when browser DevTools commands stop responding", async () => {
});
});
+test("rejects pending commands when the DevTools socket closes", async () => {
+ const browserProcess = new FakeBrowserProcess();
+ const dependencies = createDependencies({
+ browserProcess,
+ socket: new ClosingWebSocket(),
+ });
+
+ await expect(
+ captureBrowserScreenshot(
+ {
+ url: "https://example.com",
+ output: "/tmp/current.png",
+ width: 800,
+ height: 600,
+ browserPath: "/usr/bin/chromium",
+ waitUntil: "load",
+ waitForTimeout: 0,
+ timeout: 1000,
+ },
+ dependencies
+ )
+ ).rejects.toThrow("Browser DevTools connection closed.");
+
+ expect(browserProcess.kill).toHaveBeenCalled();
+});
+
test("times out when browser page target creation does not respond", async () => {
const browserProcess = new FakeBrowserProcess();
const dependencies = createDependencies({
diff --git a/packages/cli/src/screenshot-browser-cdp.ts b/packages/cli/src/screenshot-browser-cdp.ts
index a656f13877..4d905e48e9 100644
--- a/packages/cli/src/screenshot-browser-cdp.ts
+++ b/packages/cli/src/screenshot-browser-cdp.ts
@@ -21,6 +21,21 @@ export type BrowserScreenshotOptions = {
waitForSelector?: string;
waitForTimeout: number;
timeout: number;
+ format?: "png" | "jpeg" | "webp";
+ quality?: number;
+ scale?: number;
+};
+
+export type BrowserScreenshotTimings = {
+ wallMs: number;
+ targetSetupMs: number;
+ navigationMs: number;
+ readinessMs: number;
+ imageInspectionMs: number;
+ resourceInspectionMs: number;
+ screenshotMs: number;
+ artifactWriteMs: number;
+ targetCleanupMs: number;
};
export type BrowserScreenshotDependencies = {
@@ -81,6 +96,12 @@ const withDeadline = async <Result>(
}
};
+const measureDuration = async <Result>(operation: () => Promise<Result>) => {
+ const startedAt = Date.now();
+ const value = await operation();
+ return { value, duration: Date.now() - startedAt };
+};
+
type CdpMessage = {
id?: number;
method?: string;
@@ -101,9 +122,13 @@ class CdpSession {
#listeners = new Map<string, Set<(params: unknown) => void>>();
readonly #socket: WebSocket;
+ #closed = false;
constructor(socket: WebSocket) {
this.#socket = socket;
+ this.#socket.addEventListener("close", () => {
+ this.#rejectPending(new Error("Browser DevTools connection closed."));
+ });
this.#socket.addEventListener("message", (event) => {
const message = JSON.parse(String(event.data)) as CdpMessage;
if (message.id !== undefined) {
@@ -151,9 +176,21 @@ class CdpSession {
};
close = () => {
+ this.#rejectPending(new Error("Browser DevTools session was closed."));
this.#socket.close();
};
+ #rejectPending = (error: Error) => {
+ if (this.#closed) {
+ return;
+ }
+ this.#closed = true;
+ for (const callback of this.#callbacks.values()) {
+ callback.reject(error);
+ }
+ this.#callbacks.clear();
+ };
+
on = (method: string, listener: (params: unknown) => void) => {
let listeners = this.#listeners.get(method);
if (listeners === undefined) {
@@ -170,6 +207,9 @@ class CdpSession {
method: string,
params: Record<string, unknown> = {}
): Promise<Result> => {
+ if (this.#closed) {
+ throw new Error("Browser DevTools session is closed.");
+ }
const id = this.#nextId;
this.#nextId += 1;
const result = new Promise<Result>((resolveSend, rejectSend) => {
@@ -228,39 +268,74 @@ const getPageWebSocketUrl = async ({
.then((response) => response.json()),
"Browser page target could not be created",
timeout
- )) as { webSocketDebuggerUrl?: string };
+ )) as { id?: string; webSocketDebuggerUrl?: string };
if (target?.webSocketDebuggerUrl === undefined) {
throw new Error("Browser did not expose the created page target.");
}
- return target.webSocketDebuggerUrl;
+ return {
+ id: target.id,
+ webSocketDebuggerUrl: target.webSocketDebuggerUrl,
+ };
};
-const waitForLifecycleEvent = async (
+type NavigationResult = {
+ errorText?: string;
+ frameId?: string;
+ loaderId?: string;
+};
+
+const navigateAndWaitForLifecycle = async (
cdp: CdpSession,
waitUntil: ScreenshotWaitUntil,
- timeout: number
+ timeout: number,
+ navigate: () => Promise<NavigationResult>
) => {
- if (waitUntil === "commit") {
- return;
- }
const expected = lifecycleEventByWaitUntil[waitUntil];
- await withDeadline(
- new Promise<void>((resolveLifecycle) => {
- const dispose = cdp.on("Page.lifecycleEvent", (params) => {
- if (
- typeof params === "object" &&
- params !== null &&
- "name" in params &&
- params.name === expected
- ) {
- dispose();
- resolveLifecycle();
- }
- });
- }),
- `Page did not reach ${waitUntil}`,
- timeout
- );
+ let navigation: NavigationResult | undefined;
+ const pendingEvents: unknown[] = [];
+ let resolveLifecycle: () => void = () => undefined;
+ const lifecycle = new Promise<void>((resolve) => {
+ resolveLifecycle = resolve;
+ });
+ const matchesNavigation = (params: unknown) => {
+ if (
+ navigation?.frameId === undefined ||
+ typeof params !== "object" ||
+ params === null ||
+ !("name" in params) ||
+ params.name !== expected ||
+ !("frameId" in params) ||
+ params.frameId !== navigation.frameId
+ ) {
+ return false;
+ }
+ return (
+ navigation.loaderId === undefined ||
+ ("loaderId" in params && params.loaderId === navigation.loaderId)
+ );
+ };
+ const dispose = cdp.on("Page.lifecycleEvent", (params) => {
+ if (navigation === undefined) {
+ pendingEvents.push(params);
+ return;
+ }
+ if (matchesNavigation(params)) {
+ resolveLifecycle();
+ }
+ });
+ try {
+ navigation = await navigate();
+ if (navigation.errorText !== undefined || waitUntil === "commit") {
+ return navigation;
+ }
+ if (pendingEvents.some(matchesNavigation)) {
+ resolveLifecycle();
+ }
+ await withDeadline(lifecycle, `Page did not reach ${waitUntil}`, timeout);
+ return navigation;
+ } finally {
+ dispose();
+ }
};
const waitForSelector = async (
@@ -289,21 +364,84 @@ const waitForSelector = async (
);
};
-const waitForFontsAndFrames = async (cdp: CdpSession, timeout: number) => {
- await withDeadline(
- cdp.send("Runtime.evaluate", {
- expression: `
- Promise.resolve(document.fonts?.ready).then(
- () => new Promise((resolve) => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- })
- )
- `,
- awaitPromise: true,
- }),
- "Page fonts and animation frames were not ready",
- timeout
- );
+type BrowserReadiness = {
+ documentReadyState: string;
+ generatedSiteRootPresent: boolean;
+ layoutStable: boolean;
+};
+
+const waitForFontsAndFrames = async (
+ cdp: CdpSession,
+ timeout: number
+): Promise<BrowserReadiness> => {
+ const measure = async () => {
+ const response = await withDeadline(
+ cdp.send<{ result?: { value?: unknown } }>("Runtime.evaluate", {
+ expression: `Promise.resolve(document.fonts?.ready).then(() => ({
+ documentReadyState: document.readyState,
+ generatedSiteRootPresent:
+ document.documentElement.hasAttribute("data-ws-project"),
+ width: document.documentElement.scrollWidth,
+ height: document.documentElement.scrollHeight,
+ }))`,
+ awaitPromise: true,
+ returnByValue: true,
+ }),
+ "Page fonts and layout sample were not ready",
+ timeout
+ );
+ return response.result?.value;
+ };
+ const isLayoutSample = (
+ value: unknown
+ ): value is {
+ documentReadyState: string;
+ generatedSiteRootPresent: boolean;
+ width: number;
+ height: number;
+ } =>
+ typeof value === "object" &&
+ value !== null &&
+ "documentReadyState" in value &&
+ typeof value.documentReadyState === "string" &&
+ "generatedSiteRootPresent" in value &&
+ typeof value.generatedSiteRootPresent === "boolean" &&
+ "width" in value &&
+ typeof value.width === "number" &&
+ "height" in value &&
+ typeof value.height === "number";
+ const initial = await measure();
+ if (isLayoutSample(initial) === false) {
+ throw new Error(
+ "Browser did not report generated page readiness evidence."
+ );
+ }
+ let before = initial;
+ const deadline = Date.now() + timeout;
+ while (true) {
+ await delay(32);
+ const value = await measure();
+ if (isLayoutSample(value) === false) {
+ throw new Error(
+ "Browser did not report generated page readiness evidence."
+ );
+ }
+ if (before.width === value.width && before.height === value.height) {
+ return {
+ documentReadyState: value.documentReadyState,
+ generatedSiteRootPresent: value.generatedSiteRootPresent,
+ layoutStable: true,
+ };
+ }
+ if (Date.now() >= deadline) {
+ return {
+ documentReadyState: value.documentReadyState,
+ generatedSiteRootPresent: value.generatedSiteRootPresent,
+ layoutStable: false,
+ };
+ }
+ before = value;
+ }
};
const createBrowserLaunchArgs = ({
@@ -319,6 +457,9 @@ const createBrowserLaunchArgs = ({
}) => [
"--headless=new",
"--disable-gpu",
+ "--disable-background-timer-throttling",
+ "--disable-backgrounding-occluded-windows",
+ "--disable-renderer-backgrounding",
"--hide-scrollbars",
"--remote-debugging-port=0",
`--user-data-dir=${userDataDir}`,
@@ -342,7 +483,16 @@ type BrowserLayoutMetricsResponse = {
};
};
+type BrowserDocumentMetrics = {
+ scrollWidth: number;
+ scrollHeight: number;
+ horizontalOverflowSuppressed: boolean;
+ documentType: string;
+};
+
export type BrowserScreenshotLayout = {
+ navigation?: BrowserScreenshotNavigation;
+ documentType?: string;
viewportWidth: number;
viewportHeight: number;
contentWidth: number;
@@ -350,14 +500,30 @@ export type BrowserScreenshotLayout = {
horizontalOverflow: boolean;
images?: BrowserScreenshotImage[];
resources?: BrowserScreenshotResource[];
+ timings?: BrowserScreenshotTimings;
+};
+
+export type BrowserScreenshotNavigation = {
+ requestedUrl: string;
+ finalUrl: string;
+ status?: number;
+ statusText?: string;
+ mimeType?: string;
+ redirects: string[];
+ documentReadyState: string;
+ generatedSiteRootPresent: boolean;
+ layoutStable: boolean;
};
export type BrowserScreenshotImage = {
instanceId?: string;
+ sourcePathname?: string;
loading: string;
complete: boolean;
naturalWidth: number;
naturalHeight: number;
+ selectedSourceWidth?: number;
+ selectedSourceHeight?: number;
renderedWidth: number;
renderedHeight: number;
top: number;
@@ -440,19 +606,48 @@ const getBrowserScreenshotImages = async (
const response = await send<{
result?: { value?: unknown };
}>("Runtime.evaluate", {
- expression: `Array.from(document.images, (image) => {
+ expression: `Promise.all(Array.from(document.images, async (image) => {
+ globalThis.__webstudioImageDimensionCache ??= new Map();
const rect = image.getBoundingClientRect();
+ let sourcePathname;
+ let selectedSourceWidth;
+ let selectedSourceHeight;
+ const selectedSource = image.currentSrc || image.src;
+ try {
+ sourcePathname = selectedSource.startsWith("data:")
+ ? selectedSource.slice(0, selectedSource.indexOf(","))
+ : new URL(selectedSource, document.baseURI).pathname;
+ } catch {}
+ try {
+ let dimensions = globalThis.__webstudioImageDimensionCache.get(selectedSource);
+ if (dimensions === undefined) {
+ const response = await fetch(selectedSource);
+ const bitmap = await createImageBitmap(await response.blob());
+ dimensions = { width: bitmap.width, height: bitmap.height };
+ bitmap.close();
+ globalThis.__webstudioImageDimensionCache.set(selectedSource, dimensions);
+ }
+ selectedSourceWidth = dimensions.width;
+ selectedSourceHeight = dimensions.height;
+ } catch {}
return {
- instanceId: image.getAttribute("data-ws-id") || undefined,
+ instanceId:
+ image.getAttribute("data-ws-id") ||
+ image.closest("[data-ws-id]")?.getAttribute("data-ws-id") ||
+ undefined,
+ sourcePathname,
loading: image.loading || "eager",
complete: image.complete,
naturalWidth: image.naturalWidth,
naturalHeight: image.naturalHeight,
+ selectedSourceWidth,
+ selectedSourceHeight,
renderedWidth: rect.width,
renderedHeight: rect.height,
top: rect.top + window.scrollY,
};
- })`,
+ }))`,
+ awaitPromise: true,
returnByValue: true,
});
if (Array.isArray(response.result?.value) === false) {
@@ -479,10 +674,19 @@ const getBrowserScreenshotImages = async (
...(typeof image.instanceId === "string"
? { instanceId: image.instanceId }
: {}),
+ ...(typeof image.sourcePathname === "string"
+ ? { sourcePathname: image.sourcePathname }
+ : {}),
loading: image.loading,
complete: image.complete,
naturalWidth: image.naturalWidth,
naturalHeight: image.naturalHeight,
+ ...(typeof image.selectedSourceWidth === "number"
+ ? { selectedSourceWidth: image.selectedSourceWidth }
+ : {}),
+ ...(typeof image.selectedSourceHeight === "number"
+ ? { selectedSourceHeight: image.selectedSourceHeight }
+ : {}),
renderedWidth: image.renderedWidth,
renderedHeight: image.renderedHeight,
top: image.top,
@@ -493,12 +697,13 @@ const getBrowserScreenshotImages = async (
const getBrowserScreenshotLayout = (
metrics: BrowserLayoutMetricsResponse,
+ documentMetrics: BrowserDocumentMetrics,
viewport: { width: number; height: number },
images: BrowserScreenshotImage[],
resources: BrowserScreenshotResource[]
): BrowserScreenshotLayout => {
- const contentWidth = metrics.cssContentSize?.width;
- const contentHeight = metrics.cssContentSize?.height;
+ const contentWidth = documentMetrics.scrollWidth;
+ const contentHeight = documentMetrics.scrollHeight;
const viewportWidth =
metrics.cssLayoutViewport?.clientWidth ?? viewport.width;
const viewportHeight =
@@ -514,26 +719,96 @@ const getBrowserScreenshotLayout = (
throw new Error("Browser did not report valid page layout metrics.");
}
return {
+ documentType: documentMetrics.documentType,
viewportWidth: Math.round(viewportWidth),
viewportHeight: Math.round(viewportHeight),
contentWidth: Math.ceil(contentWidth),
contentHeight: Math.ceil(contentHeight),
- horizontalOverflow: contentWidth > viewportWidth + 1,
+ horizontalOverflow:
+ documentMetrics.horizontalOverflowSuppressed === false &&
+ contentWidth > viewportWidth + 1,
images,
resources,
};
};
+const getBrowserDocumentMetrics = async (
+ send: <Result = unknown>(
+ method: string,
+ params?: Record<string, unknown>
+ ) => Promise<Result>
+): Promise<BrowserDocumentMetrics> => {
+ const response = await send<{
+ result?: { value?: unknown };
+ }>("Runtime.evaluate", {
+ expression: `({
+ scrollWidth: Math.max(
+ document.documentElement.scrollWidth,
+ document.body?.scrollWidth || 0
+ ),
+ scrollHeight: Math.max(
+ document.documentElement.scrollHeight,
+ document.body?.scrollHeight || 0
+ ),
+ horizontalOverflowSuppressed: [
+ getComputedStyle(document.documentElement).overflowX,
+ document.body ? getComputedStyle(document.body).overflowX : "visible",
+ ].some((value) => value === "hidden" || value === "clip") ||
+ (document.contentType !== "text/html" &&
+ document.contentType !== "application/xhtml+xml"),
+ documentType: document.contentType || "",
+ })`,
+ returnByValue: true,
+ });
+ const value = response.result?.value;
+ if (typeof value !== "object" || value === null) {
+ throw new Error("Browser did not report valid document metrics.");
+ }
+ const {
+ scrollWidth,
+ scrollHeight,
+ horizontalOverflowSuppressed,
+ documentType,
+ } = value as Record<string, unknown>;
+ if (
+ typeof scrollWidth !== "number" ||
+ typeof scrollHeight !== "number" ||
+ scrollWidth <= 0 ||
+ scrollHeight <= 0 ||
+ typeof horizontalOverflowSuppressed !== "boolean" ||
+ typeof documentType !== "string"
+ ) {
+ throw new Error("Browser did not report valid document metrics.");
+ }
+ return {
+ scrollWidth,
+ scrollHeight,
+ horizontalOverflowSuppressed,
+ documentType,
+ };
+};
+
const getScreenshotCaptureParams = async ({
metrics,
fullPage,
+ format = "png",
+ quality,
+ scale = 1,
}: {
metrics: BrowserLayoutMetricsResponse;
fullPage?: boolean;
+ format?: "png" | "jpeg" | "webp";
+ quality?: number;
+ scale?: number;
}) => {
+ const encoding = {
+ format,
+ ...(format === "png" || quality === undefined ? {} : { quality }),
+ optimizeForSpeed: true,
+ };
if (fullPage !== true) {
return {
- format: "png",
+ ...encoding,
captureBeyondViewport: false,
};
}
@@ -547,22 +822,33 @@ const getScreenshotCaptureParams = async ({
throw new Error("Browser did not report a valid full-page content size.");
}
return {
- format: "png",
+ ...encoding,
captureBeyondViewport: true,
clip: {
x,
y,
width: Math.ceil(width),
height: Math.ceil(height),
- scale: 1,
+ scale,
},
};
};
-export const captureBrowserScreenshot = async (
+class BrowserSessionClosedError extends Error {}
+
+type BrowserRuntime = {
+ userDataDir: string;
+ browserProcess: BrowserProcess;
+ browserClosed: Promise<void>;
+ port: string;
+ running: boolean;
+ close: () => Promise<void>;
+};
+
+const startBrowserRuntime = async (
options: BrowserScreenshotOptions,
- dependencies = defaultBrowserScreenshotDependencies
-) => {
+ dependencies: BrowserScreenshotDependencies
+): Promise<BrowserRuntime> => {
const userDataDir = await dependencies.mkdtemp(
join(tmpdir(), "webstudio-browser-")
);
@@ -575,134 +861,483 @@ export const captureBrowserScreenshot = async (
uid: options.uid,
})
);
+ let running = true;
const browserClosed = new Promise<void>((resolveClosed) => {
- browserProcess.once("exit", () => resolveClosed());
- browserProcess.once("error", () => resolveClosed());
+ const close = () => {
+ running = false;
+ resolveClosed();
+ };
+ browserProcess.once("exit", close);
+ browserProcess.once("error", close);
});
+ try {
+ const { port } = await Promise.race([
+ waitForDevToolsPort(userDataDir, dependencies, options.timeout),
+ browserClosed.then(() => {
+ throw new BrowserSessionClosedError(
+ "Browser exited before its DevTools endpoint became ready."
+ );
+ }),
+ ]);
+ let closePromise: Promise<void> | undefined;
+ const runtime: BrowserRuntime = {
+ userDataDir,
+ browserProcess,
+ browserClosed,
+ port,
+ get running() {
+ return running;
+ },
+ close: async () => {
+ closePromise ??= (async () => {
+ if (running) {
+ browserProcess.kill();
+ }
+ await withDeadline(
+ browserClosed,
+ "Browser process did not exit after screenshot capture",
+ 2000
+ ).catch(() => undefined);
+ await dependencies.rm(userDataDir, {
+ recursive: true,
+ force: true,
+ });
+ })();
+ await closePromise;
+ },
+ };
+ return runtime;
+ } catch (error) {
+ browserProcess.kill();
+ await browserClosed;
+ await dependencies.rm(userDataDir, { recursive: true, force: true });
+ throw error;
+ }
+};
+
+const capturePageWithBrowserRuntime = async (
+ runtime: BrowserRuntime,
+ optionsList: readonly BrowserScreenshotOptions[],
+ dependencies: BrowserScreenshotDependencies
+) => {
+ const firstOptions = optionsList[0];
+ if (firstOptions === undefined) {
+ return [];
+ }
let cdp: CdpSession | undefined;
- let layout: BrowserScreenshotLayout | undefined;
+ let targetId: string | undefined;
+ const layouts: BrowserScreenshotLayout[] = [];
try {
await Promise.race([
- new Promise<never>((_, reject) => {
- browserProcess.once("error", reject);
- browserProcess.once("exit", (code) => {
- reject(
- new Error(
- `Browser exited before screenshot capture completed${
- code === null ? "." : ` with code ${code}.`
- }`
- )
- );
- });
+ runtime.browserClosed.then(() => {
+ throw new BrowserSessionClosedError(
+ "Browser exited before screenshot capture completed."
+ );
}),
(async () => {
- const { port } = await waitForDevToolsPort(
- userDataDir,
- dependencies,
- options.timeout
- );
- const pageWebSocketUrl = await getPageWebSocketUrl({
- port,
+ const setupStartedAt = Date.now();
+ const target = await getPageWebSocketUrl({
+ port: runtime.port,
dependencies,
- timeout: options.timeout,
+ timeout: firstOptions.timeout,
});
+ targetId = target.id;
cdp = await CdpSession.connect(
- pageWebSocketUrl,
+ target.webSocketDebuggerUrl,
dependencies,
- options.timeout
+ firstOptions.timeout
);
const send = async <Result = unknown>(
method: string,
- params: Record<string, unknown> = {}
+ params: Record<string, unknown> = {},
+ timeout = firstOptions.timeout
) =>
await withDeadline(
cdp?.send<Result>(method, params) ??
Promise.reject(new Error("Browser DevTools session is closed.")),
`Browser command ${method} did not finish`,
- options.timeout
+ timeout
);
+ const redirectsByFrame = new Map<string, string[]>();
+ const documentResponsesByFrame = new Map<
+ string,
+ {
+ url: string;
+ status: number;
+ statusText?: string;
+ mimeType?: string;
+ }
+ >();
+ cdp.on("Network.requestWillBeSent", (params) => {
+ if (
+ typeof params !== "object" ||
+ params === null ||
+ !("type" in params) ||
+ params.type !== "Document" ||
+ !("redirectResponse" in params) ||
+ typeof params.redirectResponse !== "object" ||
+ params.redirectResponse === null ||
+ !("url" in params.redirectResponse) ||
+ typeof params.redirectResponse.url !== "string" ||
+ !("frameId" in params) ||
+ typeof params.frameId !== "string"
+ ) {
+ return;
+ }
+ const redirects = redirectsByFrame.get(params.frameId) ?? [];
+ redirects.push(params.redirectResponse.url);
+ redirectsByFrame.set(params.frameId, redirects);
+ });
+ cdp.on("Network.responseReceived", (params) => {
+ if (
+ typeof params !== "object" ||
+ params === null ||
+ !("type" in params) ||
+ params.type !== "Document" ||
+ !("frameId" in params) ||
+ typeof params.frameId !== "string" ||
+ !("response" in params) ||
+ typeof params.response !== "object" ||
+ params.response === null
+ ) {
+ return;
+ }
+ const response = params.response as Record<string, unknown>;
+ if (
+ typeof response.url !== "string" ||
+ typeof response.status !== "number"
+ ) {
+ return;
+ }
+ documentResponsesByFrame.set(params.frameId, {
+ url: response.url,
+ status: response.status,
+ ...(typeof response.statusText === "string"
+ ? { statusText: response.statusText }
+ : {}),
+ ...(typeof response.mimeType === "string"
+ ? { mimeType: response.mimeType }
+ : {}),
+ });
+ });
await Promise.all([
send("Page.enable"),
+ send("Network.enable"),
send("Runtime.enable"),
send("Page.setLifecycleEventsEnabled", { enabled: true }),
- send("Emulation.setDeviceMetricsOverride", {
- width: options.width,
- height: options.height,
- deviceScaleFactor: 1,
- mobile: false,
- }),
]);
- const lifecycle = waitForLifecycleEvent(
- cdp,
- options.waitUntil,
- options.timeout
- );
- const navigation = await send<{ errorText?: string }>("Page.navigate", {
- url: options.url,
- });
- if (navigation.errorText !== undefined) {
- throw new Error(`Browser navigation failed: ${navigation.errorText}`);
- }
- await lifecycle;
- if (options.waitForSelector !== undefined) {
- await waitForSelector(cdp, options.waitForSelector, options.timeout);
- }
- await waitForFontsAndFrames(cdp, options.timeout);
- if (options.waitForTimeout > 0) {
- await delay(options.waitForTimeout);
- }
- const metrics = await send<BrowserLayoutMetricsResponse>(
- "Page.getLayoutMetrics"
- );
- const images =
- options.includeImageMetrics === true
- ? await getBrowserScreenshotImages(send)
- : undefined;
- const resources =
- options.includeResourceMetrics === true
- ? await getBrowserScreenshotResources(send)
- : undefined;
- layout = getBrowserScreenshotLayout(
- metrics,
- {
- width: options.width,
- height: options.height,
- },
- images ?? [],
- resources ?? []
- );
- if (images === undefined) {
- delete layout.images;
- }
- if (resources === undefined) {
- delete layout.resources;
+ const targetSetupMs = Date.now() - setupStartedAt;
+ let navigationFrameId: string | undefined;
+ let previousUrl: string | undefined;
+ for (const [index, options] of optionsList.entries()) {
+ const viewportStartedAt = Date.now();
+ await send(
+ "Emulation.setDeviceMetricsOverride",
+ {
+ width: options.width,
+ height: options.height,
+ deviceScaleFactor: 1,
+ mobile: false,
+ },
+ options.timeout
+ );
+ let navigationMs = 0;
+ if (options.url !== previousUrl) {
+ redirectsByFrame.clear();
+ documentResponsesByFrame.clear();
+ const navigationStartedAt = Date.now();
+ const navigation = await navigateAndWaitForLifecycle(
+ cdp,
+ options.waitUntil,
+ options.timeout,
+ async () =>
+ await send<NavigationResult>(
+ "Page.navigate",
+ { url: options.url },
+ options.timeout
+ )
+ );
+ if (navigation.errorText !== undefined) {
+ throw new Error(
+ `Browser navigation failed: ${navigation.errorText}`
+ );
+ }
+ navigationFrameId = navigation.frameId;
+ navigationMs = Date.now() - navigationStartedAt;
+ previousUrl = options.url;
+ } else {
+ await send(
+ "Runtime.evaluate",
+ {
+ expression:
+ "new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))",
+ awaitPromise: true,
+ },
+ options.timeout
+ );
+ }
+ const readinessStartedAt = Date.now();
+ if (options.waitForSelector !== undefined) {
+ await waitForSelector(
+ cdp,
+ options.waitForSelector,
+ options.timeout
+ );
+ }
+ const readiness = await waitForFontsAndFrames(cdp, options.timeout);
+ if (options.waitForTimeout > 0) {
+ await delay(options.waitForTimeout);
+ }
+ const readinessMs = Date.now() - readinessStartedAt;
+ const locationPromise = send<{
+ result?: { value?: unknown };
+ }>(
+ "Runtime.evaluate",
+ {
+ expression: "window.location.href",
+ returnByValue: true,
+ },
+ options.timeout
+ );
+ const metricsPromise = send<BrowserLayoutMetricsResponse>(
+ "Page.getLayoutMetrics",
+ {},
+ options.timeout
+ );
+ const documentMetricsPromise = getBrowserDocumentMetrics(send);
+ const imageInspectionPromise = measureDuration(async () =>
+ options.includeImageMetrics === true
+ ? await getBrowserScreenshotImages(send)
+ : undefined
+ );
+ const resourceInspectionPromise = measureDuration(async () =>
+ options.includeResourceMetrics === true
+ ? await getBrowserScreenshotResources(send)
+ : undefined
+ );
+ const screenshotPromise = (async () => {
+ const metrics = await metricsPromise;
+ const captureParams = await getScreenshotCaptureParams({
+ metrics,
+ fullPage: options.fullPage,
+ format: options.format,
+ quality: options.quality,
+ scale: options.scale,
+ });
+ const screenshot = await measureDuration(async () =>
+ send<{ data: string }>(
+ "Page.captureScreenshot",
+ captureParams,
+ options.timeout
+ )
+ );
+ const artifactWrite = await measureDuration(async () =>
+ dependencies.writeFile(
+ options.output,
+ Buffer.from(screenshot.value.data, "base64")
+ )
+ );
+ return {
+ screenshotMs: screenshot.duration,
+ artifactWriteMs: artifactWrite.duration,
+ };
+ })();
+ const [
+ locationResult,
+ metrics,
+ documentMetrics,
+ imageInspection,
+ resourceInspection,
+ screenshot,
+ ] = await Promise.all([
+ locationPromise,
+ metricsPromise,
+ documentMetricsPromise,
+ imageInspectionPromise,
+ resourceInspectionPromise,
+ screenshotPromise,
+ ]);
+ const finalUrl =
+ typeof locationResult.result?.value === "string"
+ ? locationResult.result.value
+ : ((navigationFrameId === undefined
+ ? undefined
+ : documentResponsesByFrame.get(navigationFrameId)?.url) ??
+ options.url);
+ const documentResponse =
+ navigationFrameId === undefined
+ ? undefined
+ : documentResponsesByFrame.get(navigationFrameId);
+ const redirects =
+ navigationFrameId === undefined
+ ? []
+ : (redirectsByFrame.get(navigationFrameId) ?? []);
+ const images = imageInspection.value;
+ const resources = resourceInspection.value;
+ const layout = getBrowserScreenshotLayout(
+ metrics,
+ documentMetrics,
+ { width: options.width, height: options.height },
+ images ?? [],
+ resources ?? []
+ );
+ layout.navigation = {
+ requestedUrl: options.url,
+ finalUrl,
+ ...(documentResponse === undefined
+ ? {}
+ : {
+ status: documentResponse.status,
+ ...(documentResponse.statusText === undefined
+ ? {}
+ : { statusText: documentResponse.statusText }),
+ ...(documentResponse.mimeType === undefined
+ ? {}
+ : { mimeType: documentResponse.mimeType }),
+ }),
+ redirects,
+ ...readiness,
+ };
+ if (images === undefined) {
+ delete layout.images;
+ }
+ if (resources === undefined) {
+ delete layout.resources;
+ }
+ layout.timings = {
+ wallMs: Date.now() - viewportStartedAt,
+ targetSetupMs: index === 0 ? targetSetupMs : 0,
+ navigationMs,
+ readinessMs,
+ imageInspectionMs: imageInspection.duration,
+ resourceInspectionMs: resourceInspection.duration,
+ screenshotMs: screenshot.screenshotMs,
+ artifactWriteMs: screenshot.artifactWriteMs,
+ targetCleanupMs: 0,
+ };
+ layouts.push(layout);
}
- const captureParams = await getScreenshotCaptureParams({
- metrics,
- fullPage: options.fullPage,
- });
- const screenshot = await send<{ data: string }>(
- "Page.captureScreenshot",
- captureParams
- );
- await dependencies.writeFile(
- options.output,
- Buffer.from(screenshot.data, "base64")
- );
})(),
]);
} finally {
+ const cleanupStartedAt = Date.now();
cdp?.close();
- browserProcess.kill();
- await withDeadline(
- browserClosed,
- "Browser process did not exit after screenshot capture",
- 2000
- ).catch(() => undefined);
- await dependencies.rm(userDataDir, { recursive: true, force: true });
+ if (targetId !== undefined && runtime.running) {
+ await dependencies
+ .fetch(`http://127.0.0.1:${runtime.port}/json/close/${targetId}`)
+ .catch(() => undefined);
+ }
+ const lastLayout = layouts.at(-1);
+ if (lastLayout?.timings !== undefined) {
+ lastLayout.timings.targetCleanupMs = Date.now() - cleanupStartedAt;
+ }
}
+ if (layouts.length !== optionsList.length) {
+ throw new Error("Browser did not report page layout metrics.");
+ }
+ return layouts;
+};
+
+const captureWithBrowserRuntime = async (
+ runtime: BrowserRuntime,
+ options: BrowserScreenshotOptions,
+ dependencies: BrowserScreenshotDependencies
+) => {
+ const [layout] = await capturePageWithBrowserRuntime(
+ runtime,
+ [options],
+ dependencies
+ );
if (layout === undefined) {
throw new Error("Browser did not report page layout metrics.");
}
return layout;
};
+
+export type BrowserScreenshotSession = {
+ capture: (
+ options: BrowserScreenshotOptions
+ ) => Promise<BrowserScreenshotLayout>;
+ capturePage: (
+ options: readonly BrowserScreenshotOptions[]
+ ) => Promise<BrowserScreenshotLayout[]>;
+ close: () => Promise<void>;
+};
+
+export const createBrowserScreenshotSession = async (
+ options: BrowserScreenshotOptions,
+ dependencies = defaultBrowserScreenshotDependencies
+): Promise<BrowserScreenshotSession> => {
+ let runtime = await startBrowserRuntime(options, dependencies);
+ let restartPromise: Promise<BrowserRuntime> | undefined;
+ const restart = async (failedRuntime: BrowserRuntime) => {
+ if (runtime !== failedRuntime) {
+ return runtime;
+ }
+ restartPromise ??= (async () => {
+ await failedRuntime.close();
+ const next = await startBrowserRuntime(options, dependencies);
+ runtime = next;
+ restartPromise = undefined;
+ return next;
+ })();
+ return await restartPromise;
+ };
+ const captureWithRestart = async <Result>(
+ capture: (activeRuntime: BrowserRuntime) => Promise<Result>
+ ) => {
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ const activeRuntime = runtime;
+ try {
+ return await capture(activeRuntime);
+ } catch (error) {
+ if (
+ attempt === 1 ||
+ (error instanceof BrowserSessionClosedError === false &&
+ activeRuntime.running)
+ ) {
+ throw error;
+ }
+ await restart(activeRuntime);
+ }
+ }
+ throw new Error("Browser screenshot retry was exhausted.");
+ };
+ return {
+ async capture(captureOptions) {
+ return await captureWithRestart(
+ async (activeRuntime) =>
+ await captureWithBrowserRuntime(
+ activeRuntime,
+ captureOptions,
+ dependencies
+ )
+ );
+ },
+ async capturePage(captureOptions) {
+ return await captureWithRestart(
+ async (activeRuntime) =>
+ await capturePageWithBrowserRuntime(
+ activeRuntime,
+ captureOptions,
+ dependencies
+ )
+ );
+ },
+ async close() {
+ await runtime.close();
+ },
+ };
+};
+
+export const captureBrowserScreenshot = async (
+ options: BrowserScreenshotOptions,
+ dependencies = defaultBrowserScreenshotDependencies
+) => {
+ const session = await createBrowserScreenshotSession(options, dependencies);
+ try {
+ return await session.capture(options);
+ } finally {
+ await session.close();
+ }
+};
diff --git a/packages/cli/src/screenshot.test.ts b/packages/cli/src/screenshot.test.ts
index 9aa5fa7941..fc2e5025df 100644
--- a/packages/cli/src/screenshot.test.ts
+++ b/packages/cli/src/screenshot.test.ts
@@ -6,6 +6,7 @@ import {
BrowserInstallUnavailableError,
captureScreenshot,
captureScreenshotWithBrowserInstall,
+ createScreenshotCaptureSession,
getChromiumInstallCommand,
getNoBrowserFoundMessage,
installTesseractForOcr,
@@ -378,6 +379,42 @@ describe("captureScreenshot", () => {
});
});
+test("resets a reusable capture session after browser startup rejects", async () => {
+ const spawnBrowser = vi.fn(() => ({
+ kill: vi.fn(() => true),
+ once: vi.fn((event: string, listener: () => void) => {
+ if (event === "error") {
+ setTimeout(listener, 0);
+ }
+ }),
+ }));
+ const dependencies = createDependencies({
+ which: vi.fn(async (command) =>
+ command === "chromium" ? "/usr/bin/chromium" : undefined
+ ),
+ spawnBrowser: spawnBrowser as never,
+ });
+ const session = createScreenshotCaptureSession(dependencies);
+ const options = {
+ url: "https://example.com",
+ width: 800,
+ height: 600,
+ browser: "auto" as const,
+ timeout: 100,
+ };
+
+ await expect(session.capture(options)).rejects.toThrow(
+ "Browser exited before its DevTools endpoint became ready."
+ );
+ await expect(session.close()).resolves.toBeUndefined();
+
+ await expect(session.capture(options)).rejects.toThrow(
+ "Browser exited before its DevTools endpoint became ready."
+ );
+ await session.close();
+ expect(spawnBrowser).toHaveBeenCalledTimes(2);
+});
+
describe("browser installation", () => {
test("does not offer install in json, mcp, ci, or non-interactive contexts", () => {
expect(
diff --git a/packages/cli/src/screenshot.ts b/packages/cli/src/screenshot.ts
index 7afc5cdeee..dd6957a59c 100644
--- a/packages/cli/src/screenshot.ts
+++ b/packages/cli/src/screenshot.ts
@@ -14,7 +14,9 @@ import {
} from "@webstudio-is/project-build/visual/screenshot-browser";
import {
captureBrowserScreenshot,
+ createBrowserScreenshotSession,
defaultBrowserScreenshotDependencies,
+ type BrowserScreenshotSession,
type BrowserScreenshotDependencies,
type BrowserScreenshotLayout,
type BrowserScreenshotOptions,
@@ -486,34 +488,51 @@ export const shouldOfferBrowserInstall = ({
export const getScreenshotOutputPath = ({
output,
now,
+ format = "png",
+ suffix = "",
}: {
output?: string;
now: number;
-}) => resolve(output ?? `${tmpdir()}/webstudio-screenshot-${now}.png`);
+ format?: "png" | "jpeg" | "webp";
+ suffix?: string;
+}) =>
+ resolve(
+ output ??
+ `${tmpdir()}/webstudio-screenshot-${now}${suffix}.${format === "jpeg" ? "jpg" : format}`
+ );
-export const captureScreenshot = async (
- options: {
- url: string;
- output?: string;
- width: number;
- height: number;
- fullPage?: boolean;
- includeImageMetrics?: boolean;
- includeResourceMetrics?: boolean;
- browser: ScreenshotBrowser;
- browserPath?: string;
- waitUntil?: ScreenshotWaitUntil;
- waitForSelector?: string;
- waitForTimeout?: number;
- timeout?: number;
- },
- dependencies = defaultScreenshotDependencies
+let screenshotBatchSequence = 0;
+
+type CaptureScreenshotOptions = {
+ url: string;
+ output?: string;
+ width: number;
+ height: number;
+ fullPage?: boolean;
+ includeImageMetrics?: boolean;
+ includeResourceMetrics?: boolean;
+ browser: ScreenshotBrowser;
+ browserPath?: string;
+ waitUntil?: ScreenshotWaitUntil;
+ waitForSelector?: string;
+ waitForTimeout?: number;
+ timeout?: number;
+ format?: "png" | "jpeg" | "webp";
+ quality?: number;
+ scale?: number;
+};
+
+const captureResolvedScreenshot = async (
+ options: CaptureScreenshotOptions,
+ browser: BrowserCandidate,
+ dependencies: ScreenshotDependencies,
+ browserSession?: BrowserScreenshotSession
) => {
const startedAt = dependencies.now();
- const browser = await resolveScreenshotBrowser(options, dependencies);
const output = getScreenshotOutputPath({
output: options.output,
now: startedAt,
+ format: options.format,
});
await dependencies.mkdir(dirname(output), { recursive: true });
const browserScreenshotOptions = {
@@ -530,11 +549,19 @@ export const captureScreenshot = async (
waitForSelector: options.waitForSelector,
waitForTimeout: options.waitForTimeout ?? defaultScreenshotWaitForTimeout,
timeout: options.timeout ?? defaultScreenshotTimeout,
+ format: options.format,
+ quality: options.quality,
+ scale: options.scale,
};
const layout =
- dependencies.captureBrowserScreenshot !== undefined
- ? await dependencies.captureBrowserScreenshot(browserScreenshotOptions)
- : await captureBrowserScreenshot(browserScreenshotOptions, dependencies);
+ browserSession !== undefined
+ ? await browserSession.capture(browserScreenshotOptions)
+ : dependencies.captureBrowserScreenshot !== undefined
+ ? await dependencies.captureBrowserScreenshot(browserScreenshotOptions)
+ : await captureBrowserScreenshot(
+ browserScreenshotOptions,
+ dependencies
+ );
return {
output,
browser,
@@ -545,10 +572,167 @@ export const captureScreenshot = async (
fullPage: options.fullPage === true,
elapsedMs: dependencies.now() - startedAt,
warnings: [] as string[],
+ ...(layout?.timings === undefined ? {} : { timings: layout.timings }),
+ ...(layout?.navigation === undefined
+ ? {}
+ : { navigation: layout.navigation }),
...(layout === undefined ? {} : { layout }),
};
};
+export const captureScreenshot = async (
+ options: CaptureScreenshotOptions,
+ dependencies = defaultScreenshotDependencies
+) => {
+ const browser = await resolveScreenshotBrowser(options, dependencies);
+ return await captureResolvedScreenshot(options, browser, dependencies);
+};
+
+export const createScreenshotCaptureSession = (
+ dependencies = defaultScreenshotDependencies
+) => {
+ let browserPromise: Promise<BrowserCandidate> | undefined;
+ let browserSession: BrowserScreenshotSession | undefined;
+ let browserSessionPromise: Promise<BrowserScreenshotSession> | undefined;
+ return {
+ async capture(options: CaptureScreenshotOptions) {
+ browserPromise ??= resolveScreenshotBrowser(options, dependencies);
+ const resolvedBrowser = await browserPromise;
+ if (
+ (options.browserPath !== undefined &&
+ options.browserPath !== resolvedBrowser.path) ||
+ (options.browser !== "auto" &&
+ options.browser !== resolvedBrowser.browser)
+ ) {
+ throw new Error(
+ "A reusable screenshot session cannot switch browser executables."
+ );
+ }
+ browserSessionPromise ??= createBrowserScreenshotSession(
+ {
+ browserPath: resolvedBrowser.path,
+ output: options.output ?? "",
+ width: options.width,
+ height: options.height,
+ fullPage: options.fullPage,
+ includeImageMetrics: options.includeImageMetrics,
+ includeResourceMetrics: options.includeResourceMetrics,
+ url: options.url,
+ uid: dependencies.getuid(),
+ waitUntil: options.waitUntil ?? defaultScreenshotWaitUntil,
+ waitForSelector: options.waitForSelector,
+ waitForTimeout:
+ options.waitForTimeout ?? defaultScreenshotWaitForTimeout,
+ timeout: options.timeout ?? defaultScreenshotTimeout,
+ },
+ dependencies
+ );
+ browserSession ??= await browserSessionPromise;
+ return await captureResolvedScreenshot(
+ options,
+ resolvedBrowser,
+ dependencies,
+ browserSession
+ );
+ },
+ async capturePage(optionsList: readonly CaptureScreenshotOptions[]) {
+ const firstOptions = optionsList[0];
+ if (firstOptions === undefined) {
+ return [];
+ }
+ browserPromise ??= resolveScreenshotBrowser(firstOptions, dependencies);
+ const resolvedBrowser = await browserPromise;
+ if (
+ optionsList.some(
+ (options) =>
+ (options.browserPath !== undefined &&
+ options.browserPath !== resolvedBrowser.path) ||
+ (options.browser !== "auto" &&
+ options.browser !== resolvedBrowser.browser)
+ )
+ ) {
+ throw new Error(
+ "A reusable screenshot session cannot switch browser executables."
+ );
+ }
+ const startedAt = dependencies.now();
+ const batchSequence = screenshotBatchSequence;
+ screenshotBatchSequence += 1;
+ const captures = await Promise.all(
+ optionsList.map(async (options, index) => {
+ const output = getScreenshotOutputPath({
+ output: options.output,
+ now: startedAt,
+ format: options.format,
+ suffix: `-${batchSequence}-${index}`,
+ });
+ await dependencies.mkdir(dirname(output), { recursive: true });
+ return {
+ options,
+ output,
+ browserOptions: {
+ browserPath: resolvedBrowser.path,
+ output,
+ width: options.width,
+ height: options.height,
+ fullPage: options.fullPage,
+ includeImageMetrics: options.includeImageMetrics,
+ includeResourceMetrics: options.includeResourceMetrics,
+ url: options.url,
+ uid: dependencies.getuid(),
+ waitUntil: options.waitUntil ?? defaultScreenshotWaitUntil,
+ waitForSelector: options.waitForSelector,
+ waitForTimeout:
+ options.waitForTimeout ?? defaultScreenshotWaitForTimeout,
+ timeout: options.timeout ?? defaultScreenshotTimeout,
+ format: options.format,
+ quality: options.quality,
+ scale: options.scale,
+ },
+ };
+ })
+ );
+ browserSessionPromise ??= createBrowserScreenshotSession(
+ captures[0].browserOptions,
+ dependencies
+ );
+ browserSession ??= await browserSessionPromise;
+ const layouts = await browserSession.capturePage(
+ captures.map((capture) => capture.browserOptions)
+ );
+ return captures.map(({ options, output }, index) => {
+ const layout = layouts[index];
+ if (layout === undefined) {
+ throw new Error("Browser omitted a resized screenshot result.");
+ }
+ return {
+ output,
+ browser: resolvedBrowser,
+ viewport: { width: options.width, height: options.height },
+ fullPage: options.fullPage === true,
+ elapsedMs: layout.timings?.wallMs ?? 0,
+ warnings: [] as string[],
+ ...(layout.timings === undefined ? {} : { timings: layout.timings }),
+ ...(layout.navigation === undefined
+ ? {}
+ : { navigation: layout.navigation }),
+ layout,
+ };
+ });
+ },
+ async close() {
+ try {
+ browserSession ??= await browserSessionPromise?.catch(() => undefined);
+ await browserSession?.close();
+ } finally {
+ browserSession = undefined;
+ browserSessionPromise = undefined;
+ browserPromise = undefined;
+ }
+ },
+ };
+};
+
export const captureScreenshotWithBrowserInstall = async (
options: {
url: string;
diff --git a/packages/cli/templates/defaults/package.json b/packages/cli/templates/defaults/package.json
index 34a4fdbd21..aebac80a8c 100644
--- a/packages/cli/templates/defaults/package.json
+++ b/packages/cli/templates/defaults/package.json
@@ -27,7 +27,7 @@
"@remix-run/dev": "2.16.5",
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
- "typescript": "5.8.2",
+ "typescript": "7.0.2",
"vite": "^6.3.4"
},
"engines": {
diff --git a/packages/cli/templates/react-router/app/constants.mjs b/packages/cli/templates/react-router/app/constants.mjs
new file mode 100644
index 0000000000..5e5b0868e3
--- /dev/null
+++ b/packages/cli/templates/react-router/app/constants.mjs
@@ -0,0 +1,9 @@
+/**
+ * We use mjs because this file is shared with the generated build script.
+ */
+export const assetBaseUrl = "/assets/";
+
+/** @type {import("@webstudio-is/image").ImageLoader} */
+export const imageLoader = (props) => {
+ return props.src;
+};
diff --git a/packages/cli/templates/react-router/package.json b/packages/cli/templates/react-router/package.json
index fa611843de..7a5a97d0ce 100644
--- a/packages/cli/templates/react-router/package.json
+++ b/packages/cli/templates/react-router/package.json
@@ -30,7 +30,7 @@
"devDependencies": {
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
- "typescript": "5.8.2"
+ "typescript": "7.0.2"
},
"engines": {
"node": ">=22"
diff --git a/packages/cli/templates/ssg/package.json b/packages/cli/templates/ssg/package.json
index 4599325423..87a4f46d5b 100644
--- a/packages/cli/templates/ssg/package.json
+++ b/packages/cli/templates/ssg/package.json
@@ -23,7 +23,7 @@
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
"@vitejs/plugin-react": "^4.4.1",
- "typescript": "5.8.2",
+ "typescript": "7.0.2",
"vite": "^6.3.4"
},
"engines": {
diff --git a/packages/design-system/src/components/position-grid.tsx b/packages/design-system/src/components/position-grid.tsx
index ad957aef44..cdad200526 100644
--- a/packages/design-system/src/components/position-grid.tsx
+++ b/packages/design-system/src/components/position-grid.tsx
@@ -3,7 +3,7 @@ import { css, theme } from "../stitches.config";
import { Box } from "./box";
import { Grid } from "./grid";
-// prettier-ignore
+// oxfmt-ignore
const positions = [
[0, 0], [50, 0], [100, 0],
[0, 50], [50, 50], [100, 50],
diff --git a/packages/generate-arg-types/package.json b/packages/generate-arg-types/package.json
index 29a68542e9..4c38f755d8 100644
--- a/packages/generate-arg-types/package.json
+++ b/packages/generate-arg-types/package.json
@@ -13,12 +13,12 @@
"@webstudio-is/react-sdk": "workspace:*",
"@webstudio-is/sdk": "workspace:*",
"fast-glob": "^3.3.2",
- "react-docgen-typescript": "^2.2.2",
- "typescript": "5.8.2",
"zod": "^4.4.3"
},
"devDependencies": {
- "@webstudio-is/tsconfig": "workspace:*"
+ "@webstudio-is/tsconfig": "workspace:*",
+ "react-docgen-typescript": "2.2.2",
+ "typescript": "5.8.2"
},
"bin": {
"generate-arg-types": "./src/cli.ts"
diff --git a/packages/generate-arg-types/src/cli.ts b/packages/generate-arg-types/src/cli.ts
index 3778228e9b..8d3cf73b2e 100755
--- a/packages/generate-arg-types/src/cli.ts
+++ b/packages/generate-arg-types/src/cli.ts
@@ -52,7 +52,9 @@ if (componentFiles.length === 0) {
throw new Error("No component files found");
}
-// Create a parser with using your typescript config
+// TODO: Upgrade once https://github.com/styleguidist/react-docgen-typescript/issues/538 is resolved.
+// This private build-time tool stays on TypeScript 5 until react-docgen-typescript
+// supports the TypeScript 7 compiler API.
const tsConfigParser = withCustomConfig(tsConfigPath, options);
type ComponentNameType = string;
diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
index 66a4188007..9b4016b36f 100644
--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
@@ -16,7 +16,7 @@ export const runtimeOperationContractData = [
},
required: [],
},
- readNamespaces: ["pages", "projectSettings"],
+ readNamespaces: ["pages"],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
@@ -78,7 +78,7 @@ export const runtimeOperationContractData = [
},
title: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
parentFolderId: {
@@ -89,22 +89,22 @@ export const runtimeOperationContractData = [
properties: {
description: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
language: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
redirect: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
socialImageUrl: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
socialImageAssetId: {
@@ -117,7 +117,7 @@ export const runtimeOperationContractData = [
},
{
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
],
@@ -128,12 +128,12 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
status: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
auth: {
@@ -182,7 +182,7 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
},
@@ -232,7 +232,7 @@ export const runtimeOperationContractData = [
},
title: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
parentFolderId: {
@@ -243,22 +243,22 @@ export const runtimeOperationContractData = [
properties: {
description: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
language: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
redirect: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
socialImageUrl: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
socialImageAssetId: {
@@ -271,7 +271,7 @@ export const runtimeOperationContractData = [
},
{
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
],
@@ -282,12 +282,12 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
status: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
auth: {
@@ -336,7 +336,7 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
},
@@ -1074,9 +1074,14 @@ export const runtimeOperationContractData = [
inputSchema: {
type: "object",
properties: {
- sourceData: {},
+ sourceData: {
+ description:
+ "Required hydrated WebstudioData from the source project. This is a low-level cross-project transfer command; use duplicate-page to copy a page within the configured project.",
+ },
pageId: {
type: "string",
+ description:
+ "ID of the page in sourceData to copy into this project.",
},
parentFolderId: {
type: "string",
@@ -1086,7 +1091,7 @@ export const runtimeOperationContractData = [
enum: ["ours", "theirs", "merge"],
},
},
- required: ["pageId"],
+ required: ["sourceData", "pageId"],
},
readNamespaces: [
"pages",
@@ -1157,7 +1162,7 @@ export const runtimeOperationContractData = [
},
title: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
meta: {
@@ -1165,22 +1170,22 @@ export const runtimeOperationContractData = [
properties: {
description: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
language: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
redirect: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
socialImageUrl: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
socialImageAssetId: {
@@ -1193,7 +1198,7 @@ export const runtimeOperationContractData = [
},
{
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
],
@@ -1204,12 +1209,12 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
status: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
auth: {
@@ -1258,7 +1263,7 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
},
@@ -1330,7 +1335,7 @@ export const runtimeOperationContractData = [
},
title: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
meta: {
@@ -1338,22 +1343,22 @@ export const runtimeOperationContractData = [
properties: {
description: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
language: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
redirect: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
socialImageUrl: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
socialImageAssetId: {
@@ -1366,7 +1371,7 @@ export const runtimeOperationContractData = [
},
{
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
],
@@ -1377,12 +1382,12 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
status: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
auth: {
@@ -1431,7 +1436,7 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',
type: "string",
},
},
@@ -24041,7 +24046,7 @@ export const runtimeOperationContractData = [
properties: {
contractVersion: {
type: "number",
- const: 1,
+ const: 2,
},
projectVersion: {
type: "integer",
@@ -24176,6 +24181,237 @@ export const runtimeOperationContractData = [
minimum: 0,
maximum: 9007199254740991,
},
+ renderedPlan: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ version: {
+ type: "number",
+ const: 1,
+ },
+ pages: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ pagePath: {
+ type: "string",
+ },
+ },
+ required: ["pageId", "pagePath"],
+ },
+ },
+ excludedPages: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ pagePath: {
+ type: "string",
+ },
+ reason: {
+ type: "string",
+ const: "dynamic-route-needs-example",
+ },
+ },
+ required: ["pageId", "pagePath", "reason"],
+ },
+ },
+ viewports: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ width: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ height: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ purposes: {
+ minItems: 1,
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ },
+ required: ["width", "height", "purposes"],
+ },
+ },
+ checks: {
+ type: "array",
+ items: {
+ type: "string",
+ enum: [
+ "horizontal-overflow",
+ "broken-image",
+ "eager-below-fold-image",
+ "oversized-image",
+ "render-blocking-resource",
+ "legacy-font-format",
+ ],
+ },
+ },
+ captureCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ confirmationToken: {
+ type: "string",
+ },
+ confirmationExpiresAt: {
+ type: "string",
+ format: "date-time",
+ pattern:
+ "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$",
+ },
+ },
+ required: [
+ "version",
+ "pages",
+ "excludedPages",
+ "viewports",
+ "checks",
+ "captureCount",
+ ],
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ renderedCaptureSummary: {
+ type: "object",
+ properties: {
+ planned: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ passed: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ issues: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ skipped: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ failed: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["planned", "passed", "issues", "skipped", "failed"],
+ },
+ renderedCaptureStatuses: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ pagePath: {
+ type: "string",
+ },
+ viewport: {
+ type: "object",
+ properties: {
+ width: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ height: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["width", "height"],
+ },
+ status: {
+ type: "string",
+ enum: ["passed", "issues", "skipped", "failed"],
+ },
+ screenshotPath: {
+ type: "string",
+ },
+ failureCode: {
+ type: "string",
+ enum: [
+ "RENDERED_AUDIT_PREPARATION_FAILED",
+ "RENDERED_AUDIT_NO_STATIC_PAGES",
+ "RENDERED_AUDIT_CAPTURE_LIMIT_EXCEEDED",
+ "RENDERED_AUDIT_CONFIRMATION_REQUIRED",
+ "RENDERED_AUDIT_CONFIRMATION_INVALID",
+ "RENDERED_AUDIT_PREVIEW_START_FAILED",
+ "RENDERED_AUDIT_LAYOUT_METRICS_MISSING",
+ "RENDERED_AUDIT_HTTP_ERROR",
+ "RENDERED_AUDIT_NAVIGATION_EVIDENCE_MISSING",
+ "RENDERED_AUDIT_ORIGIN_MISMATCH",
+ "RENDERED_AUDIT_ROUTE_MISMATCH",
+ "RENDERED_AUDIT_DOCUMENT_NOT_GENERATED_SITE",
+ "RENDERED_AUDIT_LAYOUT_UNSTABLE",
+ "RENDERED_AUDIT_SCREENSHOT_FAILED",
+ "RENDERED_AUDIT_CAPTURE_TIMEOUT",
+ "RENDERED_AUDIT_PAGE_TIMEOUT",
+ "RENDERED_AUDIT_OVERALL_TIMEOUT",
+ "RENDERED_AUDIT_CANCELLED",
+ "RENDERED_AUDIT_PREVIEW_STOP_FAILED",
+ "RENDERED_AUDIT_ARTIFACT_WRITE_FAILED",
+ ],
+ },
+ },
+ required: ["pageId", "pagePath", "viewport", "status"],
+ },
+ },
+ renderedArtifactManifest: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ version: {
+ type: "number",
+ const: 1,
+ },
+ path: {
+ type: "string",
+ },
+ screenshotCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["version", "path", "screenshotCount"],
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
nextCursor: {
anyOf: [
{
@@ -24353,6 +24589,94 @@ export const runtimeOperationContractData = [
],
},
},
+ renderedIssueSummaries: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ kind: {
+ type: "string",
+ enum: [
+ "horizontal-overflow",
+ "broken-image",
+ "eager-below-fold-image",
+ "oversized-image",
+ "render-blocking-resource",
+ "legacy-font-format",
+ ],
+ },
+ count: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ captureCount: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ pagePaths: {
+ maxItems: 5,
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ },
+ required: ["kind", "count", "captureCount", "pagePaths"],
+ },
+ },
+ renderedFailureSummaries: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ code: {
+ type: "string",
+ enum: [
+ "RENDERED_AUDIT_PREPARATION_FAILED",
+ "RENDERED_AUDIT_NO_STATIC_PAGES",
+ "RENDERED_AUDIT_CAPTURE_LIMIT_EXCEEDED",
+ "RENDERED_AUDIT_CONFIRMATION_REQUIRED",
+ "RENDERED_AUDIT_CONFIRMATION_INVALID",
+ "RENDERED_AUDIT_PREVIEW_START_FAILED",
+ "RENDERED_AUDIT_LAYOUT_METRICS_MISSING",
+ "RENDERED_AUDIT_HTTP_ERROR",
+ "RENDERED_AUDIT_NAVIGATION_EVIDENCE_MISSING",
+ "RENDERED_AUDIT_ORIGIN_MISMATCH",
+ "RENDERED_AUDIT_ROUTE_MISMATCH",
+ "RENDERED_AUDIT_DOCUMENT_NOT_GENERATED_SITE",
+ "RENDERED_AUDIT_LAYOUT_UNSTABLE",
+ "RENDERED_AUDIT_SCREENSHOT_FAILED",
+ "RENDERED_AUDIT_CAPTURE_TIMEOUT",
+ "RENDERED_AUDIT_PAGE_TIMEOUT",
+ "RENDERED_AUDIT_OVERALL_TIMEOUT",
+ "RENDERED_AUDIT_CANCELLED",
+ "RENDERED_AUDIT_PREVIEW_STOP_FAILED",
+ "RENDERED_AUDIT_ARTIFACT_WRITE_FAILED",
+ ],
+ },
+ phase: {
+ type: "string",
+ enum: [
+ "planning",
+ "preview-start",
+ "capture",
+ "preview-stop",
+ ],
+ },
+ remediation: {
+ type: "string",
+ },
+ count: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["code", "phase", "remediation", "count"],
+ },
+ },
},
required: [
"contractVersion",
@@ -24365,9 +24689,15 @@ export const runtimeOperationContractData = [
"renderedCheckCount",
"renderedIssueCount",
"renderedFailureCount",
+ "renderedPlan",
+ "renderedCaptureSummary",
+ "renderedCaptureStatuses",
+ "renderedArtifactManifest",
"nextCursor",
"verbose",
"findings",
+ "renderedIssueSummaries",
+ "renderedFailureSummaries",
],
},
{
@@ -24375,7 +24705,7 @@ export const runtimeOperationContractData = [
properties: {
contractVersion: {
type: "number",
- const: 1,
+ const: 2,
},
projectVersion: {
type: "integer",
@@ -24510,6 +24840,237 @@ export const runtimeOperationContractData = [
minimum: 0,
maximum: 9007199254740991,
},
+ renderedPlan: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ version: {
+ type: "number",
+ const: 1,
+ },
+ pages: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ pagePath: {
+ type: "string",
+ },
+ },
+ required: ["pageId", "pagePath"],
+ },
+ },
+ excludedPages: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ pagePath: {
+ type: "string",
+ },
+ reason: {
+ type: "string",
+ const: "dynamic-route-needs-example",
+ },
+ },
+ required: ["pageId", "pagePath", "reason"],
+ },
+ },
+ viewports: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ width: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ height: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ purposes: {
+ minItems: 1,
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ },
+ required: ["width", "height", "purposes"],
+ },
+ },
+ checks: {
+ type: "array",
+ items: {
+ type: "string",
+ enum: [
+ "horizontal-overflow",
+ "broken-image",
+ "eager-below-fold-image",
+ "oversized-image",
+ "render-blocking-resource",
+ "legacy-font-format",
+ ],
+ },
+ },
+ captureCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ confirmationToken: {
+ type: "string",
+ },
+ confirmationExpiresAt: {
+ type: "string",
+ format: "date-time",
+ pattern:
+ "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$",
+ },
+ },
+ required: [
+ "version",
+ "pages",
+ "excludedPages",
+ "viewports",
+ "checks",
+ "captureCount",
+ ],
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ renderedCaptureSummary: {
+ type: "object",
+ properties: {
+ planned: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ passed: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ issues: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ skipped: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ failed: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["planned", "passed", "issues", "skipped", "failed"],
+ },
+ renderedCaptureStatuses: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ pagePath: {
+ type: "string",
+ },
+ viewport: {
+ type: "object",
+ properties: {
+ width: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ height: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["width", "height"],
+ },
+ status: {
+ type: "string",
+ enum: ["passed", "issues", "skipped", "failed"],
+ },
+ screenshotPath: {
+ type: "string",
+ },
+ failureCode: {
+ type: "string",
+ enum: [
+ "RENDERED_AUDIT_PREPARATION_FAILED",
+ "RENDERED_AUDIT_NO_STATIC_PAGES",
+ "RENDERED_AUDIT_CAPTURE_LIMIT_EXCEEDED",
+ "RENDERED_AUDIT_CONFIRMATION_REQUIRED",
+ "RENDERED_AUDIT_CONFIRMATION_INVALID",
+ "RENDERED_AUDIT_PREVIEW_START_FAILED",
+ "RENDERED_AUDIT_LAYOUT_METRICS_MISSING",
+ "RENDERED_AUDIT_HTTP_ERROR",
+ "RENDERED_AUDIT_NAVIGATION_EVIDENCE_MISSING",
+ "RENDERED_AUDIT_ORIGIN_MISMATCH",
+ "RENDERED_AUDIT_ROUTE_MISMATCH",
+ "RENDERED_AUDIT_DOCUMENT_NOT_GENERATED_SITE",
+ "RENDERED_AUDIT_LAYOUT_UNSTABLE",
+ "RENDERED_AUDIT_SCREENSHOT_FAILED",
+ "RENDERED_AUDIT_CAPTURE_TIMEOUT",
+ "RENDERED_AUDIT_PAGE_TIMEOUT",
+ "RENDERED_AUDIT_OVERALL_TIMEOUT",
+ "RENDERED_AUDIT_CANCELLED",
+ "RENDERED_AUDIT_PREVIEW_STOP_FAILED",
+ "RENDERED_AUDIT_ARTIFACT_WRITE_FAILED",
+ ],
+ },
+ },
+ required: ["pageId", "pagePath", "viewport", "status"],
+ },
+ },
+ renderedArtifactManifest: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ version: {
+ type: "number",
+ const: 1,
+ },
+ path: {
+ type: "string",
+ },
+ screenshotCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["version", "path", "screenshotCount"],
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
nextCursor: {
anyOf: [
{
@@ -24865,6 +25426,9 @@ export const runtimeOperationContractData = [
layout: {
type: "object",
properties: {
+ documentType: {
+ type: "string",
+ },
viewportWidth: {
type: "integer",
exclusiveMinimum: 0,
@@ -24896,6 +25460,9 @@ export const runtimeOperationContractData = [
instanceId: {
type: "string",
},
+ sourcePathname: {
+ type: "string",
+ },
loading: {
type: "string",
},
@@ -24910,6 +25477,14 @@ export const runtimeOperationContractData = [
type: "number",
minimum: 0,
},
+ selectedSourceWidth: {
+ type: "number",
+ minimum: 0,
+ },
+ selectedSourceHeight: {
+ type: "number",
+ minimum: 0,
+ },
renderedWidth: {
type: "number",
minimum: 0,
@@ -25015,6 +25590,9 @@ export const runtimeOperationContractData = [
instanceId: {
type: "string",
},
+ sourcePathname: {
+ type: "string",
+ },
loading: {
type: "string",
},
@@ -25026,6 +25604,14 @@ export const runtimeOperationContractData = [
type: "number",
minimum: 0,
},
+ selectedSourceWidth: {
+ type: "number",
+ minimum: 0,
+ },
+ selectedSourceHeight: {
+ type: "number",
+ minimum: 0,
+ },
renderedWidth: {
type: "number",
minimum: 0,
@@ -25116,6 +25702,46 @@ export const runtimeOperationContractData = [
items: {
type: "object",
properties: {
+ code: {
+ type: "string",
+ enum: [
+ "RENDERED_AUDIT_PREPARATION_FAILED",
+ "RENDERED_AUDIT_NO_STATIC_PAGES",
+ "RENDERED_AUDIT_CAPTURE_LIMIT_EXCEEDED",
+ "RENDERED_AUDIT_CONFIRMATION_REQUIRED",
+ "RENDERED_AUDIT_CONFIRMATION_INVALID",
+ "RENDERED_AUDIT_PREVIEW_START_FAILED",
+ "RENDERED_AUDIT_LAYOUT_METRICS_MISSING",
+ "RENDERED_AUDIT_HTTP_ERROR",
+ "RENDERED_AUDIT_NAVIGATION_EVIDENCE_MISSING",
+ "RENDERED_AUDIT_ORIGIN_MISMATCH",
+ "RENDERED_AUDIT_ROUTE_MISMATCH",
+ "RENDERED_AUDIT_DOCUMENT_NOT_GENERATED_SITE",
+ "RENDERED_AUDIT_LAYOUT_UNSTABLE",
+ "RENDERED_AUDIT_SCREENSHOT_FAILED",
+ "RENDERED_AUDIT_CAPTURE_TIMEOUT",
+ "RENDERED_AUDIT_PAGE_TIMEOUT",
+ "RENDERED_AUDIT_OVERALL_TIMEOUT",
+ "RENDERED_AUDIT_CANCELLED",
+ "RENDERED_AUDIT_PREVIEW_STOP_FAILED",
+ "RENDERED_AUDIT_ARTIFACT_WRITE_FAILED",
+ ],
+ },
+ phase: {
+ type: "string",
+ enum: [
+ "planning",
+ "preview-start",
+ "capture",
+ "preview-stop",
+ ],
+ },
+ retryable: {
+ type: "boolean",
+ },
+ remediation: {
+ type: "string",
+ },
pageId: {
type: "string",
},
@@ -25138,11 +25764,20 @@ export const runtimeOperationContractData = [
},
required: ["width", "height"],
},
+ screenshotPath: {
+ type: "string",
+ },
message: {
type: "string",
},
},
- required: ["message"],
+ required: [
+ "code",
+ "phase",
+ "retryable",
+ "remediation",
+ "message",
+ ],
},
},
},
@@ -25157,6 +25792,10 @@ export const runtimeOperationContractData = [
"renderedCheckCount",
"renderedIssueCount",
"renderedFailureCount",
+ "renderedPlan",
+ "renderedCaptureSummary",
+ "renderedCaptureStatuses",
+ "renderedArtifactManifest",
"nextCursor",
"verbose",
"findings",
@@ -25200,6 +25839,8 @@ export const runtimeOperationContractData = [
component: {
type: "string",
minLength: 1,
+ description:
+ 'Exact component id returned by components.search, components.get, or templates.get. Do not derive HTML shorthands such as "ws:div" or "ws:form". For a native HTML element, use "ws:element" and set "tag".',
},
tag: {
description:
@@ -31758,7 +32399,8 @@ export const runtimeOperationContractData = [
},
value: {
type: "string",
- description: "JavaScript expression source.",
+ description:
+ "One Webstudio JavaScript expression, not a statement or function. Read webstudio://project/expressions for syntax and scope rules.",
},
},
required: ["instanceId", "name", "type", "value"],
@@ -31841,7 +32483,7 @@ export const runtimeOperationContractData = [
},
required: ["updates"],
},
- readNamespaces: ["instances", "props"],
+ readNamespaces: ["instances", "props", "dataSources"],
writeNamespaces: ["props"],
invalidatesNamespaces: ["props"],
retryOnConflict: false,
@@ -31967,6 +32609,8 @@ export const runtimeOperationContractData = [
},
value: {
type: "string",
+ description:
+ "One Webstudio JavaScript expression. Read webstudio://project/expressions before using unfamiliar scope or syntax.",
},
},
required: ["type", "value"],
@@ -32103,7 +32747,7 @@ export const runtimeOperationContractData = [
text: {
type: "string",
description:
- "Replacement visible text when mode is text, or JavaScript expression source when mode is expression.",
+ "Replacement visible text when mode is text, or one Webstudio JavaScript expression when mode is expression. Read webstudio://project/expressions for syntax and scope rules.",
},
mode: {
description:
@@ -32114,7 +32758,7 @@ export const runtimeOperationContractData = [
},
required: ["instanceId", "childIndex", "text"],
},
- readNamespaces: ["instances"],
+ readNamespaces: ["instances", "dataSources"],
writeNamespaces: ["instances"],
invalidatesNamespaces: ["instances"],
retryOnConflict: true,
@@ -32186,7 +32830,8 @@ export const runtimeOperationContractData = [
},
text: {
type: "string",
- description: "Visible text or JavaScript expression source.",
+ description:
+ "Visible text, or one Webstudio JavaScript expression when mode is expression. Read webstudio://project/expressions for syntax and scope rules.",
},
mode: {
default: "text",
@@ -32214,7 +32859,7 @@ export const runtimeOperationContractData = [
},
],
},
- readNamespaces: ["instances"],
+ readNamespaces: ["instances", "dataSources"],
writeNamespaces: ["instances"],
invalidatesNamespaces: ["instances"],
retryOnConflict: true,
@@ -33147,6 +33792,8 @@ export const runtimeOperationContractData = [
},
styleSourceId: {
type: "string",
+ description:
+ "ID of an attached design token to duplicate. Local style sources cannot be duplicated; convert the local source to a design token first.",
},
},
required: ["instanceId", "styleSourceId"],
@@ -36394,7 +37041,7 @@ export const runtimeOperationContractData = [
},
],
description:
- 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
},
},
required: ["name", "value"],
@@ -36428,7 +37075,7 @@ export const runtimeOperationContractData = [
},
],
description:
- 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
},
},
required: ["name", "value"],
@@ -36454,7 +37101,7 @@ export const runtimeOperationContractData = [
},
],
description:
- 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
},
},
required: ["name", "method", "url", "headers"],
@@ -36465,6 +37112,11 @@ export const runtimeOperationContractData = [
dataSourceName: {
type: "string",
},
+ exposeAsDataSource: {
+ description:
+ "Expose the resource as render-time data. Scoped GET resources default to true; write resources default to false.",
+ type: "boolean",
+ },
},
required: ["resource"],
},
@@ -36575,7 +37227,7 @@ export const runtimeOperationContractData = [
},
],
description:
- 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
},
},
required: ["name", "value"],
@@ -36609,7 +37261,7 @@ export const runtimeOperationContractData = [
},
],
description:
- 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
},
},
required: ["name", "value"],
@@ -36635,7 +37287,7 @@ export const runtimeOperationContractData = [
},
],
description:
- 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
},
},
required: [],
@@ -36646,6 +37298,11 @@ export const runtimeOperationContractData = [
scopeInstanceId: {
type: "string",
},
+ exposeAsDataSource: {
+ description:
+ "Expose the resource as render-time data. Scoped GET resources default to true; write resources default to false.",
+ type: "boolean",
+ },
},
required: ["resourceId", "values"],
},
@@ -36813,7 +37470,7 @@ export const runtimeOperationContractData = [
},
],
description:
- 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
},
},
required: ["name", "value"],
@@ -36847,7 +37504,7 @@ export const runtimeOperationContractData = [
},
],
description:
- 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
},
},
required: ["name", "value"],
@@ -36873,7 +37530,7 @@ export const runtimeOperationContractData = [
},
],
description:
- 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
},
},
required: ["name", "method", "url", "headers"],
@@ -37003,7 +37660,7 @@ export const runtimeOperationContractData = [
},
],
description:
- 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
},
},
required: ["name", "value"],
@@ -37037,7 +37694,7 @@ export const runtimeOperationContractData = [
},
],
description:
- 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
},
},
required: ["name", "value"],
@@ -37063,7 +37720,7 @@ export const runtimeOperationContractData = [
},
],
description:
- 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.',
},
},
required: ["name", "method", "url", "headers"],
diff --git a/packages/project-build/src/contracts/builder-runtime.test.ts b/packages/project-build/src/contracts/builder-runtime.test.ts
index fc754924de..e05385c89d 100644
--- a/packages/project-build/src/contracts/builder-runtime.test.ts
+++ b/packages/project-build/src/contracts/builder-runtime.test.ts
@@ -81,7 +81,7 @@ describe("builder runtime operation contracts", () => {
expect(
runtimeOperationContracts.find((contract) => contract.id === "pages.list")
?.readNamespaces
- ).toEqual(["pages", "projectSettings"]);
+ ).toEqual(["pages"]);
});
test("derives required public input fields without generated ids", () => {
diff --git a/packages/project-build/src/contracts/namespaces.test.ts b/packages/project-build/src/contracts/namespaces.test.ts
index 07a7cea0d1..869601b2de 100644
--- a/packages/project-build/src/contracts/namespaces.test.ts
+++ b/packages/project-build/src/contracts/namespaces.test.ts
@@ -1,7 +1,19 @@
import { expect, test } from "vitest";
-import { builderNamespaces } from "./namespaces";
+import { builderNamespaces, webstudioDataNamespaces } from "./namespaces";
test("defines the shared builder namespace catalog", () => {
+ expect(webstudioDataNamespaces).toEqual([
+ "pages",
+ "instances",
+ "props",
+ "styles",
+ "styleSources",
+ "styleSourceSelections",
+ "dataSources",
+ "resources",
+ "assets",
+ "breakpoints",
+ ]);
expect(builderNamespaces).toEqual([
"pages",
"instances",
diff --git a/packages/project-build/src/contracts/namespaces.ts b/packages/project-build/src/contracts/namespaces.ts
index 19e5783dc2..b69f637754 100644
--- a/packages/project-build/src/contracts/namespaces.ts
+++ b/packages/project-build/src/contracts/namespaces.ts
@@ -8,7 +8,7 @@
* this list. Account, permission, deployment, domain, and other server-owned
* state must use a dedicated tRPC API instead of Builder patches.
*/
-export const builderNamespaces = [
+export const webstudioDataNamespaces = [
"pages",
"instances",
"props",
@@ -19,6 +19,12 @@ export const builderNamespaces = [
"resources",
"assets",
"breakpoints",
+] as const;
+
+export type WebstudioDataNamespace = (typeof webstudioDataNamespaces)[number];
+
+export const builderNamespaces = [
+ ...webstudioDataNamespaces,
"projectSettings",
"marketplaceProduct",
] as const;
diff --git a/packages/project-build/src/docs.generated.ts b/packages/project-build/src/docs.generated.ts
index 174cb66885..0a0edd4e29 100644
--- a/packages/project-build/src/docs.generated.ts
+++ b/packages/project-build/src/docs.generated.ts
@@ -3,6 +3,8 @@
export const projectBuildDocs = {
"accessibility-review":
'<!-- Adapted for Webstudio MCP from Community-Access/accessibility-agents, web-accessibility-wizard/SKILL.md (MIT): https://github.com/Community-Access/accessibility-agents/blob/main/codex-skills/web-accessibility-wizard/SKILL.md -->\n\n# Webstudio Accessibility Review\n\nUse this workflow when creating or reviewing a page, component, form, menu,\ndialog, or responsive layout. It is an LLM-assisted review, not proof of WCAG\nconformance. Do not claim that a page is accessible solely because this review\nhas no findings.\n\n## Evidence First\n\n1. Read `meta.index` and use focused project tools. Do not inspect Webstudio\n source code or generated files for normal project reviews.\n2. Run `audit` with `{"scopes":["accessibility"]}` before changing\n anything. It detects deterministic metadata issues such as labels, landmark\n structure, positive tabindex values, invalid static ARIA states, and unmuted\n autoplay. Fix confirmed static findings first.\n3. For each changed route, use `preview.start` and capture screenshots with\n `screenshot` at desktop, tablet, and mobile widths. Use `waitForSelector`\n or `waitForTimeout` only when the page has an actual delayed ready state.\n4. Use `get-page-by-path`, `list-instances`, `inspect-instance`, and focused\n prop/style reads to verify semantics and authored state that screenshots\n cannot prove.\n5. Make only supported, evidence-based fixes with semantic MCP tools. Recheck\n the affected route and the static accessibility search after every fix.\n\n## Review Areas\n\nReview these areas in priority order. Record the evidence for every finding.\n\n### 1. Names, Semantics, and Structure\n\n- Every image has purposeful alternative text or an explicitly empty alt when\n decorative. Image-submit inputs need a non-empty alt label describing their\n action.\n- For `missing-image-description` findings, inspect the rendered image in its\n page context and call `set-image-descriptions` with either a concise generated\n description or `decorative: true`. Re-run the audit after saving the decision.\n- Buttons, links, icon-only controls, and form controls have accessible names.\n- Prefer native HTML semantics over ARIA roles.\n- Non-native elements using `role="button"` or `role="link"` must be\n keyboard-focusable.\n- Use one sensible page h1, ordered heading levels, meaningful link text, and\n a main landmark.\n- Iframes have titles. Static HTML ids are unique, ARIA reference props point\n to real ids, and static boolean/select/numeric ARIA values are valid.\n- Focusable controls must not be hidden from assistive technology with\n `aria-hidden`.\n\n### 2. Keyboard and Focus\n\n- Interactive controls should be native or have a documented keyboard model.\n- Visible focus must not be removed without a visible replacement.\n- Hover-only information or controls need a keyboard-accessible equivalent.\n- Do not use positive tabindex values.\n- Mark keyboard behavior as **manual verification required** when the available\n evidence cannot prove tab order, Escape handling, or focus restoration.\n\n### 3. Dialogs, Menus, and Other Overlays\n\n- Dialogs need an accessible name and a close action.\n- Opening an overlay should move focus into it, trap focus where appropriate,\n and restore focus to its trigger on close.\n- Menus, popovers, disclosures, and tabs must expose their expanded/selected\n state and remain usable without a pointer.\n- If the current MCP/browser tools cannot exercise the interaction, report it\n as a manual verification item instead of guessing.\n\n### 4. Forms and Errors\n\n- Inputs have labels, required state, helpers, and errors associated with the\n right control.\n- Invalid controls expose `aria-invalid` when applicable.\n- Error, loading, and success feedback is not conveyed only by color or a\n transient visual toast.\n- Submit controls do not become unexplained dead ends when disabled.\n\n### 5. Visual, Responsive, Media, and Motion\n\n- At each target width, text remains readable, controls remain reachable, and\n no content is clipped, overlapped, or dependent on hover alone.\n- Do not rely only on color, position, shape, or iconography to convey meaning.\n- Keep non-text contrast, text contrast, focus indicators, and small text as\n visual review items unless measured evidence is available.\n- Videos with meaningful speech need captions; non-essential motion should\n respect reduced-motion preferences. Do not autoplay sound.\n\n### 6. Dynamic Content and Data\n\n- Loading, empty, error, and success states have understandable visible text.\n- Important dynamic updates and validation feedback need an appropriate\n announcement strategy.\n- Check repeated resource-driven content for unique labels, headings, ids, and\n meaningful empty states.\n\n## Findings and Fixes\n\nClassify every item as one of:\n\n- **Confirmed:** directly shown by `audit`, project data, or a rendered\n screenshot.\n- **Likely:** a credible issue inferred from rendered evidence; explain what\n would confirm it.\n- **Manual verification required:** needs keyboard, screen-reader, contrast, or\n interaction testing that the available tools cannot prove.\n\nFor each item include: severity (`critical`, `high`, `medium`, or `low`), page\npath, affected element or instance id when known, evidence, short user impact,\nand the smallest supported fix. Fix critical and high items first. Do not add\nARIA attributes, alt text, labels, or live regions when their meaning cannot be\nknown from the project; ask the user or report the missing context.\n\nFinish with a concise summary of fixed findings, remaining findings, and manual\nverification items. Use screenshots as evidence of the rendered state, not as\nproof of accessibility compliance.\n',
+ expressions:
+ '# Webstudio Expressions\n\nUse an expression only when a value must be computed at runtime from scoped\ndata. Use direct text and direct prop values for fixed content.\n\n## Source Format\n\nExpression-capable MCP fields receive JavaScript expression source as a JSON\nstring. Send one expression, without a `return` statement or surrounding\nfunction. For example:\n\n```json\n{ "binding": { "type": "expression", "value": "post.title ?? \\"Untitled\\"" } }\n```\n\nDo not send a fixed prop string as an expression. Use `update-props` with\n`type:"string"`. Page metadata and resource URLs accept plain fixed strings and\nnormalize them for storage. Expression-only resource headers, search parameters,\nand bodies accept `{ "type": "literal", "value": "fixed text" }` when the\nvalue is not dynamic.\n\n## Scope\n\n- Data variables are available on their scope instance and descendants.\n- An inner variable with the same name masks the outer variable.\n- A scoped resource result is a variable. Read its payload from its result\n wrapper, usually `resourceName.data`; APIs may nest the desired value deeper.\n- Collection creates internal `collectionItem` and `collectionItemKey`\n parameters. They are available only to that Collection\'s descendants.\n Preserve those generated parameters and do not reuse encoded parameter ids\n copied from another Collection.\n- Array Collection iteration exposes the current item. Object iteration exposes\n the current key and value.\n- The built-in `system` context is available only where supplied by the runtime.\n Its documented fields are `system.origin`, `system.pathname`, `system.params`,\n and `system.search`. There is no `system.path`.\n- Actions expose only their declared arguments, such as `event`, plus data that\n is in scope.\n\nRead `list-variables`, `list-resources`, `inspect-instance`, and existing\nbindings before writing an expression. Do not guess identifier names. Syntax is\nvalidated when a mutation is submitted, but an identifier that is unavailable\nat the final render scope may require preview verification to detect.\n\n## Supported Syntax\n\nExpressions support literals, arrays, objects, property and index access,\noptional chaining, unary and arithmetic operators, comparisons, logical\noperators, nullish coalescing, ternaries, and template literals.\n\nSupported string methods:\n\n{{allowedStringMethods}}\n\nSupported array methods:\n\n{{allowedArrayMethods}}\n\nOther values support `toString`. Arbitrary global functions and arbitrary\nmethod calls are not supported.\n\n## Unsupported Syntax\n\nDo not use statements, declarations, functions, arrow functions, classes,\n`new`, `this`, `await`, imports, tagged templates, sequence expressions,\nincrement/decrement, or destructuring assignment. Assignment is allowed only\ninside actions. Use an explicit assignment there rather than `++` or `--`.\n\n## Common Examples\n\n- Text: `post.title ?? "Untitled"`\n- Prop: `post.url`\n- Nested API array for Collection: `posts.data.items`\n- Resource URL: `"https://api.example.com/posts?tag=" + filters.tag`\n- Header: `"Bearer " + auth.token`\n- Search parameter: `String(filters.page ?? 1)` is not supported because global\n function calls are forbidden; use `(filters.page ?? 1).toString()` instead.\n- Resource body: `{ query: queryText, variables: { slug: system.params.slug } }`\n- Conditional: `featured ? "Featured" : "Standard"`\n- Safe nested access: `post.author?.name ?? "Unknown author"`\n\n## Collections\n\nWhenever an array or object should render repeated UI, insert `ws:collection`\nwith `insert-component` and bind its `data` prop to the complete iterable. Do\nnot bind the response wrapper or one indexed item. Collection renders its child\nstructure once per entry. Bind descendants with expressions such as\n`collectionItem.name`; for object iteration, `collectionItemKey` contains the\ncurrent key. See `components.get {"component":"ws:collection"}` for the\ncomplete workflow.\n\n## Verification\n\nAfter changing expressions, preview the affected page and verify representative\ndata, empty/null data, and Collection item counts. Use `audit` for relevant\nstructural findings, but do not treat a successful syntax parse as proof that\nruntime data has the expected shape.\n',
"mcp-startup-guidance":
'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output. Before editing a Webstudio project, do one small discovery step, then act. For delegated design-system or “use every component” tasks, the first MCP command is `workflow.next {"goal":"design-system-page"}`; report that returned checkpoint to the parent/user and stop until continued. For a simple authored/styled section, the intended path is literal: call `meta.index`, call `meta.get_more_tools` with `{"tools":["insert-fragment"]}`, read the target parent id with `list-pages`/`get-page-by-path`/`list-instances` only if needed, then call `insert-fragment`. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. Do not grep source files, dump full MCP resources, or write parser scripts before trying focused MCP calls. Good first calls are `meta.index` for orientation, `meta.guide` for a goal workflow, `workflow.next` for one bounded delegated phase, `meta.get_more_tools` for exact tool schemas, and `components.coverage-plan`, `components.coverage-insert-next`, `components.find`, or `components.get` for component work. Do not call every discovery tool up front. For delegated or non-streaming agents whose parent cannot see live stderr/stdout, treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report its command/result, and wait for the parent before the next MCP command. Do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands; they hide progress from the parent. Do not take a broad task such as creating a full design-system page as one execution unit. Instead call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint to the parent, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For design-system or “use every component” tasks, start with `workflow.next`, acknowledge its checkpoint only after parent/user continuation, then run compact `components.coverage-plan`, checkpoint, create the page, checkpoint, then call `components.coverage-insert-next` once per coverage checkpoint, and finish with the `presentation-pass` workflow phase. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world design-system examples instead of raw unstyled component dumps. Request component coverage details with `components.coverage-plan {"detail":"roots"}` or `components.coverage-plan {"detail":"parts"}` only when needed. `list-pages` does not accept `detail`; use `list-pages {}` or `get-page-by-path` for page lookup. Read overview resources such as `webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview` only when focused tools are insufficient. Do not dump or parse full resources such as `webstudio://project/tools` or `webstudio://project/components` unless the focused tools are insufficient. Run one-shot shortcut or explicit `webstudio mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. For experiments, pass `--dry-run` to local-capable mutations. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project. If a one-shot call returns checkpoint.required, the CLI persists `CHECKPOINT_REQUIRED` across later one-shot calls until you report the checkpoint, wait until continued, and call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially. Complete one bounded phase and return a checkpoint before continuing. Follow the guide: read ids and Builder breakpoints first, use focused component discovery for component ids, props, and content model composition, prefer semantic tools over `apply-patch`, use direct value tools for fixed text/props, use bindings only for dynamic expressions/resources/actions, page metadata and fixed resource URLs accept plain strings, put page/resource update fields under `values`, do not edit generated files for normal content/design changes, and use `preview.start` plus screenshot/vision for visual work.\n',
} as const;
diff --git a/packages/project-build/src/docs/expressions.md b/packages/project-build/src/docs/expressions.md
new file mode 100644
index 0000000000..ac984a9d76
--- /dev/null
+++ b/packages/project-build/src/docs/expressions.md
@@ -0,0 +1,97 @@
+# Webstudio Expressions
+
+Use an expression only when a value must be computed at runtime from scoped
+data. Use direct text and direct prop values for fixed content.
+
+## Source Format
+
+Expression-capable MCP fields receive JavaScript expression source as a JSON
+string. Send one expression, without a `return` statement or surrounding
+function. For example:
+
+```json
+{ "binding": { "type": "expression", "value": "post.title ?? \"Untitled\"" } }
+```
+
+Do not send a fixed prop string as an expression. Use `update-props` with
+`type:"string"`. Page metadata and resource URLs accept plain fixed strings and
+normalize them for storage. Expression-only resource headers, search parameters,
+and bodies accept `{ "type": "literal", "value": "fixed text" }` when the
+value is not dynamic.
+
+## Scope
+
+- Data variables are available on their scope instance and descendants.
+- An inner variable with the same name masks the outer variable.
+- A scoped resource result is a variable. Read its payload from its result
+ wrapper, usually `resourceName.data`; APIs may nest the desired value deeper.
+- Collection creates internal `collectionItem` and `collectionItemKey`
+ parameters. They are available only to that Collection's descendants.
+ Preserve those generated parameters and do not reuse encoded parameter ids
+ copied from another Collection.
+- Array Collection iteration exposes the current item. Object iteration exposes
+ the current key and value.
+- The built-in `system` context is available only where supplied by the runtime.
+ Its documented fields are `system.origin`, `system.pathname`, `system.params`,
+ and `system.search`. There is no `system.path`.
+- Actions expose only their declared arguments, such as `event`, plus data that
+ is in scope.
+
+Read `list-variables`, `list-resources`, `inspect-instance`, and existing
+bindings before writing an expression. Do not guess identifier names. Syntax is
+validated when a mutation is submitted, but an identifier that is unavailable
+at the final render scope may require preview verification to detect.
+
+## Supported Syntax
+
+Expressions support literals, arrays, objects, property and index access,
+optional chaining, unary and arithmetic operators, comparisons, logical
+operators, nullish coalescing, ternaries, and template literals.
+
+Supported string methods:
+
+{{allowedStringMethods}}
+
+Supported array methods:
+
+{{allowedArrayMethods}}
+
+Other values support `toString`. Arbitrary global functions and arbitrary
+method calls are not supported.
+
+## Unsupported Syntax
+
+Do not use statements, declarations, functions, arrow functions, classes,
+`new`, `this`, `await`, imports, tagged templates, sequence expressions,
+increment/decrement, or destructuring assignment. Assignment is allowed only
+inside actions. Use an explicit assignment there rather than `++` or `--`.
+
+## Common Examples
+
+- Text: `post.title ?? "Untitled"`
+- Prop: `post.url`
+- Nested API array for Collection: `posts.data.items`
+- Resource URL: `"https://api.example.com/posts?tag=" + filters.tag`
+- Header: `"Bearer " + auth.token`
+- Search parameter: `String(filters.page ?? 1)` is not supported because global
+ function calls are forbidden; use `(filters.page ?? 1).toString()` instead.
+- Resource body: `{ query: queryText, variables: { slug: system.params.slug } }`
+- Conditional: `featured ? "Featured" : "Standard"`
+- Safe nested access: `post.author?.name ?? "Unknown author"`
+
+## Collections
+
+Whenever an array or object should render repeated UI, insert `ws:collection`
+with `insert-component` and bind its `data` prop to the complete iterable. Do
+not bind the response wrapper or one indexed item. Collection renders its child
+structure once per entry. Bind descendants with expressions such as
+`collectionItem.name`; for object iteration, `collectionItemKey` contains the
+current key. See `components.get {"component":"ws:collection"}` for the
+complete workflow.
+
+## Verification
+
+After changing expressions, preview the affected page and verify representative
+data, empty/null data, and Collection item counts. Use `audit` for relevant
+structural findings, but do not treat a successful syntax parse as proof that
+runtime data has the expected shape.
diff --git a/packages/project-build/src/mcp-rendered-audit.test.ts b/packages/project-build/src/mcp-rendered-audit.test.ts
index 9fc3fe0531..c1e9bb5b4b 100644
--- a/packages/project-build/src/mcp-rendered-audit.test.ts
+++ b/packages/project-build/src/mcp-rendered-audit.test.ts
@@ -1,12 +1,18 @@
import { describe, expect, test, vi } from "vitest";
+import type { ProjectSessionScreenshotInput } from "./mcp";
import {
+ __testing__,
augmentAuditWithRenderedChecks,
+ getRenderedAuditOverallTimeout,
getRenderedAuditViewports,
getRenderedImageIssues,
getRenderedResourceIssues,
} from "./mcp-rendered-audit";
+const { mergeRenderedAudit } = __testing__;
+
const layout = {
+ documentType: "text/html",
viewportWidth: 375,
viewportHeight: 812,
contentWidth: 375,
@@ -16,26 +22,529 @@ const layout = {
resources: [],
};
+const getNavigation = (path: string) => ({
+ requestedUrl: `http://127.0.0.1:5177${path}`,
+ finalUrl: `http://127.0.0.1:5177${path}`,
+ status: 200,
+ statusText: "OK",
+ mimeType: "text/html",
+ redirects: [],
+ documentReadyState: "complete",
+ generatedSiteRootPresent: true,
+ layoutStable: true,
+});
+
describe("rendered audit evidence", () => {
- test("captures mobile, desktop, and both sides of breakpoint edges", () => {
+ test("budgets five minutes for each confirmed capture batch", () => {
+ expect(getRenderedAuditOverallTimeout(1)).toBe(5 * 60_000);
+ expect(getRenderedAuditOverallTimeout(120)).toBe(5 * 60_000);
+ expect(getRenderedAuditOverallTimeout(121)).toBe(10 * 60_000);
+ expect(getRenderedAuditOverallTimeout(396)).toBe(20 * 60_000);
+ expect(getRenderedAuditOverallTimeout(396, 1234)).toBe(1234);
+ });
+
+ test("matches the public root path to the stored empty home path", async () => {
+ const captureScreenshot = vi.fn(async (input) => ({
+ output: `/tmp/home-${input.viewport.width}.png`,
+ browserPath: "/usr/bin/chromium",
+ browser: "chromium" as const,
+ viewport: input.viewport,
+ fullPage: true,
+ elapsedMs: 10,
+ warnings: [],
+ navigation: getNavigation("/"),
+ layout,
+ }));
+ const result = await augmentAuditWithRenderedChecks({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: {
+ scopes: ["accessibility"],
+ manualCheckCount: 0,
+ verbose: true,
+ },
+ } as never,
+ input: { rendered: true, pagePath: "/", verbose: true },
+ executeRead: async (command) =>
+ ({
+ result:
+ command === "list-pages"
+ ? { pages: [{ id: "home", path: "" }] }
+ : { breakpoints: [] },
+ }) as never,
+ startPreview: vi.fn(),
+ stopPreview: vi.fn(),
+ captureScreenshot,
+ });
+
+ expect(captureScreenshot).toHaveBeenCalledOnce();
+ expect(result.result).toMatchObject({
+ renderedPlan: {
+ pages: [{ pageId: "home", pagePath: "/" }],
+ captureCount: 1,
+ },
+ renderedFailureCount: 0,
+ });
+ });
+
+ test("loads pages and breakpoints concurrently", async () => {
+ let activeReads = 0;
+ let maximumActiveReads = 0;
+ const executeRead = vi.fn(async (command: string) => {
+ activeReads += 1;
+ maximumActiveReads = Math.max(maximumActiveReads, activeReads);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ activeReads -= 1;
+ return {
+ result:
+ command === "list-pages"
+ ? { pages: [{ id: "home", path: "" }] }
+ : { breakpoints: [] },
+ } as never;
+ });
+
+ await augmentAuditWithRenderedChecks({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: {
+ scopes: ["accessibility"],
+ manualCheckCount: 0,
+ verbose: true,
+ },
+ } as never,
+ input: { rendered: true, verbose: true },
+ executeRead,
+ startPreview: vi.fn(),
+ stopPreview: vi.fn(),
+ captureScreenshot: vi.fn(async (input) => ({
+ output: "/tmp/home.png",
+ browserPath: "/usr/bin/chromium",
+ browser: "chromium" as const,
+ viewport: input.viewport,
+ fullPage: true,
+ elapsedMs: 10,
+ warnings: [],
+ navigation: getNavigation("/"),
+ layout,
+ })),
+ });
+
+ expect(maximumActiveReads).toBe(2);
+ });
+
+ test("captures each page once and resizes through its viewport plan", async () => {
+ const captureScreenshot = vi.fn();
+ const capturePageScreenshots = vi.fn(
+ async (inputs: readonly ProjectSessionScreenshotInput[]) =>
+ inputs.map((input) => ({
+ output: `/tmp/page-${input.viewport.width}.png`,
+ browserPath: "/usr/bin/chromium",
+ browser: "chromium" as const,
+ viewport: input.viewport,
+ fullPage: true,
+ elapsedMs: 10,
+ warnings: [],
+ timings: {
+ wallMs: 25,
+ targetSetupMs: 5,
+ navigationMs: 20,
+ readinessMs: 4,
+ imageInspectionMs: 3,
+ resourceInspectionMs: 1,
+ screenshotMs: 8,
+ artifactWriteMs: 2,
+ targetCleanupMs: input.viewport.width === 1440 ? 1 : 0,
+ },
+ navigation: getNavigation("/page"),
+ layout: {
+ ...layout,
+ viewportWidth: input.viewport.width,
+ viewportHeight: input.viewport.height,
+ },
+ }))
+ );
+ const storeRenderedAuditArtifacts = vi.fn(async () => "/manifest.json");
+
+ const result = await augmentAuditWithRenderedChecks({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: {
+ scopes: ["performance"],
+ manualCheckCount: 0,
+ verbose: true,
+ },
+ } as never,
+ input: { rendered: true, pagePath: "/page", verbose: true },
+ executeRead: async (command) =>
+ ({
+ result:
+ command === "list-pages"
+ ? { pages: [{ id: "page", path: "/page" }] }
+ : { breakpoints: [] },
+ }) as never,
+ startPreview: vi.fn(),
+ stopPreview: vi.fn(),
+ captureScreenshot,
+ capturePageScreenshots,
+ storeRenderedAuditArtifacts,
+ });
+
+ expect(capturePageScreenshots).toHaveBeenCalledOnce();
+ expect(capturePageScreenshots).toHaveBeenCalledWith([
+ expect.objectContaining({
+ path: "/page",
+ output: ".webstudio/audits/screenshots/page-1440x900.webp",
+ viewport: { width: 1440, height: 900 },
+ waitForTimeout: 0,
+ }),
+ ]);
+ expect(captureScreenshot).not.toHaveBeenCalled();
+ expect(result.result).toMatchObject({
+ renderedCheckCount: 1,
+ renderedFailureCount: 0,
+ });
+ expect(storeRenderedAuditArtifacts).toHaveBeenCalledWith(
+ expect.objectContaining({
+ screenshot: {
+ format: "webp",
+ quality: 82,
+ scale: 0.5,
+ },
+ performance: {
+ captureCount: 1,
+ previewStartMs: expect.any(Number),
+ captureWallMs: expect.any(Number),
+ previewStopMs: expect.any(Number),
+ targetSetupMs: 5,
+ navigationMs: 20,
+ readinessMs: 4,
+ imageInspectionMs: 3,
+ resourceInspectionMs: 1,
+ screenshotMs: 8,
+ artifactWriteMs: 2,
+ targetCleanupMs: 1,
+ },
+ })
+ );
+ });
+
+ test("falls back to isolated captures when resized page capture fails", async () => {
+ const capturePageScreenshots = vi.fn(async () => {
+ throw new Error("responsive script failed during resize");
+ });
+ const captureScreenshot = vi.fn(async (input) => ({
+ output: `/tmp/fallback-${input.viewport.width}.png`,
+ browserPath: "/usr/bin/chromium",
+ browser: "chromium" as const,
+ viewport: input.viewport,
+ fullPage: true,
+ elapsedMs: 10,
+ warnings: [],
+ navigation: getNavigation("/page"),
+ layout,
+ }));
+
+ const result = await augmentAuditWithRenderedChecks({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: {
+ scopes: ["accessibility"],
+ manualCheckCount: 0,
+ verbose: true,
+ },
+ } as never,
+ input: { rendered: true, pagePath: "/page", verbose: true },
+ executeRead: async (command) =>
+ ({
+ result:
+ command === "list-pages"
+ ? { pages: [{ id: "page", path: "/page" }] }
+ : { breakpoints: [] },
+ }) as never,
+ startPreview: vi.fn(),
+ stopPreview: vi.fn(),
+ captureScreenshot,
+ capturePageScreenshots,
+ });
+
+ expect(capturePageScreenshots).toHaveBeenCalledOnce();
+ expect(captureScreenshot).toHaveBeenCalledOnce();
+ expect(result.result).toMatchObject({
+ renderedCheckCount: 1,
+ renderedFailureCount: 0,
+ });
+ });
+
+ test("isolates a failed page without falling back healthy concurrent pages", async () => {
+ const pages = Array.from({ length: 7 }, (_, index) => ({
+ id: `page-${index}`,
+ path: index === 0 ? "/bad" : `/page-${index}`,
+ }));
+ const capturePageScreenshots = vi.fn(
+ async (inputs: readonly ProjectSessionScreenshotInput[]) => {
+ if (inputs.some((input) => input.path === "/bad")) {
+ throw new Error("bad page did not become ready");
+ }
+ return inputs.map((input) => {
+ const path = input.path ?? "/";
+ return {
+ output: `/tmp/${path.slice(1)}-${input.viewport.width}.webp`,
+ browserPath: "/usr/bin/chromium",
+ browser: "chromium" as const,
+ viewport: input.viewport,
+ fullPage: true,
+ elapsedMs: 1,
+ warnings: [],
+ navigation: getNavigation(path),
+ layout,
+ };
+ });
+ }
+ );
+ const captureScreenshot = vi.fn(async (input) => ({
+ output: `/tmp/bad-${input.viewport.width}.webp`,
+ browserPath: "/usr/bin/chromium",
+ browser: "chromium" as const,
+ viewport: input.viewport,
+ fullPage: true,
+ elapsedMs: 1,
+ warnings: [],
+ navigation: getNavigation("/bad"),
+ layout,
+ }));
+
+ const result = await augmentAuditWithRenderedChecks({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: {
+ scopes: ["accessibility"],
+ manualCheckCount: 0,
+ verbose: true,
+ },
+ } as never,
+ input: { rendered: true, verbose: true },
+ executeRead: async (command) =>
+ ({
+ result: command === "list-pages" ? { pages } : { breakpoints: [] },
+ }) as never,
+ startPreview: vi.fn(),
+ stopPreview: vi.fn(),
+ captureScreenshot,
+ capturePageScreenshots,
+ });
+
+ expect(capturePageScreenshots).toHaveBeenCalledTimes(7);
+ expect(captureScreenshot).toHaveBeenCalledOnce();
+ expect(captureScreenshot.mock.calls.map(([input]) => input.path)).toEqual([
+ "/bad",
+ ]);
+ expect(result.result).toMatchObject({
+ renderedCheckCount: 7,
+ renderedFailureCount: 0,
+ });
+ });
+
+ test("captures a common device viewport in each breakpoint range", () => {
expect(
getRenderedAuditViewports({
breakpoints: [
- { minWidth: 768 },
- { maxWidth: 991.5 },
- { minWidth: Number.NaN },
+ { label: "Base" },
+ { label: "Tablet", maxWidth: 991 },
+ { label: "Mobile landscape", maxWidth: 767 },
+ { label: "Mobile portrait", maxWidth: 479 },
+ { label: "Large", minWidth: 1280 },
+ { label: "Wide", minWidth: 1440 },
],
})
).toEqual([
- { width: 375, height: 812 },
- { width: 767, height: 900 },
- { width: 768, height: 900 },
- { width: 992, height: 900 },
- { width: 993, height: 900 },
- { width: 1440, height: 900 },
+ {
+ width: 390,
+ height: 844,
+ purposes: ["Mobile portrait: representative"],
+ },
+ {
+ width: 667,
+ height: 375,
+ purposes: ["Mobile landscape: representative"],
+ },
+ {
+ width: 820,
+ height: 1180,
+ purposes: ["Tablet: representative"],
+ },
+ {
+ width: 1024,
+ height: 768,
+ purposes: ["base breakpoint: representative"],
+ },
+ {
+ width: 1366,
+ height: 768,
+ purposes: ["Large: representative"],
+ },
+ {
+ width: 1440,
+ height: 900,
+ purposes: ["Wide: representative"],
+ },
+ ]);
+ });
+
+ test("uses a desktop viewport when the project only has a base breakpoint", () => {
+ expect(
+ getRenderedAuditViewports({
+ breakpoints: [{ id: "base", label: "Base" }],
+ })
+ ).toEqual([
+ {
+ width: 1440,
+ height: 900,
+ purposes: ["base breakpoint: desktop"],
+ },
]);
});
+ test("does not assign one capture failure to unrelated captures", () => {
+ const result = mergeRenderedAudit({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: {
+ scopes: ["accessibility"],
+ manualCheckCount: 0,
+ verbose: true,
+ },
+ } as never,
+ input: { rendered: true, verbose: true },
+ checks: [],
+ failures: [
+ {
+ code: "RENDERED_AUDIT_SCREENSHOT_FAILED",
+ phase: "capture",
+ retryable: true,
+ remediation: "Retry this capture.",
+ pageId: "one",
+ pagePath: "/one",
+ viewport: { width: 1440, height: 900 },
+ message: "Capture failed.",
+ },
+ ],
+ plan: {
+ version: 1,
+ pages: [
+ { pageId: "one", pagePath: "/one" },
+ { pageId: "two", pagePath: "/two" },
+ ],
+ excludedPages: [],
+ viewports: [
+ {
+ width: 1440,
+ height: 900,
+ purposes: ["base breakpoint: desktop"],
+ },
+ ],
+ checks: ["horizontal-overflow"],
+ captureCount: 2,
+ },
+ });
+
+ expect(result.result).toMatchObject({
+ renderedCaptureStatuses: [
+ {
+ pageId: "one",
+ status: "failed",
+ failureCode: "RENDERED_AUDIT_SCREENSHOT_FAILED",
+ },
+ { pageId: "two", status: "skipped" },
+ ],
+ });
+ expect(
+ (result.result as { renderedCaptureStatuses: Array<unknown> })
+ .renderedCaptureStatuses[1]
+ ).not.toHaveProperty("failureCode");
+ });
+
+ test("summarizes rendered issue kinds in compact results", () => {
+ const result = mergeRenderedAudit({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: {
+ scopes: ["performance"],
+ manualCheckCount: 0,
+ verbose: false,
+ },
+ } as never,
+ input: { rendered: true },
+ checks: [
+ {
+ pageId: "home",
+ pagePath: "/",
+ viewport: { width: 390, height: 844 },
+ issues: ["oversized-image", "oversized-image", "broken-image"],
+ },
+ {
+ pageId: "home",
+ pagePath: "/",
+ viewport: { width: 1440, height: 900 },
+ issues: ["oversized-image"],
+ },
+ ] as never,
+ failures: [],
+ });
+
+ expect(result.result).toMatchObject({
+ renderedIssueCount: 4,
+ renderedIssueSummaries: [
+ {
+ kind: "oversized-image",
+ count: 3,
+ captureCount: 2,
+ pagePaths: ["/"],
+ },
+ {
+ kind: "broken-image",
+ count: 1,
+ captureCount: 1,
+ pagePaths: ["/"],
+ },
+ ],
+ });
+ });
+
test("classifies broken, eager below-fold, and oversized images once", () => {
expect(
getRenderedImageIssues({
@@ -73,6 +582,43 @@ describe("rendered audit evidence", () => {
).toEqual(["broken-image", "eager-below-fold-image", "oversized-image"]);
});
+ test("uses the selected response bitmap dimensions for oversized images", () => {
+ const issues = getRenderedImageIssues({
+ ...layout,
+ images: [
+ {
+ loading: "lazy",
+ complete: true,
+ naturalWidth: 2000,
+ naturalHeight: 1200,
+ selectedSourceWidth: 400,
+ selectedSourceHeight: 240,
+ renderedWidth: 300,
+ renderedHeight: 180,
+ top: 0,
+ },
+ {
+ loading: "lazy",
+ complete: true,
+ naturalWidth: 300,
+ naturalHeight: 180,
+ selectedSourceWidth: 1600,
+ selectedSourceHeight: 960,
+ renderedWidth: 300,
+ renderedHeight: 180,
+ top: 0,
+ },
+ ],
+ });
+
+ expect(issues).toHaveLength(1);
+ expect(issues[0]).toMatchObject({
+ kind: "oversized-image",
+ selectedSourceWidth: 1600,
+ selectedSourceHeight: 960,
+ });
+ });
+
test("reports blocking resources and legacy font formats independently", () => {
expect(
getRenderedResourceIssues({
@@ -92,10 +638,57 @@ describe("rendered audit evidence", () => {
).toEqual(["render-blocking-resource", "legacy-font-format"]);
});
- test("rejects project-wide capture plans above the bounded limit", async () => {
- const startPreview = vi.fn();
- const stopPreview = vi.fn();
- const captureScreenshot = vi.fn();
+ test("does not report vector sizing or an eager source already used above the fold", () => {
+ expect(
+ getRenderedImageIssues({
+ ...layout,
+ images: [
+ {
+ sourcePathname: "/assets/mark.svg",
+ loading: "eager",
+ complete: true,
+ naturalWidth: 280,
+ naturalHeight: 280,
+ renderedWidth: 30,
+ renderedHeight: 30,
+ top: 10,
+ },
+ {
+ sourcePathname: "/assets/mark.svg",
+ loading: "eager",
+ complete: true,
+ naturalWidth: 280,
+ naturalHeight: 280,
+ renderedWidth: 30,
+ renderedHeight: 30,
+ top: 900,
+ },
+ ],
+ })
+ ).toEqual([]);
+ });
+
+ test("does not report the generated application stylesheet", () => {
+ expect(
+ getRenderedResourceIssues({
+ ...layout,
+ resources: [
+ {
+ pathname: "/assets/index-DIEIbGZp.css",
+ initiatorType: "link",
+ transferSize: 10,
+ encodedBodySize: 8,
+ decodedBodySize: 12,
+ duration: 5,
+ renderBlockingStatus: "blocking",
+ },
+ ],
+ })
+ ).toEqual([]);
+ });
+
+ test("classifies an HTTP error capture as failed rendered evidence", async () => {
+ const storeRenderedAuditArtifacts = vi.fn(async () => "/manifest.json");
const result = await augmentAuditWithRenderedChecks({
envelope: {
operationId: "project.audit",
@@ -105,42 +698,374 @@ describe("rendered audit evidence", () => {
version: 1,
committed: false,
result: {
- scopes: ["accessibility"],
- manualCheckCount: 1,
+ scopes: ["performance"],
+ manualCheckCount: 0,
+ verbose: true,
},
} as never,
- input: { rendered: true, verbose: true },
+ input: { rendered: true, pagePath: "/missing", verbose: true },
executeRead: async (command) =>
({
- operationId:
- command === "list-pages" ? "pages.list" : "breakpoints.list",
- source: "remote",
- projectId: "project",
- buildId: "build",
- version: 1,
- committed: false,
result:
command === "list-pages"
- ? {
- pages: Array.from({ length: 61 }, (_, index) => ({
- id: `page-${index}`,
- path: `/page-${index}`,
- })),
- }
+ ? { pages: [{ id: "missing", path: "/missing" }] }
: { breakpoints: [] },
}) as never,
- startPreview,
- stopPreview,
- captureScreenshot,
+ startPreview: vi.fn(),
+ stopPreview: vi.fn(),
+ captureScreenshot: vi.fn(async () => ({
+ output: "/tmp/missing.png",
+ browserPath: "/usr/bin/chromium",
+ browser: "chromium" as const,
+ viewport: { width: 375, height: 812 },
+ fullPage: true,
+ elapsedMs: 10,
+ warnings: [],
+ navigation: {
+ requestedUrl: "http://127.0.0.1:5177/missing",
+ finalUrl: "http://127.0.0.1:5177/missing",
+ status: 404,
+ statusText: "Not Found",
+ mimeType: "text/html",
+ redirects: [],
+ documentReadyState: "complete",
+ generatedSiteRootPresent: true,
+ layoutStable: true,
+ },
+ layout,
+ })),
+ storeRenderedAuditArtifacts,
});
expect(result.result).toMatchObject({
renderedCheckCount: 0,
renderedFailureCount: 1,
+ renderedCaptureSummary: {
+ planned: 1,
+ passed: 0,
+ issues: 0,
+ skipped: 0,
+ failed: 1,
+ },
+ renderedCaptureStatuses: [
+ expect.objectContaining({
+ pagePath: "/missing",
+ status: "failed",
+ screenshotPath: "/tmp/missing.png",
+ failureCode: "RENDERED_AUDIT_HTTP_ERROR",
+ }),
+ ],
+ renderedFailures: [
+ expect.objectContaining({
+ code: "RENDERED_AUDIT_HTTP_ERROR",
+ pagePath: "/missing",
+ message: expect.stringContaining("HTTP 404"),
+ }),
+ ],
+ renderedArtifactManifest: {
+ version: 1,
+ path: "/manifest.json",
+ screenshotCount: 1,
+ },
+ });
+ expect(storeRenderedAuditArtifacts).toHaveBeenCalledWith(
+ expect.objectContaining({
+ failures: [
+ expect.objectContaining({ screenshotPath: "/tmp/missing.png" }),
+ ],
+ })
+ );
+ });
+
+ test("accepts an intentional generated redirect", async () => {
+ const result = await augmentAuditWithRenderedChecks({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: {
+ scopes: ["accessibility"],
+ manualCheckCount: 0,
+ verbose: true,
+ },
+ } as never,
+ input: { rendered: true, pagePath: "/old", verbose: true },
+ executeRead: async (command) =>
+ ({
+ result:
+ command === "list-pages"
+ ? { pages: [{ id: "old", path: "/old" }] }
+ : { breakpoints: [] },
+ }) as never,
+ startPreview: vi.fn(),
+ stopPreview: vi.fn(),
+ captureScreenshot: vi.fn(async (input) => ({
+ output: `/tmp/redirect-${input.viewport.width}.png`,
+ browserPath: "/usr/bin/chromium",
+ browser: "chromium" as const,
+ viewport: input.viewport,
+ fullPage: true,
+ elapsedMs: 10,
+ warnings: [],
+ navigation: {
+ ...getNavigation("/new"),
+ requestedUrl: "http://127.0.0.1:5177/old",
+ redirects: ["http://127.0.0.1:5177/old"],
+ },
+ layout,
+ })),
+ });
+
+ expect(result.result).toMatchObject({
+ renderedCheckCount: 1,
+ renderedFailureCount: 0,
+ renderedCaptureSummary: {
+ planned: 1,
+ passed: 1,
+ issues: 0,
+ skipped: 0,
+ failed: 0,
+ },
+ });
+ });
+
+ test("accepts a generated non-HTML document without an HTML marker", async () => {
+ const result = await augmentAuditWithRenderedChecks({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: {
+ scopes: ["accessibility"],
+ manualCheckCount: 0,
+ verbose: true,
+ },
+ } as never,
+ input: { rendered: true, pagePath: "/sitemap.xml", verbose: true },
+ executeRead: async (command) =>
+ ({
+ result:
+ command === "list-pages"
+ ? { pages: [{ id: "sitemap", path: "/sitemap.xml" }] }
+ : { breakpoints: [] },
+ }) as never,
+ startPreview: vi.fn(),
+ stopPreview: vi.fn(),
+ captureScreenshot: vi.fn(async (input) => ({
+ output: `/tmp/sitemap-${input.viewport.width}.png`,
+ browserPath: "/usr/bin/chromium",
+ browser: "chromium" as const,
+ viewport: input.viewport,
+ fullPage: true,
+ elapsedMs: 10,
+ warnings: [],
+ navigation: {
+ ...getNavigation("/sitemap.xml"),
+ mimeType: "application/xml",
+ generatedSiteRootPresent: false,
+ },
+ layout: { ...layout, documentType: "application/xml" },
+ })),
+ });
+
+ expect(result.result).toMatchObject({
+ renderedCheckCount: 1,
+ renderedFailureCount: 0,
+ renderedCaptureSummary: {
+ planned: 1,
+ passed: 1,
+ issues: 0,
+ skipped: 0,
+ failed: 0,
+ },
+ });
+ });
+
+ test("classifies bounded capture timeouts and preserves reconciliation", async () => {
+ const result = await augmentAuditWithRenderedChecks({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: {
+ scopes: ["accessibility"],
+ manualCheckCount: 1,
+ verbose: true,
+ },
+ } as never,
+ input: { rendered: true, pagePath: "/slow", verbose: true },
+ executeRead: async (command) =>
+ ({
+ result:
+ command === "list-pages"
+ ? { pages: [{ id: "slow", path: "/slow" }] }
+ : { breakpoints: [] },
+ }) as never,
+ startPreview: vi.fn(),
+ stopPreview: vi.fn(),
+ captureScreenshot: vi.fn(
+ async (): Promise<never> => await new Promise<never>(() => {})
+ ),
+ timeouts: { capture: 5 },
+ });
+
+ expect(result.result).toMatchObject({
+ renderedCheckCount: 0,
+ renderedFailureCount: 1,
+ renderedCaptureSummary: {
+ planned: 1,
+ passed: 0,
+ issues: 0,
+ skipped: 0,
+ failed: 1,
+ },
+ renderedFailures: [
+ expect.objectContaining({ code: "RENDERED_AUDIT_CAPTURE_TIMEOUT" }),
+ ],
+ });
+ });
+
+ test("does not retry an unresolved resized capture after its timeout", async () => {
+ const captureScreenshot = vi.fn();
+ const result = await augmentAuditWithRenderedChecks({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: { scopes: ["performance"], manualCheckCount: 0, verbose: true },
+ } as never,
+ input: { rendered: true, pagePath: "/slow", verbose: true },
+ executeRead: async (command) =>
+ ({
+ result:
+ command === "list-pages"
+ ? { pages: [{ id: "slow", path: "/slow" }] }
+ : { breakpoints: [] },
+ }) as never,
+ startPreview: vi.fn(),
+ stopPreview: vi.fn(),
+ captureScreenshot,
+ capturePageScreenshots: vi.fn(
+ async (): Promise<never> => await new Promise<never>(() => {})
+ ),
+ timeouts: { page: 5 },
+ });
+
+ expect(captureScreenshot).not.toHaveBeenCalled();
+ expect(result.result).toMatchObject({
+ renderedFailureCount: 1,
+ renderedCaptureSummary: { planned: 1, failed: 1 },
+ renderedFailures: [
+ expect.objectContaining({ code: "RENDERED_AUDIT_CAPTURE_TIMEOUT" }),
+ ],
+ });
+ });
+
+ test("requires and consumes confirmation for a large unchanged plan", async () => {
+ const startPreview = vi.fn();
+ const stopPreview = vi.fn();
+ const captureScreenshot = vi.fn(async (input) => ({
+ output: `/tmp/${input.path}-${input.viewport.width}.png`,
+ browserPath: "/browser",
+ browser: "chromium" as const,
+ viewport: input.viewport,
+ fullPage: true,
+ elapsedMs: 1,
+ warnings: [],
+ navigation: getNavigation(input.path ?? "/"),
+ layout: {
+ ...layout,
+ viewportWidth: input.viewport.width,
+ viewportHeight: input.viewport.height,
+ },
+ }));
+ const envelope = {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: {
+ scopes: ["accessibility"],
+ manualCheckCount: 1,
+ },
+ } as never;
+ const executeRead = async (command: "list-pages" | "list-breakpoints") =>
+ ({
+ operationId:
+ command === "list-pages" ? "pages.list" : "breakpoints.list",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result:
+ command === "list-pages"
+ ? {
+ pages: Array.from({ length: 122 }, (_, index) => ({
+ id: `page-${index}`,
+ path: `/page-${index}`,
+ })),
+ }
+ : { breakpoints: [] },
+ }) as never;
+ const result = await augmentAuditWithRenderedChecks({
+ envelope,
+ input: { rendered: true, verbose: true },
+ executeRead,
+ startPreview,
+ stopPreview,
+ captureScreenshot,
+ });
+
+ expect(result.result).toMatchObject({
+ renderedPlan: {
+ version: 1,
+ pages: expect.arrayContaining([
+ { pageId: "page-0", pagePath: "/page-0" },
+ ]),
+ excludedPages: [],
+ viewports: [
+ expect.objectContaining({
+ width: 1440,
+ purposes: ["base breakpoint: desktop"],
+ }),
+ ],
+ checks: ["horizontal-overflow"],
+ captureCount: 122,
+ confirmationToken: expect.any(String),
+ confirmationExpiresAt: expect.any(String),
+ },
+ renderedCheckCount: 0,
+ renderedFailureCount: 1,
+ renderedCaptureSummary: {
+ planned: 122,
+ passed: 0,
+ issues: 0,
+ skipped: 122,
+ failed: 0,
+ },
renderedFailures: [
{
+ code: "RENDERED_AUDIT_CONFIRMATION_REQUIRED",
+ phase: "planning",
+ retryable: false,
+ remediation: expect.stringContaining("confirmLargeRun"),
message: expect.stringContaining(
- "122 screenshots, exceeding the 120-screenshot limit"
+ "122 screenshots, exceeding the 120-screenshot unconfirmed threshold"
),
},
],
@@ -148,5 +1073,358 @@ describe("rendered audit evidence", () => {
expect(startPreview).not.toHaveBeenCalled();
expect(stopPreview).not.toHaveBeenCalled();
expect(captureScreenshot).not.toHaveBeenCalled();
+
+ const plan = (result.result as Record<string, unknown>)
+ .renderedPlan as Record<string, unknown>;
+ const confirmed = await augmentAuditWithRenderedChecks({
+ envelope,
+ input: {
+ rendered: true,
+ verbose: true,
+ confirmLargeRun: true,
+ confirmationToken: plan.confirmationToken,
+ },
+ executeRead,
+ startPreview,
+ stopPreview,
+ captureScreenshot,
+ });
+
+ expect(confirmed.result).toMatchObject({
+ renderedCheckCount: 122,
+ renderedFailureCount: 0,
+ renderedCaptureSummary: {
+ planned: 122,
+ passed: 122,
+ issues: 0,
+ skipped: 0,
+ failed: 0,
+ },
+ });
+ expect(startPreview).toHaveBeenCalledOnce();
+ expect(stopPreview).toHaveBeenCalledOnce();
+ expect(captureScreenshot).toHaveBeenCalledTimes(122);
+
+ const secondPlan = await augmentAuditWithRenderedChecks({
+ envelope,
+ input: { rendered: true, verbose: true },
+ executeRead,
+ startPreview,
+ stopPreview,
+ captureScreenshot,
+ });
+ const secondToken = (
+ (secondPlan.result as Record<string, unknown>).renderedPlan as Record<
+ string,
+ unknown
+ >
+ ).confirmationToken;
+ const stale = await augmentAuditWithRenderedChecks({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 2,
+ committed: false,
+ result: {
+ scopes: ["accessibility"],
+ manualCheckCount: 1,
+ },
+ } as never,
+ input: {
+ rendered: true,
+ verbose: true,
+ confirmLargeRun: true,
+ confirmationToken: secondToken,
+ },
+ executeRead,
+ startPreview,
+ stopPreview,
+ captureScreenshot,
+ });
+ expect(stale.result).toMatchObject({
+ renderedCheckCount: 0,
+ renderedFailures: [
+ expect.objectContaining({
+ code: "RENDERED_AUDIT_CONFIRMATION_INVALID",
+ }),
+ ],
+ });
+ expect(startPreview).toHaveBeenCalledOnce();
+ });
+
+ test("explains excluded dynamic routes without starting preview", async () => {
+ const startPreview = vi.fn();
+ const result = await augmentAuditWithRenderedChecks({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: {
+ scopes: ["performance"],
+ manualCheckCount: 1,
+ verbose: false,
+ },
+ } as never,
+ input: { rendered: true, pagePath: "/blog/:slug" },
+ executeRead: async (command) =>
+ ({
+ operationId:
+ command === "list-pages" ? "pages.list" : "breakpoints.list",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result:
+ command === "list-pages"
+ ? { pages: [{ id: "post", path: "/blog/:slug" }] }
+ : { breakpoints: [{ id: "tablet", maxWidth: 991 }] },
+ }) as never,
+ startPreview,
+ stopPreview: vi.fn(),
+ captureScreenshot: vi.fn(),
+ });
+
+ expect(result.result).toMatchObject({
+ renderedPlan: {
+ pages: [],
+ excludedPages: [
+ {
+ pageId: "post",
+ pagePath: "/blog/:slug",
+ reason: "dynamic-route-needs-example",
+ },
+ ],
+ viewports: expect.arrayContaining([
+ expect.objectContaining({
+ width: 390,
+ purposes: ["tablet: representative"],
+ }),
+ ]),
+ checks: [
+ "horizontal-overflow",
+ "broken-image",
+ "eager-below-fold-image",
+ "oversized-image",
+ "render-blocking-resource",
+ "legacy-font-format",
+ ],
+ captureCount: 0,
+ },
+ renderedFailureCount: 1,
+ renderedFailureSummaries: [
+ expect.objectContaining({ code: "RENDERED_AUDIT_NO_STATIC_PAGES" }),
+ ],
+ });
+ expect(startPreview).not.toHaveBeenCalled();
+ });
+
+ test("stops scheduling captures and cleans up when the caller cancels", async () => {
+ const controller = new AbortController();
+ const startPreview = vi.fn();
+ const stopPreview = vi.fn();
+ const captureScreenshot = vi.fn(() => {
+ controller.abort();
+ return new Promise<never>(() => undefined);
+ });
+ const result = await augmentAuditWithRenderedChecks({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: {
+ scopes: ["performance"],
+ manualCheckCount: 0,
+ verbose: true,
+ },
+ } as never,
+ input: { rendered: true, verbose: true },
+ executeRead: async (command) =>
+ ({
+ result:
+ command === "list-pages"
+ ? { pages: [{ id: "home", path: "/" }] }
+ : { breakpoints: [] },
+ }) as never,
+ startPreview,
+ stopPreview,
+ captureScreenshot,
+ signal: controller.signal,
+ });
+
+ expect(result.result).toMatchObject({
+ renderedCheckCount: 0,
+ renderedCaptureSummary: {
+ planned: 1,
+ skipped: 1,
+ failed: 0,
+ },
+ renderedFailures: [
+ expect.objectContaining({ code: "RENDERED_AUDIT_CANCELLED" }),
+ ],
+ });
+ expect(startPreview).toHaveBeenCalledOnce();
+ expect(captureScreenshot).toHaveBeenCalledOnce();
+ expect(stopPreview).toHaveBeenCalledOnce();
+ });
+
+ test("captures a caller-supplied concrete example for a dynamic route", async () => {
+ const storeRenderedAuditArtifacts = vi.fn(
+ async () => "/project/.webstudio/audits/rendered-project-1.json"
+ );
+ const captureScreenshot = vi.fn(async (input) => ({
+ output: `/tmp/post-${input.viewport.width}.png`,
+ browserPath: "/browser",
+ browser: "chromium" as const,
+ viewport: input.viewport,
+ fullPage: true,
+ elapsedMs: 1,
+ warnings: [],
+ navigation: getNavigation(input.path ?? "/"),
+ layout: {
+ ...layout,
+ viewportWidth: input.viewport.width,
+ viewportHeight: input.viewport.height,
+ },
+ }));
+ const result = await augmentAuditWithRenderedChecks({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: {
+ scopes: ["accessibility"],
+ manualCheckCount: 1,
+ verbose: true,
+ },
+ } as never,
+ input: {
+ rendered: true,
+ verbose: true,
+ pageId: "post",
+ routeExamples: [{ pageId: "post", path: "/blog/hello?draft=1" }],
+ },
+ executeRead: async (command) =>
+ ({
+ result:
+ command === "list-pages"
+ ? { pages: [{ id: "post", path: "/blog/:slug" }] }
+ : { breakpoints: [] },
+ }) as never,
+ startPreview: vi.fn(),
+ stopPreview: vi.fn(),
+ captureScreenshot,
+ storeRenderedAuditArtifacts,
+ });
+
+ expect(captureScreenshot).toHaveBeenCalledOnce();
+ expect(captureScreenshot).toHaveBeenCalledWith(
+ expect.objectContaining({ path: "/blog/hello?draft=1" })
+ );
+ expect(result.result).toMatchObject({
+ renderedPlan: {
+ pages: [{ pageId: "post", pagePath: "/blog/hello?draft=1" }],
+ excludedPages: [],
+ captureCount: 1,
+ },
+ renderedCaptureSummary: {
+ planned: 1,
+ passed: 1,
+ issues: 0,
+ skipped: 0,
+ failed: 0,
+ },
+ renderedArtifactManifest: {
+ version: 1,
+ path: "/project/.webstudio/audits/rendered-project-1.json",
+ screenshotCount: 1,
+ },
+ });
+ expect(storeRenderedAuditArtifacts).toHaveBeenCalledWith(
+ expect.objectContaining({
+ version: 1,
+ auditContractVersion: 2,
+ projectId: "project",
+ projectVersion: 1,
+ captureStatuses: [
+ expect.objectContaining({
+ pagePath: "/blog/hello?draft=1",
+ screenshotPath: "/tmp/post-1440.png",
+ }),
+ ],
+ checks: [
+ expect.objectContaining({
+ screenshotPath: "/tmp/post-1440.png",
+ layout: expect.objectContaining({
+ navigation: expect.objectContaining({
+ finalUrl: "http://127.0.0.1:5177/blog/hello?draft=1",
+ status: 200,
+ generatedSiteRootPresent: true,
+ }),
+ }),
+ }),
+ ],
+ failures: [],
+ })
+ );
+ });
+
+ test("treats empty and slash home paths as the same rendered page", async () => {
+ const captureScreenshot = vi.fn(async (input) => ({
+ output: "/tmp/home.webp",
+ browserPath: "/browser",
+ browser: "chromium" as const,
+ viewport: input.viewport,
+ fullPage: true,
+ elapsedMs: 1,
+ warnings: [],
+ navigation: getNavigation(input.path ?? "/"),
+ layout,
+ }));
+
+ const result = await augmentAuditWithRenderedChecks({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: { scopes: ["accessibility"], manualCheckCount: 1 },
+ } as never,
+ input: { rendered: true, pagePath: "" },
+ executeRead: async (command) =>
+ ({
+ result:
+ command === "list-pages"
+ ? { pages: [{ id: "home", path: "" }] }
+ : { breakpoints: [] },
+ }) as never,
+ startPreview: vi.fn(),
+ stopPreview: vi.fn(),
+ captureScreenshot,
+ });
+
+ expect(captureScreenshot).toHaveBeenCalledWith(
+ expect.objectContaining({ path: "/" })
+ );
+ expect(result.result).toMatchObject({
+ renderedPlan: {
+ pages: [{ pageId: "home", pagePath: "/" }],
+ captureCount: 1,
+ },
+ renderedCaptureSummary: { passed: 1, failed: 0 },
+ });
});
});
diff --git a/packages/project-build/src/mcp-rendered-audit.ts b/packages/project-build/src/mcp-rendered-audit.ts
index 0fae03a4e7..51210c3767 100644
--- a/packages/project-build/src/mcp-rendered-audit.ts
+++ b/packages/project-build/src/mcp-rendered-audit.ts
@@ -1,15 +1,29 @@
import type { ProjectSessionEnvelope } from "./project-session";
-import type { RenderedAuditCheck, RenderedAuditFailure } from "./runtime/audit";
+import type {
+ RenderedAuditCheck,
+ RenderedAuditFailure,
+ renderedAuditPlan,
+} from "./runtime/audit";
+import {
+ auditContractVersion,
+ renderedAuditManifestVersion,
+} from "./runtime/audit";
+import type { z } from "zod";
import { isRecord } from "./shared/type-utils";
import type {
ProjectSessionScreenshotInput,
ProjectSessionScreenshotResult,
} from "./mcp";
-type Viewport = { width: number; height: number };
+type Viewport = { width: number; height: number; purposes: string[] };
+type RenderedAuditPlan = z.infer<typeof renderedAuditPlan>;
type RenderedAuditInput = Record<string, unknown> & {
rendered: true;
+ confirmLargeRun?: boolean;
+ confirmationToken?: string;
+ imageDomains?: string[];
+ routeExamples?: Array<{ pageId: string; path: string }>;
};
type ExecuteRead = (
@@ -18,7 +32,7 @@ type ExecuteRead = (
) => Promise<ProjectSessionEnvelope>;
type StartPreview = (
- input: { source: "session"; port: number },
+ input: { source: "session"; port: number; imageDomains?: string[] },
progress: { report: (message: string) => void }
) => Promise<unknown>;
@@ -26,36 +40,347 @@ type CaptureScreenshot = (
input: ProjectSessionScreenshotInput
) => Promise<ProjectSessionScreenshotResult>;
+type CapturePageScreenshots = (
+ inputs: readonly ProjectSessionScreenshotInput[]
+) => Promise<ProjectSessionScreenshotResult[]>;
+
type StopPreview = () => Promise<unknown>;
+export type RenderedAuditArtifactManifest = {
+ version: typeof renderedAuditManifestVersion;
+ auditContractVersion: typeof auditContractVersion;
+ projectId: string;
+ buildId: string;
+ projectVersion: number;
+ plan: RenderedAuditPlan;
+ captureStatuses: Array<Record<string, unknown>>;
+ checks: RenderedAuditCheck[];
+ failures: RenderedAuditFailure[];
+ screenshot: {
+ format: "webp";
+ quality: 82;
+ scale: 0.5;
+ };
+ performance: {
+ captureCount: number;
+ previewStartMs: number;
+ captureWallMs: number;
+ previewStopMs: number;
+ targetSetupMs: number;
+ navigationMs: number;
+ readinessMs: number;
+ imageInspectionMs: number;
+ resourceInspectionMs: number;
+ screenshotMs: number;
+ artifactWriteMs: number;
+ targetCleanupMs: number;
+ };
+};
+
+type StoreRenderedAuditArtifacts = (
+ manifest: RenderedAuditArtifactManifest
+) => Promise<string>;
+
export const maxRenderedAuditCaptures = 120;
+const renderedAuditConfirmationTtlMs = 5 * 60 * 1000;
const renderedAuditScreenshotTimeout = 10_000;
+const renderedAuditCaptureTimeout = 30_000;
+const renderedAuditPageTimeout = 120_000;
+const renderedAuditOverallTimeout = 5 * 60_000;
const renderedAuditPreviewPort = 5177;
-const renderedAuditCaptureConcurrency = 3;
+const renderedAuditCaptureConcurrency = 6;
+
+const getRenderedAuditCaptureKey = (
+ pageId: string,
+ viewport: { width: number; height: number }
+) => `${pageId}\n${viewport.width}\n${viewport.height}`;
+
+const getRenderedAuditScreenshotInput = ({
+ pageId,
+ pagePath,
+ viewport,
+ performanceEnabled,
+}: {
+ pageId: string;
+ pagePath: string;
+ viewport: { width: number; height: number };
+ performanceEnabled: boolean;
+}): ProjectSessionScreenshotInput => ({
+ path: pagePath,
+ output: `.webstudio/audits/screenshots/${pageId.replaceAll(/[^a-z0-9_-]/gi, "_")}-${viewport.width}x${viewport.height}.webp`,
+ source: "session",
+ viewport: { width: viewport.width, height: viewport.height },
+ fullPage: true,
+ includeImageMetrics: performanceEnabled,
+ includeResourceMetrics: performanceEnabled,
+ browser: "auto",
+ waitForTimeout: 0,
+ timeout: renderedAuditScreenshotTimeout,
+ format: "webp",
+ quality: 82,
+ scale: 0.5,
+});
+
+export const getRenderedAuditOverallTimeout = (
+ captureCount: number,
+ override?: number
+) =>
+ override ??
+ Math.max(1, Math.ceil(captureCount / maxRenderedAuditCaptures)) *
+ renderedAuditOverallTimeout;
+
+class RenderedAuditCaptureTimeoutError extends Error {}
+class RenderedAuditCancelledError extends Error {}
+
+const withRenderedAuditCancellation = async <Result>(
+ promise: Promise<Result>,
+ signal: AbortSignal | undefined
+) => {
+ if (signal === undefined) {
+ return await promise;
+ }
+ if (signal.aborted) {
+ throw new RenderedAuditCancelledError("Rendered audit was cancelled.");
+ }
+ let rejectCancellation: ((error: Error) => void) | undefined;
+ const onAbort = () => {
+ rejectCancellation?.(
+ new RenderedAuditCancelledError("Rendered audit was cancelled.")
+ );
+ };
+ const cancelled = new Promise<never>((_resolve, reject) => {
+ rejectCancellation = reject;
+ signal.addEventListener("abort", onAbort, { once: true });
+ });
+ try {
+ return await Promise.race([promise, cancelled]);
+ } finally {
+ signal.removeEventListener("abort", onAbort);
+ }
+};
+
+const withRenderedAuditCaptureTimeout = async <Result>(
+ promise: Promise<Result>,
+ timeoutMs: number
+) => {
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ promise,
+ new Promise<never>((_resolve, reject) => {
+ timeout = setTimeout(
+ () =>
+ reject(
+ new RenderedAuditCaptureTimeoutError(
+ `Rendered capture exceeded ${timeoutMs}ms.`
+ )
+ ),
+ timeoutMs
+ );
+ timeout.unref?.();
+ }),
+ ]);
+ } finally {
+ if (timeout !== undefined) {
+ clearTimeout(timeout);
+ }
+ }
+};
+
+const getRenderedAuditPlanSignature = ({
+ envelope,
+ input,
+ plan,
+}: {
+ envelope: ProjectSessionEnvelope;
+ input: RenderedAuditInput;
+ plan: RenderedAuditPlan;
+}) =>
+ JSON.stringify({
+ projectId: envelope.projectId,
+ buildId: envelope.buildId,
+ version: envelope.version,
+ scopes: input.scopes,
+ severities: input.severities,
+ pageId: input.pageId,
+ pagePath: input.pagePath,
+ imageDomains: input.imageDomains,
+ routeExamples: input.routeExamples,
+ plan: {
+ version: plan.version,
+ pages: plan.pages,
+ viewports: plan.viewports,
+ checks: plan.checks,
+ captureCount: plan.captureCount,
+ },
+ });
+
+const getRenderedAuditConfirmationDigest = async (
+ signature: string,
+ expiresAt: number
+) => {
+ const digest = await globalThis.crypto.subtle.digest(
+ "SHA-256",
+ new TextEncoder().encode(`${expiresAt}:${signature}`)
+ );
+ return btoa(String.fromCharCode(...new Uint8Array(digest)))
+ .replaceAll("+", "-")
+ .replaceAll("/", "_")
+ .replaceAll("=", "");
+};
+
+const createRenderedAuditConfirmation = async (signature: string) => {
+ const expiresAt = Date.now() + renderedAuditConfirmationTtlMs;
+ const digest = await getRenderedAuditConfirmationDigest(signature, expiresAt);
+ const token = `${expiresAt.toString(36)}.${digest}`;
+ return { token, expiresAt };
+};
+
+const validateRenderedAuditConfirmation = async (
+ token: string | undefined,
+ signature: string
+) => {
+ if (token === undefined) {
+ return false;
+ }
+ const [encodedExpiresAt, digest, ...extra] = token.split(".");
+ if (
+ encodedExpiresAt === undefined ||
+ digest === undefined ||
+ extra.length > 0
+ ) {
+ return false;
+ }
+ const expiresAt = Number.parseInt(encodedExpiresAt, 36);
+ if (Number.isSafeInteger(expiresAt) === false || expiresAt < Date.now()) {
+ return false;
+ }
+ return (
+ digest === (await getRenderedAuditConfirmationDigest(signature, expiresAt))
+ );
+};
export const getRenderedAuditViewports = (breakpoints: unknown): Viewport[] => {
- const widths = new Set([375, 1440]);
- if (isRecord(breakpoints) && Array.isArray(breakpoints.breakpoints)) {
- for (const breakpoint of breakpoints.breakpoints) {
- if (isRecord(breakpoint) === false) {
- continue;
- }
- for (const [key, delta] of [
- ["minWidth", -1],
- ["minWidth", 0],
- ["maxWidth", 0],
- ["maxWidth", 1],
- ] as const) {
- const value = breakpoint[key];
- if (typeof value === "number" && Number.isFinite(value)) {
- widths.add(Math.max(1, Math.round(value) + delta));
- }
- }
+ const popularViewports = [
+ { width: 390, height: 844 },
+ { width: 667, height: 375 },
+ { width: 820, height: 1180 },
+ { width: 1024, height: 768 },
+ { width: 1366, height: 768 },
+ { width: 1440, height: 900 },
+ { width: 1920, height: 1080 },
+ ];
+ const widths = new Map<number, { height: number; purposes: Set<string> }>();
+ const addViewport = (
+ viewport: { width: number; height: number },
+ purpose: string
+ ) => {
+ const purposes = widths.get(viewport.width)?.purposes ?? new Set<string>();
+ purposes.add(purpose);
+ widths.set(viewport.width, { height: viewport.height, purposes });
+ };
+ const addRepresentative = (
+ minimum: number,
+ maximum: number | undefined,
+ purpose: string
+ ) => {
+ const candidates = popularViewports.filter(
+ ({ width }) =>
+ width >= minimum && (maximum === undefined || width <= maximum)
+ );
+ const viewport =
+ maximum === undefined
+ ? candidates[0]
+ : candidates.sort(
+ (left, right) =>
+ Math.abs(left.width - (minimum + maximum) / 2) -
+ Math.abs(right.width - (minimum + maximum) / 2)
+ )[0];
+ addViewport(
+ viewport ?? {
+ width: maximum ?? minimum,
+ height: (maximum ?? minimum) <= 480 ? 844 : 900,
+ },
+ purpose
+ );
+ };
+ const records =
+ isRecord(breakpoints) && Array.isArray(breakpoints.breakpoints)
+ ? breakpoints.breakpoints.flatMap((breakpoint, index) => {
+ if (isRecord(breakpoint) === false) {
+ return [];
+ }
+ const label =
+ typeof breakpoint.label === "string"
+ ? breakpoint.label
+ : typeof breakpoint.id === "string"
+ ? breakpoint.id
+ : `breakpoint ${index + 1}`;
+ const minWidth =
+ typeof breakpoint.minWidth === "number" &&
+ Number.isFinite(breakpoint.minWidth)
+ ? Math.max(1, Math.round(breakpoint.minWidth))
+ : undefined;
+ const maxWidth =
+ typeof breakpoint.maxWidth === "number" &&
+ Number.isFinite(breakpoint.maxWidth)
+ ? Math.max(1, Math.round(breakpoint.maxWidth))
+ : undefined;
+ return [{ label, minWidth, maxWidth }];
+ })
+ : [];
+ const minimumBreakpoints = records
+ .filter(
+ (breakpoint): breakpoint is typeof breakpoint & { minWidth: number } =>
+ breakpoint.minWidth !== undefined
+ )
+ .sort((left, right) => left.minWidth - right.minWidth);
+ const maximumBreakpoints = records
+ .filter(
+ (breakpoint): breakpoint is typeof breakpoint & { maxWidth: number } =>
+ breakpoint.minWidth === undefined && breakpoint.maxWidth !== undefined
+ )
+ .sort((left, right) => left.maxWidth - right.maxWidth);
+ if (minimumBreakpoints.length === 0 && maximumBreakpoints.length === 0) {
+ addViewport(popularViewports[5], "base breakpoint: desktop");
+ }
+ let previousMaximum = 0;
+ for (const breakpoint of maximumBreakpoints) {
+ addRepresentative(
+ previousMaximum + 1,
+ breakpoint.maxWidth,
+ `${breakpoint.label}: representative`
+ );
+ previousMaximum = breakpoint.maxWidth;
+ }
+ const firstMinimum = minimumBreakpoints[0]?.minWidth;
+ if (minimumBreakpoints.length > 0 || maximumBreakpoints.length > 0) {
+ const baseMaximum =
+ firstMinimum === undefined ? undefined : firstMinimum - 1;
+ if (baseMaximum === undefined || previousMaximum < baseMaximum) {
+ addRepresentative(
+ previousMaximum + 1,
+ baseMaximum,
+ "base breakpoint: representative"
+ );
}
}
- return [...widths]
- .sort((left, right) => left - right)
- .map((width) => ({ width, height: width <= 480 ? 812 : 900 }));
+ for (const [index, breakpoint] of minimumBreakpoints.entries()) {
+ const nextMinimum = minimumBreakpoints[index + 1]?.minWidth;
+ addRepresentative(
+ breakpoint.minWidth,
+ breakpoint.maxWidth ??
+ (nextMinimum === undefined ? undefined : nextMinimum - 1),
+ `${breakpoint.label}: representative`
+ );
+ }
+ return [...widths.entries()]
+ .sort(([left], [right]) => left - right)
+ .map(([width, { height, purposes }]) => ({
+ width,
+ height,
+ purposes: [...purposes],
+ }));
};
type Layout = NonNullable<ProjectSessionScreenshotResult["layout"]> & {
@@ -69,8 +394,19 @@ type Layout = NonNullable<ProjectSessionScreenshotResult["layout"]> & {
export const getRenderedImageIssues = (
layout: Layout
-): RenderedAuditCheck["imageIssues"] =>
- layout.images.flatMap((image) => {
+): RenderedAuditCheck["imageIssues"] => {
+ const eagerSourcesAboveFold = new Set(
+ layout.images.flatMap((image) =>
+ image.loading !== "lazy" &&
+ image.top < layout.viewportHeight &&
+ image.sourcePathname !== undefined
+ ? [image.sourcePathname]
+ : []
+ )
+ );
+ return layout.images.flatMap((image) => {
+ const sourceWidth = image.selectedSourceWidth ?? image.naturalWidth;
+ const sourceHeight = image.selectedSourceHeight ?? image.naturalHeight;
let kind: RenderedAuditCheck["imageIssues"][number]["kind"] | undefined;
if (
image.complete &&
@@ -79,25 +415,37 @@ export const getRenderedImageIssues = (
image.renderedHeight > 0
) {
kind = "broken-image";
- } else if (image.top >= layout.viewportHeight && image.loading !== "lazy") {
+ } else if (
+ image.top >= layout.viewportHeight &&
+ image.loading !== "lazy" &&
+ (image.sourcePathname === undefined ||
+ eagerSourcesAboveFold.has(image.sourcePathname) === false)
+ ) {
kind = "eager-below-fold-image";
} else if (
+ image.sourcePathname?.toLowerCase().endsWith(".svg") !== true &&
+ image.sourcePathname?.toLowerCase().startsWith("data:image/svg+xml") !==
+ true &&
image.renderedWidth > 0 &&
image.renderedHeight > 0 &&
- image.naturalWidth > image.renderedWidth * 2 &&
- image.naturalHeight > image.renderedHeight * 2
+ sourceWidth > image.renderedWidth * 2 &&
+ sourceHeight > image.renderedHeight * 2
) {
kind = "oversized-image";
}
return kind === undefined ? [] : [{ kind, ...image }];
});
+};
export const getRenderedResourceIssues = (
layout: Layout
): RenderedAuditCheck["resourceIssues"] =>
layout.resources.flatMap((resource) => {
const issues: RenderedAuditCheck["resourceIssues"] = [];
- if (resource.renderBlockingStatus === "blocking") {
+ if (
+ resource.renderBlockingStatus === "blocking" &&
+ /^\/assets\/index-[a-zA-Z0-9_-]+\.css$/.test(resource.pathname) === false
+ ) {
issues.push({ kind: "render-blocking-resource", ...resource });
}
if (/\.(?:ttf|otf|woff)$/i.test(resource.pathname)) {
@@ -106,34 +454,83 @@ export const getRenderedResourceIssues = (
return issues;
});
-const selectStaticPages = (pagesResult: unknown, input: RenderedAuditInput) =>
- isRecord(pagesResult) && Array.isArray(pagesResult.pages)
- ? pagesResult.pages.filter(
- (
- page
- ): page is Record<string, unknown> & { id: string; path: string } =>
- isRecord(page) &&
- typeof page.id === "string" &&
- typeof page.path === "string" &&
- page.path.includes(":") === false &&
- page.path.includes("*") === false &&
- (typeof input.pageId !== "string" || page.id === input.pageId) &&
- (typeof input.pagePath !== "string" || page.path === input.pagePath)
- )
- : [];
+const getRenderedAuditPlan = (
+ pagesResult: unknown,
+ breakpointsResult: unknown,
+ input: RenderedAuditInput,
+ performanceEnabled: boolean
+): RenderedAuditPlan => {
+ const normalizePagePath = (path: string) => path || "/";
+ const candidates =
+ isRecord(pagesResult) && Array.isArray(pagesResult.pages)
+ ? pagesResult.pages.filter(
+ (
+ page
+ ): page is Record<string, unknown> & { id: string; path: string } =>
+ isRecord(page) &&
+ typeof page.id === "string" &&
+ typeof page.path === "string" &&
+ (typeof input.pageId !== "string" || page.id === input.pageId) &&
+ (typeof input.pagePath !== "string" ||
+ normalizePagePath(page.path) ===
+ normalizePagePath(input.pagePath))
+ )
+ : [];
+ const routeExamples = new Map(
+ input.routeExamples?.map((example) => [example.pageId, example.path]) ?? []
+ );
+ const isDynamicRoute = (path: string) =>
+ path.includes(":") || path.includes("*");
+ const pages = candidates.flatMap((page) => {
+ if (isDynamicRoute(page.path) === false) {
+ return [{ pageId: page.id, pagePath: normalizePagePath(page.path) }];
+ }
+ const example = routeExamples.get(page.id);
+ return example === undefined
+ ? []
+ : [{ pageId: page.id, pagePath: example }];
+ });
+ const excludedPages = candidates
+ .filter((page) => isDynamicRoute(page.path) && !routeExamples.has(page.id))
+ .map((page) => ({
+ pageId: page.id,
+ pagePath: normalizePagePath(page.path),
+ reason: "dynamic-route-needs-example" as const,
+ }));
+ const viewports = getRenderedAuditViewports(breakpointsResult);
+ return {
+ version: 1,
+ pages,
+ excludedPages,
+ viewports,
+ checks: [
+ "horizontal-overflow",
+ ...(performanceEnabled
+ ? ([
+ "broken-image",
+ "eager-below-fold-image",
+ "oversized-image",
+ "render-blocking-resource",
+ "legacy-font-format",
+ ] as const)
+ : []),
+ ],
+ captureCount: pages.length * viewports.length,
+ };
+};
const mergeRenderedAudit = ({
envelope,
input,
checks,
failures,
- complete,
+ plan,
}: {
envelope: ProjectSessionEnvelope;
input: RenderedAuditInput;
checks: RenderedAuditCheck[];
failures: RenderedAuditFailure[];
- complete: boolean;
+ plan?: RenderedAuditPlan;
}): ProjectSessionEnvelope => {
const result = envelope.result;
if (isRecord(result) === false) {
@@ -143,14 +540,163 @@ const mergeRenderedAudit = ({
(count, check) => count + check.issues.length,
0
);
+ const plannedCaptures =
+ plan?.pages.flatMap((page) =>
+ plan.viewports.map((viewport) => ({ page, viewport }))
+ ) ?? [];
+ const captureOrder = new Map(
+ plannedCaptures.map(({ page, viewport }, index) => [
+ getRenderedAuditCaptureKey(page.pageId, viewport),
+ index,
+ ])
+ );
+ const getCaptureOrder = (
+ pageId: string | undefined,
+ viewport: { width: number; height: number } | undefined
+ ) =>
+ pageId === undefined || viewport === undefined
+ ? Number.MAX_SAFE_INTEGER
+ : (captureOrder.get(getRenderedAuditCaptureKey(pageId, viewport)) ??
+ Number.MAX_SAFE_INTEGER);
+ const orderedChecks = [...checks].sort(
+ (left, right) =>
+ getCaptureOrder(left.pageId, left.viewport) -
+ getCaptureOrder(right.pageId, right.viewport)
+ );
+ const orderedFailures = [...failures].sort(
+ (left, right) =>
+ getCaptureOrder(left.pageId, left.viewport) -
+ getCaptureOrder(right.pageId, right.viewport)
+ );
+ const checkByCapture = new Map(
+ checks.map((check) => [
+ getRenderedAuditCaptureKey(check.pageId, check.viewport),
+ check,
+ ])
+ );
+ const failureByCapture = new Map(
+ failures.flatMap((failure) =>
+ failure.pageId === undefined || failure.viewport === undefined
+ ? []
+ : [
+ [
+ getRenderedAuditCaptureKey(failure.pageId, failure.viewport),
+ failure,
+ ] as const,
+ ]
+ )
+ );
+ const fallbackFailure = failures.find(
+ (failure) => failure.pageId === undefined || failure.viewport === undefined
+ );
+ const getFailureStatus = (failure: RenderedAuditFailure | undefined) => {
+ if (failure === undefined) {
+ return "skipped" as const;
+ }
+ return failure.code === "RENDERED_AUDIT_CAPTURE_LIMIT_EXCEEDED" ||
+ failure.code === "RENDERED_AUDIT_CONFIRMATION_REQUIRED" ||
+ failure.code === "RENDERED_AUDIT_CONFIRMATION_INVALID" ||
+ failure.code === "RENDERED_AUDIT_CANCELLED"
+ ? ("skipped" as const)
+ : ("failed" as const);
+ };
+ const renderedCaptureStatuses =
+ plan?.pages.flatMap((page) =>
+ plan.viewports.map((viewport) => {
+ const check = checkByCapture.get(
+ getRenderedAuditCaptureKey(page.pageId, viewport)
+ );
+ const failure =
+ failureByCapture.get(
+ getRenderedAuditCaptureKey(page.pageId, viewport)
+ ) ?? fallbackFailure;
+ if (check !== undefined) {
+ return {
+ pageId: page.pageId,
+ pagePath: page.pagePath,
+ viewport: { width: viewport.width, height: viewport.height },
+ status:
+ check.issues.length === 0
+ ? ("passed" as const)
+ : ("issues" as const),
+ screenshotPath: check.screenshotPath,
+ };
+ }
+ return {
+ pageId: page.pageId,
+ pagePath: page.pagePath,
+ viewport: { width: viewport.width, height: viewport.height },
+ status: getFailureStatus(failure),
+ ...(failure === undefined ? {} : { failureCode: failure.code }),
+ ...(failure?.screenshotPath === undefined
+ ? {}
+ : { screenshotPath: failure.screenshotPath }),
+ };
+ })
+ ) ?? [];
+ const renderedCaptureSummary = renderedCaptureStatuses.reduce(
+ (summary, capture) => {
+ summary[capture.status] += 1;
+ return summary;
+ },
+ {
+ planned: renderedCaptureStatuses.length,
+ passed: 0,
+ issues: 0,
+ skipped: 0,
+ failed: 0,
+ }
+ );
const isVerbose = input.verbose === true;
+ const renderedIssueSummaries = Array.from(
+ checks
+ .reduce((summaries, check) => {
+ for (const kind of new Set(check.issues)) {
+ const summary = summaries.get(kind) ?? {
+ kind,
+ count: 0,
+ captureCount: 0,
+ pagePaths: new Set<string>(),
+ };
+ summary.captureCount += 1;
+ summary.pagePaths.add(check.pagePath);
+ summaries.set(kind, summary);
+ }
+ for (const kind of check.issues) {
+ const summary = summaries.get(kind);
+ if (summary !== undefined) {
+ summary.count += 1;
+ }
+ }
+ return summaries;
+ }, new Map<RenderedAuditCheck["issues"][number], { kind: RenderedAuditCheck["issues"][number]; count: number; captureCount: number; pagePaths: Set<string> }>())
+ .values(),
+ ({ pagePaths, ...summary }) => ({
+ ...summary,
+ pagePaths: Array.from(pagePaths).sort().slice(0, 5),
+ })
+ ).sort(
+ (left, right) =>
+ right.count - left.count || left.kind.localeCompare(right.kind)
+ );
+ const renderedFailureSummaries = Array.from(
+ failures
+ .reduce((summaries, failure) => {
+ const key = `${failure.code}\n${failure.phase}\n${failure.remediation}`;
+ const summary = summaries.get(key);
+ summaries.set(key, {
+ code: failure.code,
+ phase: failure.phase,
+ remediation: failure.remediation,
+ count: (summary?.count ?? 0) + 1,
+ });
+ return summaries;
+ }, new Map<string, { code: RenderedAuditFailure["code"]; phase: RenderedAuditFailure["phase"]; remediation: string; count: number }>())
+ .values()
+ );
const manualChecks =
isVerbose && Array.isArray(result.manualChecks)
- ? result.manualChecks.filter(
- (check) =>
- complete === false ||
- (isRecord(check) && check.checkId !== "responsive-visual-review")
- )
+ ? result.manualChecks
: undefined;
return {
...envelope,
@@ -159,22 +705,17 @@ const mergeRenderedAudit = ({
renderedCheckCount: checks.length,
renderedIssueCount,
renderedFailureCount: failures.length,
- manualCheckCount:
- complete === false
- ? result.manualCheckCount
- : Math.max(
- 0,
- typeof result.manualCheckCount === "number"
- ? result.manualCheckCount - 1
- : 0
- ),
+ renderedPlan: plan ?? null,
+ renderedCaptureSummary,
+ renderedCaptureStatuses,
+ manualCheckCount: result.manualCheckCount,
...(isVerbose
? {
- renderedChecks: checks,
- renderedFailures: failures,
+ renderedChecks: orderedChecks,
+ renderedFailures: orderedFailures,
manualChecks: manualChecks ?? [],
}
- : {}),
+ : { renderedIssueSummaries, renderedFailureSummaries }),
},
};
};
@@ -186,7 +727,11 @@ export const augmentAuditWithRenderedChecks = async ({
startPreview,
stopPreview,
captureScreenshot,
+ capturePageScreenshots,
reportProgress,
+ storeRenderedAuditArtifacts,
+ timeouts,
+ signal,
}: {
envelope: ProjectSessionEnvelope;
input: unknown;
@@ -194,7 +739,15 @@ export const augmentAuditWithRenderedChecks = async ({
startPreview?: StartPreview;
stopPreview?: StopPreview;
captureScreenshot?: CaptureScreenshot;
+ capturePageScreenshots?: CapturePageScreenshots;
reportProgress?: (message: string) => void;
+ storeRenderedAuditArtifacts?: StoreRenderedAuditArtifacts;
+ timeouts?: Partial<{
+ capture: number;
+ page: number;
+ overall: number;
+ }>;
+ signal?: AbortSignal;
}): Promise<ProjectSessionEnvelope> => {
if (
isRecord(input) === false ||
@@ -212,97 +765,574 @@ export const augmentAuditWithRenderedChecks = async ({
Array.isArray(result.scopes) && result.scopes.includes("performance");
const checks: RenderedAuditCheck[] = [];
const failures: RenderedAuditFailure[] = [];
- const finish = (complete: boolean) =>
- mergeRenderedAudit({
+ const performance = {
+ captureCount: 0,
+ previewStartMs: 0,
+ captureWallMs: 0,
+ previewStopMs: 0,
+ targetSetupMs: 0,
+ navigationMs: 0,
+ readinessMs: 0,
+ imageInspectionMs: 0,
+ resourceInspectionMs: 0,
+ screenshotMs: 0,
+ artifactWriteMs: 0,
+ targetCleanupMs: 0,
+ };
+ const captureTimeout = timeouts?.capture ?? renderedAuditCaptureTimeout;
+ const pageTimeout = timeouts?.page ?? renderedAuditPageTimeout;
+ let overallTimeout = getRenderedAuditOverallTimeout(1, timeouts?.overall);
+ let plan: RenderedAuditPlan | undefined;
+ let cancellationRecorded = false;
+ const projectId = envelope.projectId;
+ const buildId = envelope.buildId;
+ const projectVersion = envelope.version;
+ const recordCancellation = (capture?: {
+ page: RenderedAuditPlan["pages"][number];
+ viewport: Viewport;
+ }) => {
+ if (cancellationRecorded) {
+ return;
+ }
+ cancellationRecorded = true;
+ failures.push({
+ code: "RENDERED_AUDIT_CANCELLED",
+ phase: capture === undefined ? "planning" : "capture",
+ retryable: true,
+ remediation:
+ "Retry the rendered audit. Completed capture evidence remains available in the artifact manifest.",
+ ...(capture === undefined
+ ? {}
+ : {
+ pageId: capture.page.pageId,
+ pagePath: capture.page.pagePath,
+ viewport: {
+ width: capture.viewport.width,
+ height: capture.viewport.height,
+ },
+ }),
+ message: "Rendered audit was cancelled by the caller.",
+ });
+ };
+ const finish = async () => {
+ let merged = mergeRenderedAudit({
envelope,
input: renderedInput,
checks,
failures,
- complete,
+ plan,
});
+ if (
+ plan !== undefined &&
+ storeRenderedAuditArtifacts !== undefined &&
+ typeof projectId === "string" &&
+ typeof buildId === "string" &&
+ typeof projectVersion === "number" &&
+ isRecord(merged.result)
+ ) {
+ try {
+ reportProgress?.("tool audit storing rendered artifact manifest");
+ const path = await storeRenderedAuditArtifacts({
+ version: renderedAuditManifestVersion,
+ auditContractVersion,
+ projectId,
+ buildId,
+ projectVersion,
+ plan,
+ captureStatuses: Array.isArray(merged.result.renderedCaptureStatuses)
+ ? merged.result.renderedCaptureStatuses
+ : [],
+ checks: [...checks],
+ failures: [...failures],
+ screenshot: {
+ format: "webp",
+ quality: 82,
+ scale: 0.5,
+ },
+ performance: { ...performance },
+ });
+ const screenshotCount = new Set([
+ ...checks.map((check) => check.screenshotPath),
+ ...failures.flatMap((failure) =>
+ failure.screenshotPath === undefined ? [] : [failure.screenshotPath]
+ ),
+ ]).size;
+ merged = {
+ ...merged,
+ result: {
+ ...merged.result,
+ renderedArtifactManifest: {
+ version: renderedAuditManifestVersion,
+ path,
+ screenshotCount,
+ },
+ },
+ };
+ } catch (error) {
+ failures.push({
+ code: "RENDERED_AUDIT_ARTIFACT_WRITE_FAILED",
+ phase: "capture",
+ retryable: true,
+ remediation:
+ "Verify that the project .webstudio directory is writable, then retry the rendered audit.",
+ message: `Rendered audit could not store its artifact manifest: ${error instanceof Error ? error.message : String(error)}`,
+ });
+ merged = mergeRenderedAudit({
+ envelope,
+ input: renderedInput,
+ checks,
+ failures,
+ plan,
+ });
+ }
+ }
+ return merged;
+ };
reportProgress?.("tool audit preparing rendered responsive checks");
let pagesEnvelope: ProjectSessionEnvelope;
let breakpointsEnvelope: ProjectSessionEnvelope;
try {
- pagesEnvelope = await executeRead("list-pages", {});
- breakpointsEnvelope = await executeRead("list-breakpoints", {});
+ [pagesEnvelope, breakpointsEnvelope] = await Promise.all([
+ executeRead("list-pages", {}),
+ executeRead("list-breakpoints", {}),
+ ]);
} catch (error) {
failures.push({
+ code: "RENDERED_AUDIT_PREPARATION_FAILED",
+ phase: "planning",
+ retryable: true,
+ remediation:
+ "Refresh the project session and retry. If the failure persists, inspect list-pages and list-breakpoints separately.",
message: `Rendered audit could not prepare: ${error instanceof Error ? error.message : String(error)}`,
});
- return finish(false);
+ return await finish();
}
- const pages = selectStaticPages(pagesEnvelope.result, renderedInput);
- const viewports = getRenderedAuditViewports(breakpointsEnvelope.result);
- if (pages.length === 0) {
+ plan = getRenderedAuditPlan(
+ pagesEnvelope.result,
+ breakpointsEnvelope.result,
+ renderedInput,
+ performanceEnabled
+ );
+ if (plan.pages.length === 0) {
failures.push({
+ code: "RENDERED_AUDIT_NO_STATIC_PAGES",
+ phase: "planning",
+ retryable: false,
+ remediation:
+ "Choose an existing static pagePath or pageId. Dynamic routes require a concrete route example.",
message: "Rendered audit found no static page paths to capture.",
});
- return finish(false);
+ return await finish();
+ }
+
+ if (signal?.aborted) {
+ recordCancellation();
+ return await finish();
}
- const captureCount = pages.length * viewports.length;
+ const captureCount = plan.captureCount;
+ overallTimeout = getRenderedAuditOverallTimeout(
+ captureCount,
+ timeouts?.overall
+ );
if (captureCount > maxRenderedAuditCaptures) {
- failures.push({
- message:
- `Rendered audit requires ${captureCount} screenshots, exceeding the ` +
- `${maxRenderedAuditCaptures}-screenshot limit. Run it for one page with pagePath or pageId.`,
+ const signature = getRenderedAuditPlanSignature({
+ envelope,
+ input: renderedInput,
+ plan,
});
- return finish(false);
+ if (
+ renderedInput.confirmLargeRun !== true ||
+ (await validateRenderedAuditConfirmation(
+ renderedInput.confirmationToken,
+ signature
+ )) === false
+ ) {
+ const confirmation = await createRenderedAuditConfirmation(signature);
+ plan = {
+ ...plan,
+ confirmationToken: confirmation.token,
+ confirmationExpiresAt: new Date(confirmation.expiresAt).toISOString(),
+ };
+ failures.push({
+ code:
+ renderedInput.confirmLargeRun === true
+ ? "RENDERED_AUDIT_CONFIRMATION_INVALID"
+ : "RENDERED_AUDIT_CONFIRMATION_REQUIRED",
+ phase: "planning",
+ retryable: false,
+ remediation:
+ "Review the returned rendered plan, then retry the unchanged audit with confirmLargeRun: true and its confirmationToken before the token expires.",
+ message:
+ `Rendered audit requires ${captureCount} screenshots, exceeding the ` +
+ `${maxRenderedAuditCaptures}-screenshot unconfirmed threshold.`,
+ });
+ return await finish();
+ }
}
+ const previewStartStartedAt = Date.now();
try {
await startPreview(
- { source: "session", port: renderedAuditPreviewPort },
+ {
+ source: "session",
+ port: renderedAuditPreviewPort,
+ imageDomains: renderedInput.imageDomains,
+ },
{ report: (message) => reportProgress?.(message) }
);
+ performance.previewStartMs = Date.now() - previewStartStartedAt;
} catch (error) {
+ performance.previewStartMs = Date.now() - previewStartStartedAt;
failures.push({
+ code: "RENDERED_AUDIT_PREVIEW_START_FAILED",
+ phase: "preview-start",
+ retryable: true,
+ remediation:
+ "Run preview.start separately to inspect the generated build failure, fix it, then retry the rendered audit.",
message: `Rendered audit could not start: ${error instanceof Error ? error.message : String(error)}`,
});
- return finish(false);
+ return await finish();
}
+ const captureStartedAt = Date.now();
try {
- const captures = pages.flatMap((page) =>
- viewports.map((viewport) => ({ page, viewport }))
+ const captures = plan.pages.flatMap((page) =>
+ plan.viewports.map((viewport) => ({ page, viewport }))
);
+ const overallDeadline = Date.now() + overallTimeout;
+ const resizedScreenshots = new Map<
+ string,
+ ProjectSessionScreenshotResult
+ >();
+ const terminalCaptureKeys = new Set<string>();
+ if (capturePageScreenshots !== undefined) {
+ const capturePageBatch = async (
+ pages: RenderedAuditPlan["pages"]
+ ): Promise<void> => {
+ if (signal?.aborted) {
+ recordCancellation();
+ return;
+ }
+ const batchCaptures = pages.flatMap((page) =>
+ plan.viewports.map((viewport) => ({ page, viewport }))
+ );
+ const inputs = batchCaptures.map(({ page, viewport }) =>
+ getRenderedAuditScreenshotInput({
+ pageId: page.pageId,
+ pagePath: page.pagePath,
+ viewport,
+ performanceEnabled,
+ })
+ );
+ try {
+ reportProgress?.(
+ `tool audit capturing ${pages.length} pages across ${inputs.length} viewport widths`
+ );
+ const screenshots = await withRenderedAuditCancellation(
+ withRenderedAuditCaptureTimeout(
+ capturePageScreenshots(inputs),
+ Math.min(overallTimeout, pageTimeout * pages.length)
+ ),
+ signal
+ );
+ if (screenshots.length !== batchCaptures.length) {
+ throw new Error(
+ `Resized capture returned ${screenshots.length} of ${batchCaptures.length} viewport results.`
+ );
+ }
+ for (const [index, screenshot] of screenshots.entries()) {
+ const capture = batchCaptures[index];
+ if (capture !== undefined) {
+ resizedScreenshots.set(
+ getRenderedAuditCaptureKey(
+ capture.page.pageId,
+ capture.viewport
+ ),
+ screenshot
+ );
+ }
+ }
+ } catch (error) {
+ if (error instanceof RenderedAuditCancelledError) {
+ const capture = batchCaptures[0];
+ capture === undefined
+ ? recordCancellation()
+ : recordCancellation(capture);
+ return;
+ }
+ if (error instanceof RenderedAuditCaptureTimeoutError) {
+ for (const capture of batchCaptures) {
+ const viewport = {
+ width: capture.viewport.width,
+ height: capture.viewport.height,
+ };
+ terminalCaptureKeys.add(
+ getRenderedAuditCaptureKey(
+ capture.page.pageId,
+ capture.viewport
+ )
+ );
+ failures.push({
+ code: "RENDERED_AUDIT_CAPTURE_TIMEOUT",
+ phase: "capture",
+ retryable: true,
+ remediation:
+ "Audit this page alone and inspect its navigation/readiness behavior before retrying the full run.",
+ pageId: capture.page.pageId,
+ pagePath: capture.page.pagePath,
+ viewport,
+ message: error.message,
+ });
+ }
+ return;
+ }
+ reportProgress?.(
+ `tool audit resized capture failed for ${pages[0]?.pagePath}; retrying its viewports with fresh navigation`
+ );
+ }
+ };
+ let nextPage = 0;
+ const captureNextPage = async (): Promise<void> => {
+ const page = plan.pages[nextPage];
+ nextPage += 1;
+ if (page === undefined) {
+ return;
+ }
+ await capturePageBatch([page]);
+ await captureNextPage();
+ };
+ await Promise.all(
+ Array.from(
+ {
+ length: Math.min(
+ renderedAuditCaptureConcurrency,
+ plan.pages.length
+ ),
+ },
+ captureNextPage
+ )
+ );
+ }
+ const pageStartedAt = new Map<string, number>();
let nextCapture = 0;
const captureNext = async (): Promise<void> => {
+ if (signal?.aborted) {
+ recordCancellation();
+ return;
+ }
const capture = captures[nextCapture];
nextCapture += 1;
if (capture === undefined) {
return;
}
const { page, viewport } = capture;
- const pagePath = page.path || "/";
+ if (
+ terminalCaptureKeys.has(
+ getRenderedAuditCaptureKey(page.pageId, viewport)
+ )
+ ) {
+ return await captureNext();
+ }
+ const pagePath = page.pagePath;
+ const viewportSize = { width: viewport.width, height: viewport.height };
+ const now = Date.now();
+ const pageStart = pageStartedAt.get(page.pageId) ?? now;
+ pageStartedAt.set(page.pageId, pageStart);
+ if (now > overallDeadline) {
+ failures.push({
+ code: "RENDERED_AUDIT_OVERALL_TIMEOUT",
+ phase: "capture",
+ retryable: true,
+ remediation:
+ "Run a focused page audit or reduce the viewport plan, then retry the remaining pages.",
+ pageId: page.pageId,
+ pagePath,
+ viewport: viewportSize,
+ message: `Rendered audit exceeded its ${overallTimeout}ms overall timeout.`,
+ });
+ return await captureNext();
+ }
+ if (now - pageStart > pageTimeout) {
+ failures.push({
+ code: "RENDERED_AUDIT_PAGE_TIMEOUT",
+ phase: "capture",
+ retryable: true,
+ remediation:
+ "Audit this page alone and inspect slow resources or readiness behavior before retrying the full run.",
+ pageId: page.pageId,
+ pagePath,
+ viewport: viewportSize,
+ message: `Rendered page audit exceeded its ${pageTimeout}ms timeout.`,
+ });
+ return await captureNext();
+ }
reportProgress?.(
`tool audit capturing ${pagePath} at ${viewport.width}px`
);
try {
- const screenshot = await captureScreenshot({
- path: pagePath,
- source: "session",
- viewport,
- fullPage: true,
- includeImageMetrics: performanceEnabled,
- includeResourceMetrics: performanceEnabled,
- browser: "auto",
- timeout: renderedAuditScreenshotTimeout,
- });
+ const screenshot =
+ resizedScreenshots.get(
+ getRenderedAuditCaptureKey(page.pageId, viewport)
+ ) ??
+ (await withRenderedAuditCancellation(
+ withRenderedAuditCaptureTimeout(
+ captureScreenshot(
+ getRenderedAuditScreenshotInput({
+ pageId: page.pageId,
+ pagePath,
+ viewport: viewportSize,
+ performanceEnabled,
+ })
+ ),
+ captureTimeout
+ ),
+ signal
+ ));
+ if (screenshot.timings !== undefined) {
+ performance.captureCount += 1;
+ for (const key of [
+ "targetSetupMs",
+ "navigationMs",
+ "readinessMs",
+ "imageInspectionMs",
+ "resourceInspectionMs",
+ "screenshotMs",
+ "artifactWriteMs",
+ "targetCleanupMs",
+ ] as const) {
+ performance[key] += screenshot.timings[key];
+ }
+ }
if (screenshot.layout === undefined) {
failures.push({
- pageId: page.id,
+ code: "RENDERED_AUDIT_LAYOUT_METRICS_MISSING",
+ phase: "capture",
+ retryable: true,
+ remediation:
+ "Retry the page capture. If layout metrics remain absent, verify the screenshot browser and generated page readiness.",
+ pageId: page.pageId,
pagePath,
- viewport,
+ viewport: viewportSize,
message: "Screenshot did not return rendered layout metrics.",
});
return await captureNext();
}
+ if (screenshot.navigation === undefined) {
+ failures.push({
+ code: "RENDERED_AUDIT_NAVIGATION_EVIDENCE_MISSING",
+ phase: "capture",
+ retryable: true,
+ remediation:
+ "Retry with a current Chromium-family browser and CLI that reports top-level navigation evidence.",
+ pageId: page.pageId,
+ pagePath,
+ viewport: viewportSize,
+ screenshotPath: screenshot.output,
+ message:
+ "Screenshot did not report its final URL, HTTP status, redirects, and readiness evidence.",
+ });
+ return await captureNext();
+ }
+ const finalUrl = new URL(screenshot.navigation.finalUrl);
+ if (
+ finalUrl.origin !== `http://127.0.0.1:${renderedAuditPreviewPort}`
+ ) {
+ failures.push({
+ code: "RENDERED_AUDIT_ORIGIN_MISMATCH",
+ phase: "capture",
+ retryable: false,
+ remediation:
+ "Stop conflicting local servers and retry so the audit captures only its owned generated preview.",
+ pageId: page.pageId,
+ pagePath,
+ viewport: viewportSize,
+ screenshotPath: screenshot.output,
+ message: `Expected the owned generated preview origin, but captured ${finalUrl.origin}.`,
+ });
+ return await captureNext();
+ }
+ const requestedUrl = new URL(pagePath, finalUrl.origin);
+ const requestedRoute = `${requestedUrl.pathname}${requestedUrl.search}`;
+ const finalRoute = `${finalUrl.pathname}${finalUrl.search}`;
+ if (
+ finalRoute !== requestedRoute &&
+ screenshot.navigation.redirects.includes(requestedUrl.toString()) ===
+ false
+ ) {
+ failures.push({
+ code: "RENDERED_AUDIT_ROUTE_MISMATCH",
+ phase: "capture",
+ retryable: false,
+ remediation:
+ "Inspect generated redirects and route definitions, then provide the canonical concrete page path.",
+ pageId: page.pageId,
+ pagePath,
+ viewport: viewportSize,
+ screenshotPath: screenshot.output,
+ message: `Requested ${requestedRoute}, but the generated preview finished at ${finalRoute}.`,
+ });
+ return await captureNext();
+ }
+ if (
+ screenshot.navigation.status !== undefined &&
+ screenshot.navigation.status >= 400
+ ) {
+ failures.push({
+ code: "RENDERED_AUDIT_HTTP_ERROR",
+ phase: "capture",
+ retryable: false,
+ remediation:
+ "Verify that the generated project defines this route and that the preview server can render it.",
+ pageId: page.pageId,
+ pagePath,
+ viewport: viewportSize,
+ screenshotPath: screenshot.output,
+ message: `Generated preview returned HTTP ${screenshot.navigation.status} for ${screenshot.navigation.finalUrl}.`,
+ });
+ return await captureNext();
+ }
+ const isHtmlDocument =
+ screenshot.layout.documentType === "text/html" ||
+ screenshot.layout.documentType === "application/xhtml+xml";
+ if (
+ isHtmlDocument &&
+ screenshot.navigation.generatedSiteRootPresent === false
+ ) {
+ failures.push({
+ code: "RENDERED_AUDIT_DOCUMENT_NOT_GENERATED_SITE",
+ phase: "capture",
+ retryable: false,
+ remediation:
+ "Verify that the capture uses the owned generated preview rather than a Builder/share URL or unrelated server.",
+ pageId: page.pageId,
+ pagePath,
+ viewport: viewportSize,
+ screenshotPath: screenshot.output,
+ message: `Captured ${screenshot.navigation.finalUrl} without a generated Webstudio page marker.`,
+ });
+ return await captureNext();
+ }
+ if (screenshot.navigation.layoutStable === false) {
+ failures.push({
+ code: "RENDERED_AUDIT_LAYOUT_UNSTABLE",
+ phase: "capture",
+ retryable: true,
+ remediation:
+ "Retry after the page finishes loading, or provide a readiness selector for asynchronously rendered content.",
+ pageId: page.pageId,
+ pagePath,
+ viewport: viewportSize,
+ screenshotPath: screenshot.output,
+ message: `Captured ${screenshot.navigation.finalUrl} before its layout stabilized.`,
+ });
+ return await captureNext();
+ }
const layout: Layout = {
...screenshot.layout,
+ navigation: screenshot.navigation,
images: screenshot.layout.images ?? [],
resources: screenshot.layout.resources ?? [],
};
@@ -313,9 +1343,9 @@ export const augmentAuditWithRenderedChecks = async ({
? getRenderedResourceIssues(layout)
: [];
checks.push({
- pageId: page.id,
+ pageId: page.pageId,
pagePath,
- viewport,
+ viewport: viewportSize,
screenshotPath: screenshot.output,
layout,
issues: [
@@ -329,10 +1359,24 @@ export const augmentAuditWithRenderedChecks = async ({
resourceIssues,
});
} catch (error) {
+ if (error instanceof RenderedAuditCancelledError) {
+ recordCancellation(capture);
+ return;
+ }
failures.push({
- pageId: page.id,
+ code:
+ error instanceof RenderedAuditCaptureTimeoutError
+ ? "RENDERED_AUDIT_CAPTURE_TIMEOUT"
+ : "RENDERED_AUDIT_SCREENSHOT_FAILED",
+ phase: "capture",
+ retryable: true,
+ remediation:
+ error instanceof RenderedAuditCaptureTimeoutError
+ ? "Audit this page alone and inspect its navigation/readiness behavior before retrying the full run."
+ : "Capture this page and viewport with the screenshot tool to inspect browser startup, navigation, or readiness errors, then retry.",
+ pageId: page.pageId,
pagePath,
- viewport,
+ viewport: viewportSize,
message: error instanceof Error ? error.message : String(error),
});
}
@@ -345,15 +1389,24 @@ export const augmentAuditWithRenderedChecks = async ({
)
);
} finally {
+ performance.captureWallMs = Date.now() - captureStartedAt;
+ const previewStopStartedAt = Date.now();
try {
await stopPreview();
} catch (error) {
failures.push({
+ code: "RENDERED_AUDIT_PREVIEW_STOP_FAILED",
+ phase: "preview-stop",
+ retryable: true,
+ remediation:
+ "Run preview.status and preview.stop in the same MCP session before retrying.",
message: `Rendered audit could not stop its preview: ${error instanceof Error ? error.message : String(error)}`,
});
+ } finally {
+ performance.previewStopMs = Date.now() - previewStopStartedAt;
}
}
- return finish(
- failures.length === 0 && checks.length === pages.length * viewports.length
- );
+ return await finish();
};
+
+export const __testing__ = { mergeRenderedAudit };
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index 9fcaaa3f1a..c5d3b957ed 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -140,7 +140,7 @@ const publicMcpOperations: readonly PublicMcpOperation[] = [
outputSchema: getTestInputSchema(
z.discriminatedUnion("verbose", [
z.object({
- contractVersion: z.literal(1),
+ contractVersion: z.literal(2),
projectVersion: z.number(),
verbose: z.literal(false),
findings: z.array(z.unknown()),
@@ -149,7 +149,7 @@ const publicMcpOperations: readonly PublicMcpOperation[] = [
renderedFailureCount: z.number(),
}),
z.object({
- contractVersion: z.literal(1),
+ contractVersion: z.literal(2),
projectVersion: z.number(),
verbose: z.literal(true),
findings: z.array(z.unknown()),
@@ -562,6 +562,7 @@ describe("project session mcp adapter", () => {
"reset-session",
]);
expect(toolNames).toContain("insert-fragment");
+ expect(toolNames).not.toContain("copy-page");
const imageDescriptionsTool = tools.find(
(tool) => tool.name === "set-image-descriptions"
);
@@ -598,13 +599,25 @@ describe("project session mcp adapter", () => {
)?.outputSchema;
expect(auditOutputSchema).toEqual(
expect.objectContaining({
- type: "object",
- required: ["ok", "data", "meta"],
- properties: expect.objectContaining({
- ok: { type: "boolean", const: true },
- data: expect.objectContaining({ oneOf: expect.any(Array) }),
- meta: { type: "object", additionalProperties: true },
- }),
+ oneOf: [
+ expect.objectContaining({
+ required: ["ok", "data", "meta"],
+ properties: expect.objectContaining({
+ ok: { type: "boolean", const: true },
+ data: expect.objectContaining({ oneOf: expect.any(Array) }),
+ }),
+ }),
+ expect.objectContaining({
+ required: ["ok", "error", "meta"],
+ properties: expect.objectContaining({
+ ok: { type: "boolean", const: false },
+ data: expect.objectContaining({ oneOf: expect.any(Array) }),
+ error: expect.objectContaining({
+ required: ["code", "message"],
+ }),
+ }),
+ }),
+ ],
})
);
expect(() =>
@@ -950,6 +963,10 @@ describe("project session mcp adapter", () => {
}),
expect.objectContaining({ uri: "webstudio://project/components" }),
expect.objectContaining({ uri: "webstudio://project/guide" }),
+ expect.objectContaining({
+ uri: "webstudio://project/expressions",
+ mimeType: "text/markdown",
+ }),
expect.objectContaining({
uri: "webstudio://project/accessibility-review",
mimeType: "text/markdown",
@@ -1013,7 +1030,7 @@ describe("project session mcp adapter", () => {
test("exposes the audit input and structured result through MCP", async () => {
const auditResult = {
- contractVersion: 1,
+ contractVersion: 2,
projectVersion: 7,
scopes: ["accessibility"],
pageFilter: null,
@@ -1116,7 +1133,7 @@ describe("project session mcp adapter", () => {
return createEnvelope({
operationId: "project.audit",
result: {
- contractVersion: 1,
+ contractVersion: 2,
projectVersion: 7,
scopes: requestedScopes,
pageFilter: null,
@@ -1168,17 +1185,28 @@ describe("project session mcp adapter", () => {
fullPage: true,
elapsedMs: 1,
warnings: [],
+ navigation: {
+ requestedUrl: `http://127.0.0.1:5177${input.path}`,
+ finalUrl: `http://127.0.0.1:5177${input.path}`,
+ status: 200,
+ statusText: "OK",
+ mimeType: "text/html",
+ redirects: [],
+ documentReadyState: "complete",
+ generatedSiteRootPresent: true,
+ layoutStable: true,
+ },
layout: {
viewportWidth: input.viewport.width,
viewportHeight: input.viewport.height,
contentWidth:
- input.viewport.width === 375
+ input.viewport.width === 390
? input.viewport.width + 20
: input.viewport.width,
contentHeight: 1200,
- horizontalOverflow: input.viewport.width === 375,
+ horizontalOverflow: input.viewport.width === 390,
images:
- input.viewport.width === 375
+ input.viewport.width === 390
? [
{
instanceId: "broken",
@@ -1213,7 +1241,7 @@ describe("project session mcp adapter", () => {
]
: [],
resources:
- input.viewport.width === 375
+ input.viewport.width === 390
? [
{
pathname: "/styles.css",
@@ -1259,23 +1287,23 @@ describe("project session mcp adapter", () => {
expect(startPreview).toHaveBeenCalledTimes(1);
expect(stopPreview).toHaveBeenCalledTimes(1);
- expect(captureScreenshot).toHaveBeenCalledTimes(4);
+ expect(captureScreenshot).toHaveBeenCalledTimes(2);
expect(captureScreenshot).toHaveBeenCalledWith(
expect.objectContaining({
path: "/",
timeout: 10_000,
- viewport: { width: 375, height: 812 },
+ viewport: { width: 390, height: 844 },
})
);
expect(result.structuredContent.data).toMatchObject({
- renderedCheckCount: 4,
+ renderedCheckCount: 2,
renderedIssueCount: 6,
renderedFailureCount: 0,
- manualCheckCount: 2,
+ manualCheckCount: 3,
renderedChecks: [
expect.objectContaining({
pageId: "home",
- viewport: { width: 375, height: 812 },
+ viewport: { width: 390, height: 844 },
issues: [
"horizontal-overflow",
"broken-image",
@@ -1310,11 +1338,10 @@ describe("project session mcp adapter", () => {
],
}),
expect.any(Object),
- expect.any(Object),
- expect.any(Object),
],
renderedFailures: [],
manualChecks: [
+ { checkId: "responsive-visual-review" },
{ checkId: "visual-contrast-review" },
{ checkId: "visual-hierarchy-review" },
],
@@ -1330,7 +1357,7 @@ describe("project session mcp adapter", () => {
},
});
- expect(captureScreenshot).toHaveBeenCalledTimes(4);
+ expect(captureScreenshot).toHaveBeenCalledTimes(2);
expect(stopPreview).toHaveBeenCalledTimes(2);
expect(captureScreenshot).toHaveBeenCalledWith(
expect.objectContaining({
@@ -1340,7 +1367,7 @@ describe("project session mcp adapter", () => {
);
expect(accessibilityResult.structuredContent.data).toMatchObject({
scopes: ["accessibility"],
- renderedCheckCount: 4,
+ renderedCheckCount: 2,
renderedIssueCount: 1,
renderedChecks: [
expect.objectContaining({
@@ -1349,8 +1376,6 @@ describe("project session mcp adapter", () => {
resourceIssues: [],
}),
expect.any(Object),
- expect.any(Object),
- expect.any(Object),
],
});
@@ -1362,7 +1387,7 @@ describe("project session mcp adapter", () => {
).rejects.toThrow(/cannot be combined with cursor pagination/);
});
- test("keeps audit successful when rendered preview cannot start", async () => {
+ test("returns static audit data with an error when rendered preview cannot start", async () => {
const executeOperation = createExecuteOperation(async ({ command }) => {
if (command === "list-pages") {
return createEnvelope({
@@ -1379,7 +1404,7 @@ describe("project session mcp adapter", () => {
return createEnvelope({
operationId: "project.audit",
result: {
- contractVersion: 1,
+ contractVersion: 2,
projectVersion: 7,
scopes: [],
pageFilter: null,
@@ -1420,18 +1445,108 @@ describe("project session mcp adapter", () => {
input: { rendered: true, verbose: true },
});
+ expect(result.isError).toBe(true);
+ expect(result.structuredContent).toMatchObject({
+ ok: false,
+ error: {
+ code: "RENDERED_AUDIT_FAILED",
+ message: expect.stringContaining("completed no rendered checks"),
+ },
+ });
expect(result.structuredContent.data).toMatchObject({
renderedCheckCount: 0,
renderedIssueCount: 0,
renderedFailureCount: 1,
renderedFailures: [
- { message: "Rendered audit could not start: preview build failed" },
+ {
+ code: "RENDERED_AUDIT_PREVIEW_START_FAILED",
+ phase: "preview-start",
+ retryable: true,
+ remediation: expect.stringContaining("preview.start"),
+ message: "Rendered audit could not start: preview build failed",
+ },
],
manualCheckCount: 3,
manualChecks: [{ checkId: "responsive-visual-review" }],
});
});
+ test("includes actionable rendered failure summaries in compact output", async () => {
+ const executeOperation = createExecuteOperation(async ({ command }) => {
+ if (command === "list-pages") {
+ return createEnvelope({
+ operationId: "pages.list",
+ result: { pages: [{ id: "home", path: "/" }] },
+ });
+ }
+ if (command === "list-breakpoints") {
+ return createEnvelope({
+ operationId: "breakpoints.list",
+ result: { breakpoints: [] },
+ });
+ }
+ return createEnvelope({
+ operationId: "project.audit",
+ result: {
+ contractVersion: 2,
+ projectVersion: 1,
+ scopes: ["accessibility"],
+ pageFilter: null,
+ summary: {
+ total: 0,
+ selectedTotal: 0,
+ bySeverity: { error: 0, warning: 0, info: 0 },
+ byScope: {
+ accessibility: 0,
+ security: 0,
+ seo: 0,
+ assets: 0,
+ styles: 0,
+ performance: 0,
+ },
+ },
+ skippedCheckCount: 0,
+ manualCheckCount: 1,
+ renderedCheckCount: 0,
+ renderedIssueCount: 0,
+ renderedFailureCount: 0,
+ renderedFailureSummaries: [],
+ nextCursor: null,
+ verbose: false,
+ findings: [],
+ },
+ });
+ });
+ const adapter = createProjectSessionMcpCore({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation,
+ startPreview: vi.fn(async () => {
+ throw new Error("preview build failed");
+ }),
+ getPreviewStatus: vi.fn(),
+ stopPreview: vi.fn(),
+ captureScreenshot: vi.fn(),
+ });
+
+ const result = await adapter.callTool({
+ name: "audit",
+ input: { rendered: true },
+ });
+
+ expect(result.structuredContent.data).toMatchObject({
+ renderedFailureCount: 1,
+ renderedFailureSummaries: [
+ {
+ code: "RENDERED_AUDIT_PREVIEW_START_FAILED",
+ phase: "preview-start",
+ remediation: expect.stringContaining("preview.start"),
+ count: 1,
+ },
+ ],
+ });
+ });
+
test("does not advertise or silently accept rendered audit without visual capabilities", async () => {
const adapter = createProjectSessionMcpCore({
operations: publicMcpOperations,
@@ -1444,6 +1559,90 @@ describe("project session mcp adapter", () => {
await expect(
adapter.callTool({ name: "audit", input: { rendered: true } })
).rejects.toThrow(/does not provide preview and screenshot capabilities/);
+ await expect(
+ adapter.callTool({
+ name: "audit",
+ input: { confirmationToken: "not-rendered" },
+ })
+ ).rejects.toThrow(/confirmationToken requires rendered: true/);
+ await expect(
+ adapter.callTool({ name: "audit", input: { rendered: false } })
+ ).resolves.toMatchObject({
+ structuredContent: { ok: true },
+ });
+ });
+
+ test("returns a large rendered audit confirmation plan as a successful result", async () => {
+ const executeOperation = createExecuteOperation(async ({ command }) => {
+ if (command === "list-pages") {
+ return createEnvelope({
+ operationId: "pages.list",
+ result: {
+ pages: Array.from({ length: 121 }, (_, index) => ({
+ id: `page-${index}`,
+ path: `/page-${index}`,
+ })),
+ },
+ });
+ }
+ if (command === "list-breakpoints") {
+ return createEnvelope({
+ operationId: "breakpoints.list",
+ result: { breakpoints: [] },
+ });
+ }
+ return createEnvelope({
+ operationId: "project.audit",
+ result: {
+ contractVersion: 2,
+ projectVersion: 7,
+ scopes: [],
+ pageFilter: null,
+ summary: {
+ total: 0,
+ bySeverity: { error: 0, warning: 0, info: 0 },
+ byScope: {},
+ },
+ verbose: false,
+ findings: [],
+ skippedCheckCount: 0,
+ manualCheckCount: 0,
+ renderedCheckCount: 0,
+ renderedIssueCount: 0,
+ renderedFailureCount: 0,
+ nextCursor: null,
+ },
+ });
+ });
+ const adapter = createProjectSessionMcpCore({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation,
+ startPreview: vi.fn(),
+ getPreviewStatus: vi.fn(),
+ stopPreview: vi.fn(),
+ captureScreenshot: vi.fn(),
+ });
+
+ const result = await adapter.callTool({
+ name: "audit",
+ input: { rendered: true },
+ });
+
+ expect(result.isError).not.toBe(true);
+ expect(result.structuredContent).toMatchObject({
+ ok: true,
+ data: {
+ renderedPlan: {
+ captureCount: 121,
+ confirmationToken: expect.any(String),
+ },
+ renderedFailureCount: 1,
+ renderedFailureSummaries: [
+ { code: "RENDERED_AUDIT_CONFIRMATION_REQUIRED", count: 1 },
+ ],
+ },
+ });
});
test("returns the computed transaction for dry-run mutations", async () => {
@@ -3204,6 +3403,14 @@ describe("project session mcp adapter", () => {
name: "meta.guide",
input: { brief: "Add JSON-LD structured data to the home page" },
});
+ const collectionGuide = await adapter.callTool({
+ name: "meta.guide",
+ input: { brief: "Render an array of blog posts as repeated cards" },
+ });
+ const expressionGuide = await adapter.callTool({
+ name: "meta.guide",
+ input: { brief: "Bind a dynamic expression to a prop" },
+ });
const getComponentToolNames = (
getComponentDetails.structuredContent.data as {
tools: { name: string }[];
@@ -3238,6 +3445,29 @@ describe("project session mcp adapter", () => {
]),
})
);
+ expect(collectionGuide.structuredContent.data).toEqual(
+ expect.objectContaining({
+ workflow: expect.arrayContaining([
+ expect.stringContaining("complete nested array/object"),
+ expect.stringContaining('Insert "ws:collection"'),
+ expect.stringContaining("current-item context"),
+ expect.stringContaining("stable unique id or slug"),
+ ]),
+ tools: expect.arrayContaining([
+ expect.objectContaining({ name: "components.get" }),
+ ]),
+ })
+ );
+ expect(expressionGuide.structuredContent.data).toEqual(
+ expect.objectContaining({
+ workflow: expect.arrayContaining([
+ expect.stringContaining("webstudio://project/expressions"),
+ expect.stringContaining("do not guess scoped identifier names"),
+ expect.stringContaining("one expression rather than a statement"),
+ expect.stringContaining("successful syntax validation"),
+ ]),
+ })
+ );
});
test("rejects invalid focused discovery input with path-specific messages", async () => {
@@ -3460,6 +3690,10 @@ describe("project session mcp adapter", () => {
name: "components.get",
input: { component: "JsonLd" },
});
+ const collectionDetails = await adapter.callTool({
+ name: "components.get",
+ input: { component: "ws:collection" },
+ });
const italicDetails = await adapter.callTool({
name: "components.get",
input: { component: "Italic" },
@@ -3938,6 +4172,21 @@ describe("project session mcp adapter", () => {
}),
})
);
+ expect(collectionDetails.structuredContent.data).toEqual(
+ expect.objectContaining({
+ component: "ws:collection",
+ description: expect.stringContaining("array or object"),
+ collectionUsage: expect.stringMatching(
+ /complete array or object.*renders its child structure once per entry/
+ ),
+ usage: expect.stringContaining("internal item/itemKey parameter"),
+ props: expect.objectContaining({
+ data: expect.objectContaining({ type: "json", required: true }),
+ item: expect.objectContaining({ type: "string" }),
+ itemKey: expect.objectContaining({ type: "string" }),
+ }),
+ })
+ );
expect(selectTemplateDetails.structuredContent.data).toEqual(
expect.objectContaining({
found: true,
@@ -4227,6 +4476,90 @@ describe("project session mcp adapter", () => {
).rejects.toThrow("CHECKPOINT_REQUIRED");
});
+ test("keeps coverage reads active during a dry-run insertion", async () => {
+ const instances = [
+ { id: "body", component: "ws:element", depth: 0 },
+ {
+ id: "switch",
+ component: "@webstudio-is/sdk-components-react-radix:Switch",
+ depth: 1,
+ },
+ ];
+ const executeOperation = createExecuteOperation(
+ async ({ command, dryRun }) => {
+ if (command === "list-instances") {
+ if (dryRun) {
+ throw new Error("read operations do not accept dryRun");
+ }
+ return createEnvelope({
+ operationId: "instances.list",
+ result: { instances },
+ });
+ }
+ if (command === "insert-component") {
+ expect(dryRun).toBe(true);
+ return createEnvelope({
+ operationId: "components.insert",
+ result: {
+ rootInstanceIds: ["inserted"],
+ instanceIds: ["inserted"],
+ parentInstanceId: "root",
+ },
+ state: { committed: false, freshness: {} },
+ version: 1,
+ });
+ }
+ throw new Error(`Unexpected command ${command}`);
+ }
+ );
+ const adapter = createProjectSessionMcpCore({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation,
+ });
+
+ await expect(
+ adapter.callTool({
+ name: "components.coverage-insert-next",
+ input: {
+ pagePath: "/design-system",
+ parentInstanceId: "root",
+ component: "@webstudio-is/sdk-components-react-radix:Select",
+ },
+ dryRun: true,
+ })
+ ).resolves.toEqual(
+ expect.objectContaining({
+ structuredContent: expect.objectContaining({
+ data: expect.objectContaining({ committed: false }),
+ }),
+ })
+ );
+ expect(executeOperation).toHaveBeenNthCalledWith(1, {
+ command: "list-instances",
+ input: {
+ pageId: undefined,
+ pagePath: "/design-system",
+ },
+ dryRun: false,
+ });
+ expect(executeOperation).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ command: "insert-component",
+ dryRun: true,
+ })
+ );
+ expect(executeOperation).toHaveBeenNthCalledWith(3, {
+ command: "list-instances",
+ input: {
+ pageId: undefined,
+ pagePath: "/design-system",
+ },
+ dryRun: false,
+ });
+ });
+
test("inserts uncovered non-standalone coverage parts under compatible parents", async () => {
const isTestRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" &&
@@ -4663,7 +4996,7 @@ describe("project session mcp adapter", () => {
},
})
).rejects.toThrow(
- "screenshot baseUrl uses an existing preview/site and cannot be combined with host, port, or source."
+ "screenshot baseUrl uses an existing preview/site and cannot be combined with host, port, source, or imageDomains."
);
});
@@ -5111,6 +5444,9 @@ describe("project session mcp adapter", () => {
const guide = await adapter.readResource({
uri: "webstudio://project/guide",
});
+ const expressions = await adapter.readResource({
+ uri: "webstudio://project/expressions",
+ });
const accessibilityReview = await adapter.readResource({
uri: "webstudio://project/accessibility-review",
});
@@ -5178,6 +5514,21 @@ describe("project session mcp adapter", () => {
expect(accessibilityReview.contents[0]?.text).toContain(
"Community-Access/accessibility-agents"
);
+ expect(expressions.contents[0]).toEqual(
+ expect.objectContaining({
+ mimeType: "text/markdown",
+ text: expect.stringContaining("# Webstudio Expressions"),
+ })
+ );
+ expect(expressions.contents[0]?.text).toContain("Supported string methods");
+ expect(expressions.contents[0]?.text).toContain("- `toLowerCase`");
+ expect(expressions.contents[0]?.text).toContain("- `join`");
+ expect(expressions.contents[0]?.text).not.toContain(
+ "{{allowedStringMethods}}"
+ );
+ expect(expressions.contents[0]?.text).toContain(
+ "Collection creates internal `collectionItem` and `collectionItemKey`"
+ );
const componentOverviewData = JSON.parse(
componentsOverview.contents[0]?.text ?? "{}"
);
@@ -5278,6 +5629,13 @@ describe("project session mcp adapter", () => {
destructiveHint: false,
}),
}),
+ expect.objectContaining({
+ name: "components.coverage-status",
+ annotations: expect.objectContaining({
+ readOnlyHint: true,
+ destructiveHint: false,
+ }),
+ }),
expect.objectContaining({
name: "refresh",
annotations: expect.objectContaining({
@@ -5314,6 +5672,42 @@ describe("project session mcp adapter", () => {
}
});
+ test("keeps one MCP SDK connection healthy across repeated reads and mutations", async () => {
+ const executeOperation = createExecuteOperation(async ({ command }) =>
+ createEnvelope({
+ operationId: command === "list-pages" ? "pages.list" : "pages.update",
+ result: command === "list-pages" ? { pages: [] } : { pageId: "home" },
+ })
+ );
+ const server = await createProjectSessionMcpServer({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation,
+ });
+ const { client, close } = await createConnectedClient(server);
+
+ try {
+ for (let index = 0; index < 50; index += 1) {
+ const read = await client.callTool({
+ name: "list-pages",
+ arguments: {},
+ });
+ expect(read.isError).not.toBe(true);
+ const mutation = await client.callTool({
+ name: "update-page",
+ arguments: {
+ pageId: "home",
+ values: { title: `Session title ${index}` },
+ },
+ });
+ expect(mutation.isError).not.toBe(true);
+ }
+ expect(executeOperation).toHaveBeenCalledTimes(100);
+ } finally {
+ await close();
+ }
+ });
+
test("sends sparse protocol-native startup logging after initialization", async () => {
const server = await createProjectSessionMcpServer({
operations: publicMcpOperations,
@@ -5404,6 +5798,92 @@ describe("project session mcp adapter", () => {
}
});
+ test("returns schema-valid rendered failures and stores their artifact manifest through the server", async () => {
+ const storeRenderedAuditArtifacts = vi.fn(async () => "/manifest.json");
+ const executeOperation = createExecuteOperation(async ({ command }) => {
+ if (command === "list-pages") {
+ return createEnvelope({
+ operationId: "pages.list",
+ result: { pages: [{ id: "home", path: "/" }] },
+ });
+ }
+ if (command === "list-breakpoints") {
+ return createEnvelope({
+ operationId: "breakpoints.list",
+ result: { breakpoints: [] },
+ });
+ }
+ return createEnvelope({
+ operationId: "project.audit",
+ result: {
+ contractVersion: 2,
+ projectVersion: 7,
+ scopes: ["accessibility"],
+ pageFilter: null,
+ summary: {
+ total: 0,
+ bySeverity: { error: 0, warning: 0, info: 0 },
+ byScope: { accessibility: 0 },
+ },
+ verbose: true,
+ findings: [],
+ skippedCheckCount: 0,
+ skippedChecks: [],
+ manualCheckCount: 1,
+ manualChecks: [{ checkId: "responsive-visual-review" }],
+ renderedCheckCount: 0,
+ renderedIssueCount: 0,
+ renderedFailureCount: 0,
+ renderedChecks: [],
+ renderedFailures: [],
+ nextCursor: null,
+ },
+ });
+ });
+ const server = await createProjectSessionMcpServer({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation,
+ startPreview: vi.fn(async () => {
+ throw new Error("preview build failed");
+ }),
+ getPreviewStatus: vi.fn(),
+ stopPreview: vi.fn(),
+ captureScreenshot: vi.fn(),
+ storeRenderedAuditArtifacts,
+ });
+ const { client, close } = await createConnectedClient(server);
+
+ try {
+ const result = await client.callTool({
+ name: "audit",
+ arguments: { rendered: true, verbose: true },
+ });
+
+ expect(result).toMatchObject({
+ isError: true,
+ structuredContent: {
+ ok: false,
+ error: { code: "RENDERED_AUDIT_FAILED" },
+ data: { renderedFailureCount: 1 },
+ },
+ });
+ expect(storeRenderedAuditArtifacts).toHaveBeenCalledWith(
+ expect.objectContaining({
+ projectId: "project-1",
+ projectVersion: 1,
+ failures: [
+ expect.objectContaining({
+ code: "RENDERED_AUDIT_PREVIEW_START_FAILED",
+ }),
+ ],
+ })
+ );
+ } finally {
+ await close();
+ }
+ });
+
test("sends visible fallback and heartbeat logs for long-running tools", async () => {
const reportLog = vi.fn();
const executeOperation = createExecuteOperation(
@@ -5536,6 +6016,14 @@ describe("project session mcp adapter", () => {
openWorldHint: true,
}),
}),
+ expect.objectContaining({
+ name: "preview.stop",
+ annotations: expect.objectContaining({
+ readOnlyHint: false,
+ destructiveHint: false,
+ openWorldHint: true,
+ }),
+ }),
expect.objectContaining({
name: "screenshot",
annotations: expect.objectContaining({
@@ -5738,7 +6226,17 @@ describe("project session mcp adapter", () => {
ok: false,
error: {
message: expect.stringContaining('"email":"[email protected]"'),
- code: "MCP_TOOL_FAILED",
+ code: "INVALID_INPUT",
+ issues: expect.arrayContaining([
+ expect.objectContaining({
+ path: ["email"],
+ message: expect.any(String),
+ }),
+ expect.objectContaining({
+ path: ["description"],
+ message: expect.any(String),
+ }),
+ ]),
},
meta: {},
},
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index a875f96390..6468d72847 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -3,9 +3,12 @@ import {
type BuilderNamespace,
} from "./contracts/namespaces";
import {
+ allowedArrayMethods,
+ allowedStringMethods,
getInputJsonSchemaMetadata,
getInputJsonSchemaProperties,
inputJsonSchemaAcceptsType,
+ parseComponentName,
toInputJsonSchemaObject,
type InputJsonSchema,
} from "@webstudio-is/sdk";
@@ -19,7 +22,10 @@ import {
} from "./project-session";
import type { ScreenshotVisualExpectation } from "./visual/screenshot-diff";
import { isPlainRecord, isRecord } from "./shared/type-utils";
-import { augmentAuditWithRenderedChecks } from "./mcp-rendered-audit";
+import {
+ augmentAuditWithRenderedChecks,
+ type RenderedAuditArtifactManifest,
+} from "./mcp-rendered-audit";
import {
defaultScreenshotTimeout,
defaultScreenshotWaitForTimeout,
@@ -41,7 +47,6 @@ import {
ListToolsRequestSchema,
ReadResourceRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
-import { parseComponentName } from "@webstudio-is/sdk";
import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";
import { readProjectBuildDoc } from "./docs";
import type { ComponentTemplateRegistry } from "./runtime/component-template";
@@ -113,6 +118,7 @@ export type ProjectSessionScreenshotInput = {
output?: string;
host?: string;
port?: number;
+ imageDomains?: string[];
source?: "local" | "session";
viewport: {
width: number;
@@ -127,6 +133,9 @@ export type ProjectSessionScreenshotInput = {
waitForSelector?: string;
waitForTimeout?: number;
timeout?: number;
+ format?: "png" | "jpeg" | "webp";
+ quality?: number;
+ scale?: number;
};
export type ProjectSessionScreenshotResult = {
@@ -140,7 +149,41 @@ export type ProjectSessionScreenshotResult = {
fullPage: boolean;
elapsedMs: number;
warnings: readonly string[];
+ timings?: {
+ wallMs: number;
+ targetSetupMs: number;
+ navigationMs: number;
+ readinessMs: number;
+ imageInspectionMs: number;
+ resourceInspectionMs: number;
+ screenshotMs: number;
+ artifactWriteMs: number;
+ targetCleanupMs: number;
+ };
+ navigation?: {
+ requestedUrl: string;
+ finalUrl: string;
+ status?: number;
+ statusText?: string;
+ mimeType?: string;
+ redirects: string[];
+ documentReadyState: string;
+ generatedSiteRootPresent: boolean;
+ layoutStable: boolean;
+ };
layout?: {
+ navigation?: {
+ requestedUrl: string;
+ finalUrl: string;
+ status?: number;
+ statusText?: string;
+ mimeType?: string;
+ redirects: string[];
+ documentReadyState: string;
+ generatedSiteRootPresent: boolean;
+ layoutStable: boolean;
+ };
+ documentType?: string;
viewportWidth: number;
viewportHeight: number;
contentWidth: number;
@@ -148,10 +191,13 @@ export type ProjectSessionScreenshotResult = {
horizontalOverflow: boolean;
images?: Array<{
instanceId?: string;
+ sourcePathname?: string;
loading: string;
complete: boolean;
naturalWidth: number;
naturalHeight: number;
+ selectedSourceWidth?: number;
+ selectedSourceHeight?: number;
renderedWidth: number;
renderedHeight: number;
top: number;
@@ -177,6 +223,11 @@ type CaptureScreenshot = (
progress?: McpToolProgress
) => Promise<ProjectSessionScreenshotResult>;
+type CapturePageScreenshots = (
+ inputs: readonly ProjectSessionScreenshotInput[],
+ progress?: McpToolProgress
+) => Promise<ProjectSessionScreenshotResult[]>;
+
export type ProjectSessionScreenshotDiffInput = {
baselinePath: string;
currentPath: string;
@@ -206,6 +257,7 @@ export type ProjectSessionPreviewInput = {
host?: string;
port?: number;
source?: "local" | "session";
+ imageDomains?: string[];
};
export type ProjectSessionPreviewResult = {
@@ -877,6 +929,12 @@ const screenshotInputSchema = {
description:
"Port used when screenshot starts or restarts the generated-site preview for a path.",
},
+ imageDomains: {
+ type: "array",
+ description:
+ "External image hostnames allowed by the generated preview optimizer, for example storage.example.com.",
+ items: { type: "string" },
+ },
},
required: ["viewport"],
} as const satisfies ProjectSessionMcpInputSchema;
@@ -898,6 +956,39 @@ const renderedAuditInputProperty = {
"Run a rendered responsive pass through this long-lived MCP session. Cannot be combined with cursor pagination.",
} as const;
+const renderedAuditConfirmationInputProperties = {
+ confirmLargeRun: {
+ type: "boolean",
+ description:
+ "Confirm an audit plan above the unconfirmed capture threshold. Requires the unchanged plan's confirmationToken.",
+ },
+ confirmationToken: {
+ type: "string",
+ description:
+ "Short-lived token returned with a large rendered plan. Use with confirmLargeRun: true.",
+ },
+ imageDomains: {
+ type: "array",
+ description:
+ "External image hostnames allowed by the generated preview optimizer during rendered audit.",
+ items: { type: "string" },
+ },
+ routeExamples: {
+ type: "array",
+ description:
+ 'Concrete paths for dynamic pages, identified by page id. For example [{"pageId":"post","path":"/blog/hello"}].',
+ items: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ pageId: { type: "string" },
+ path: { type: "string" },
+ },
+ required: ["pageId", "path"],
+ },
+ },
+} as const;
+
const getMcpOperationInputSchema = (
operation: PublicMcpOperation,
options: { includeRenderedAudit: boolean }
@@ -911,6 +1002,7 @@ const getMcpOperationInputSchema = (
properties: {
...schema.properties,
rendered: renderedAuditInputProperty,
+ ...renderedAuditConfirmationInputProperties,
},
} satisfies InputJsonSchema;
};
@@ -1033,6 +1125,12 @@ const previewInputSchema = {
description:
"Project data source for generated preview: local uses .webstudio/data.json; session materializes the current ProjectSession snapshot first, which is the right choice after MCP mutations.",
},
+ imageDomains: {
+ type: "array",
+ description:
+ "External image hostnames allowed by the generated preview optimizer, for example storage.example.com.",
+ items: { type: "string" },
+ },
},
} as const satisfies ProjectSessionMcpInputSchema;
@@ -1325,7 +1423,7 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
searchParams: [
{ name: "tag", value: "filters.tag" },
{ name: "source", value: { type: "literal", value: "website" } },
- { name: "page", value: "String(filters.page ?? 1)" },
+ { name: "page", value: "(filters.page ?? 1).toString()" },
],
headers: [{ name: "Authorization", value: '"Bearer " + auth.token' }],
},
@@ -1348,6 +1446,7 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
},
scopeInstanceId: "body-id",
dataSourceName: "post",
+ exposeAsDataSource: true,
},
{
resource: {
@@ -1366,6 +1465,11 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
resourceId: "resource-id",
values: { url: "https://api.example.com/posts" },
},
+ {
+ resourceId: "resource-id",
+ values: { method: "post" },
+ exposeAsDataSource: false,
+ },
],
"update-asset": [
{
@@ -2023,15 +2127,26 @@ const previewTools: readonly ProjectSessionMcpTool[] = [
}),
];
-type ProjectSessionMcpStructuredContent = {
- ok: true;
- data: unknown;
- meta: {
- session?:
- | ReturnType<typeof serializeProjectSessionMeta>
- | ReturnType<typeof serializeProjectSessionDebug>;
- };
-};
+type ProjectSessionMcpStructuredContent =
+ | {
+ ok: true;
+ data: unknown;
+ meta: {
+ session?:
+ | ReturnType<typeof serializeProjectSessionMeta>
+ | ReturnType<typeof serializeProjectSessionDebug>;
+ };
+ }
+ | {
+ ok: false;
+ data: unknown;
+ error: { code: string; message: string };
+ meta: {
+ session?:
+ | ReturnType<typeof serializeProjectSessionMeta>
+ | ReturnType<typeof serializeProjectSessionDebug>;
+ };
+ };
class ProjectSessionMcpCheckpointError extends Error {
code = "CHECKPOINT_REQUIRED";
@@ -2070,17 +2185,44 @@ type SdkTool = {
};
};
-export const hiddenMcpOperationCommands = new Set<string>();
+export const hiddenMcpOperationCommands = new Set<string>([
+ // Hydrated Map-backed sourceData is available only to typed API callers.
+ // MCP callers use duplicate-page or serializable page-transfer workflows.
+ "copy-page",
+]);
const getMcpOutputSchema = (dataSchema: InputJsonSchema): InputJsonSchema => ({
- type: "object",
- properties: {
- ok: { type: "boolean", const: true },
- data: dataSchema,
- meta: { type: "object", additionalProperties: true },
- },
- required: ["ok", "data", "meta"],
- additionalProperties: false,
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ ok: { type: "boolean", const: true },
+ data: dataSchema,
+ meta: { type: "object", additionalProperties: true },
+ },
+ required: ["ok", "data", "meta"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ ok: { type: "boolean", const: false },
+ data: dataSchema,
+ error: {
+ type: "object",
+ properties: {
+ code: { type: "string" },
+ message: { type: "string" },
+ },
+ required: ["code", "message"],
+ additionalProperties: true,
+ },
+ meta: { type: "object", additionalProperties: true },
+ },
+ required: ["ok", "error", "meta"],
+ additionalProperties: false,
+ },
+ ],
});
export const listProjectSessionMcpTools = (
@@ -3004,6 +3146,20 @@ const filterCapabilities = (tools: readonly ProjectSessionMcpTool[]) => {
};
const startupGuidance = readProjectBuildDoc("mcp-startup-guidance").trim();
+const formatExpressionMethods = (methods: ReadonlySet<string>) =>
+ [...methods]
+ .sort((left, right) => left.localeCompare(right))
+ .map((method) => `- \`${method}\``)
+ .join("\n");
+const expressionsGuide = readProjectBuildDoc("expressions")
+ .replace(
+ "{{allowedStringMethods}}",
+ formatExpressionMethods(allowedStringMethods)
+ )
+ .replace(
+ "{{allowedArrayMethods}}",
+ formatExpressionMethods(allowedArrayMethods)
+ );
const valuesVsBindingsRule =
"Use direct value tools for fixed text/props. Use bindings only for dynamic expressions, resources, actions, or existing scoped runtime context such as system. Parameters are internal scoped runtime values, not a public create/update/delete surface. Page metadata and fixed resource URLs accept plain strings; use JavaScript expression code only when values are computed. Page and resource updates put changed fields under values.";
@@ -3072,6 +3228,9 @@ const animationComponentGuidanceByComponent = new Map<string, string>([
const getAnimationComponentGuidance = (component: string) =>
animationComponentGuidanceByComponent.get(component);
+const collectionComponentUsage =
+ 'Use Collection whenever an array or object from a resource or data variable should render a repeated list, grid, set of cards, table rows, options, tabs, or similar UI. Insert "ws:collection" with insert-component so Webstudio creates and preserves its internal item and itemKey parameters. Bind the Collection data prop to the complete array or object, not the resource response wrapper and not one indexed item; external resource arrays are often nested under the scoped resource result\'s data field or deeper. Collection renders its child structure once per entry. Array iteration exposes the current item as `collectionItem`; object iteration exposes the current value as `collectionItem` and key as `collectionItemKey`. Bind descendant content and props with expressions such as `collectionItem.name`; do not reuse encoded parameter ids from another Collection. Wrap multiple repeated sibling instances in one Element. For repeated Radix items, bind a stable unique id or slug to each required value prop. Do not create, replace, or delete the internal item/itemKey parameter records directly.';
+
const getComponentCatalog = () => ({
source: "@webstudio-is/sdk-components-registry/metas",
usage:
@@ -3576,11 +3735,9 @@ const getAvailableComponentEntries = async ({
const getComponentCoverageStatus = async ({
input,
executeOperation,
- dryRun,
}: {
input: unknown;
executeOperation: ExecuteMcpOperation;
- dryRun: boolean;
}) => {
const { pageId, pagePath, documentType } = getCoverageStatusInput(input);
const envelope = await executeOperation({
@@ -3589,7 +3746,7 @@ const getComponentCoverageStatus = async ({
pageId,
pagePath,
},
- dryRun,
+ dryRun: false,
});
const instancesResult = envelope.result;
if (
@@ -3684,7 +3841,6 @@ const getComponentCoverageInsertNext = async ({
const before = await getComponentCoverageStatus({
input: definedStatusInput,
executeOperation,
- dryRun,
});
const missingRoots = before.missingRoots;
const missingParts = before.missingParts;
@@ -3758,7 +3914,6 @@ const getComponentCoverageInsertNext = async ({
const after = await getComponentCoverageStatus({
input: definedStatusInput,
executeOperation,
- dryRun,
});
return {
usage:
@@ -3927,6 +4082,8 @@ const getComponentDetails = (component: string) => {
const meta = componentMetas.get(component);
const stateUsage = getComponentStateUsage(meta?.states);
const animationUsage = getAnimationComponentGuidance(component);
+ const collectionUsage =
+ component === "ws:collection" ? collectionComponentUsage : undefined;
const jsonLdUsage =
component === "JsonLd"
? 'Prefer placing JsonLd inside HeadSlot. Insert it with insert-component using the HeadSlot instance as parentInstanceId and component "JsonLd". Set its code prop with update-props using type "string" and a compact JSON object or array string. Fixed values with structurally invalid JSON-LD are rejected. Run audit with the seo scope after editing to find unknown, superseded, unsupported, or incompatible Schema.org terms; vocabulary findings are warnings because custom vocabularies remain valid.'
@@ -3936,7 +4093,7 @@ const getComponentDetails = (component: string) => {
found: false,
component,
usage:
- "Component id was not found in the known registry. Unknown component ids may still be inserted as custom single instances.",
+ 'Component id was not found in the known registry. Do not insert a guessed component id; use components.search, components.list, or templates.list to discover the exact id. For a native HTML element, use component "ws:element" with its "tag" property instead of inventing an id such as "ws:div".',
};
}
return {
@@ -3949,6 +4106,7 @@ const getComponentDetails = (component: string) => {
states: meta.states ?? [],
stateUsage,
animationUsage,
+ collectionUsage,
jsonLdUsage,
indexWithinAncestor: meta.indexWithinAncestor,
usage: [
@@ -3957,6 +4115,7 @@ const getComponentDetails = (component: string) => {
: "Do not insert this component standalone. It is a child/part component and must be created by inserting a containing root/template component.",
stateUsage,
animationUsage,
+ collectionUsage,
jsonLdUsage,
]
.filter(Boolean)
@@ -4007,6 +4166,8 @@ const getMetaIndex = (
'Use components.list({"source":"all"}) for shadcn-compatible registry items, templates.list({}) for templates, components.summary for a compact catalog, components.coverage-plan for design-system/all-component tasks, components.coverage-insert-next({"pagePath":"/design-system","parentInstanceId":"root-id"}) for one checkpoint-safe coverage insertion, components.coverage-status({"pagePath":"/design-system"}) to verify progress, components.search({"brief":"radix select"}) to search, and components.get({"component":"@webstudio-is/sdk-components-react-radix:Select"}) or templates.get({"component":"@webstudio-is/sdk-components-react-radix:Select"}) for one item. Do not dump or parse webstudio://project/components unless those focused tools are insufficient.',
guide:
'Use meta.guide({"brief":"Create a design system page using every component"}) for a goal-specific workflow.',
+ expressions:
+ "Read webstudio://project/expressions before authoring unfamiliar expressions, Collection item bindings, or dynamic resource fields.",
accessibility:
"For an accessibility review, read webstudio://project/accessibility-review, run audit with scopes [accessibility], then verify changed routes with preview and screenshots.",
workflow:
@@ -4040,6 +4201,14 @@ const getMetaGuide = (
guidance: ProjectSessionMcpGuidance | undefined
) => {
const isJsonLdGoal = /json\s*-?\s*ld|structured\s+data/i.test(brief);
+ const isCollectionGoal =
+ /collection|repeat(?:ed|ing)?\s+(?:list|item|card|row|content)|render\s+(?:an?\s+)?array|array\s+(?:as|into)\s+(?:a\s+)?(?:list|grid|table|cards?)/i.test(
+ brief
+ );
+ const isExpressionGoal =
+ /\bexpressions?\b|computed\s+(?:text|value|prop|metadata|url)|dynamic\s+(?:text|prop|binding)/i.test(
+ brief
+ );
const matches = isJsonLdGoal
? getExactTools(
[
@@ -4051,7 +4220,32 @@ const getMetaGuide = (
],
tools
)
- : getMatchingTools(brief, tools).slice(0, 12);
+ : isCollectionGoal
+ ? getExactTools(
+ [
+ "components.get",
+ "list-variables",
+ "list-resources",
+ "insert-component",
+ "inspect-instance",
+ "bind-props",
+ ],
+ tools
+ )
+ : isExpressionGoal
+ ? getExactTools(
+ [
+ "list-variables",
+ "list-resources",
+ "list-texts",
+ "inspect-instance",
+ "update-text",
+ "bind-props",
+ "update-resource",
+ ],
+ tools
+ )
+ : getMatchingTools(brief, tools).slice(0, 12);
const canVerifyVisually =
tools.some((tool) => tool.name === "preview.start") &&
tools.some((tool) => tool.name === "screenshot");
@@ -4071,6 +4265,23 @@ const getMetaGuide = (
'Run audit with {"scopes":["seo"],"pagePath":"<path>"} and fix any JSON-LD finding.',
]
: []),
+ ...(isCollectionGoal
+ ? [
+ 'Call components.get with {"component":"ws:collection"} and use its Collection-specific guidance.',
+ "Find the array or object to repeat. For a scoped resource result, select the complete nested array/object, commonly below the result's data field; do not bind the response wrapper or one indexed item.",
+ 'Insert "ws:collection" with insert-component so its internal item and itemKey parameters are created. Do not create or replace those parameter records manually.',
+ "Bind the Collection data prop to the complete iterable. Put the repeated UI under Collection and bind descendant text/props to the generated current-item context; wrap multiple sibling instances in one Element.",
+ "Verify that every array/object entry renders once. For repeated Radix items, bind a stable unique id or slug to required value props.",
+ ]
+ : []),
+ ...(isExpressionGoal
+ ? [
+ "Read webstudio://project/expressions for the supported syntax, method allowlist, scope rules, and encoding examples.",
+ "Read variables, resources, the target instance, and existing bindings before writing an expression; do not guess scoped identifier names.",
+ "Use one expression rather than a statement or function. Use direct values for fixed content and expressions only for runtime-computed values.",
+ "Preview the affected route with representative and empty data; successful syntax validation does not prove the runtime data shape or scope is correct.",
+ ]
+ : []),
"Use the fewest discovery calls needed for the immediate action.",
"Call permissions or status only when the task depends on capabilities or local session freshness.",
matches.some((tool) => tool.annotations.localCapable)
@@ -4313,13 +4524,13 @@ const readOnlySessionTools = new Set([
"components.summary",
"components.list",
"components.coverage-plan",
+ "components.coverage-status",
"components.find",
"components.search",
"components.get",
"templates.list",
"templates.get",
"preview.status",
- "preview.stop",
]);
const toolAliases = new Map([
@@ -4397,6 +4608,13 @@ export const listProjectSessionMcpResources =
"Concise model-facing guide for discovering and choosing Webstudio MCP tools.",
mimeType: "application/json",
},
+ {
+ uri: "webstudio://project/expressions",
+ name: "Webstudio expressions",
+ description:
+ "Model-facing reference for expression syntax, scope, supported methods, bindings, Collections, and verification.",
+ mimeType: "text/markdown",
+ },
{
uri: "webstudio://project/accessibility-review",
name: "Webstudio accessibility review",
@@ -4408,18 +4626,30 @@ export const listProjectSessionMcpResources =
const toCallResult = (
envelope: Parameters<typeof serializeProjectSessionMeta>[0],
- options: { verboseSession?: boolean } = {}
+ options: {
+ verboseSession?: boolean;
+ error?: { code: string; message: string };
+ } = {}
): ProjectSessionMcpToolResult => {
- const structuredContent = {
- ok: true as const,
- data: envelope.result,
- meta: {
- session:
- options.verboseSession === true
- ? serializeProjectSessionDebug(envelope)
- : serializeProjectSessionMeta(envelope),
- },
+ const meta = {
+ session:
+ options.verboseSession === true
+ ? serializeProjectSessionDebug(envelope)
+ : serializeProjectSessionMeta(envelope),
};
+ const structuredContent: ProjectSessionMcpStructuredContent =
+ options.error === undefined
+ ? {
+ ok: true,
+ data: envelope.result,
+ meta,
+ }
+ : {
+ ok: false,
+ data: envelope.result,
+ error: options.error,
+ meta,
+ };
return {
content: [
{
@@ -4428,9 +4658,52 @@ const toCallResult = (
},
],
structuredContent,
+ ...(options.error === undefined ? {} : { isError: true }),
};
};
+const getRenderedAuditError = (
+ envelope: Parameters<typeof serializeProjectSessionMeta>[0],
+ rendered: boolean
+) => {
+ if (rendered === false || isRecord(envelope.result) === false) {
+ return undefined;
+ }
+ const failureCount = envelope.result.renderedFailureCount;
+ if (typeof failureCount !== "number" || failureCount === 0) {
+ return undefined;
+ }
+ const failures = Array.isArray(envelope.result.renderedFailures)
+ ? envelope.result.renderedFailures
+ : envelope.result.renderedFailureSummaries;
+ const confirmationRequired =
+ Array.isArray(failures) &&
+ failures.length > 0 &&
+ failures.every(
+ (failure) =>
+ isRecord(failure) &&
+ failure.code === "RENDERED_AUDIT_CONFIRMATION_REQUIRED"
+ );
+ if (confirmationRequired) {
+ return undefined;
+ }
+ const checkCount =
+ typeof envelope.result.renderedCheckCount === "number"
+ ? envelope.result.renderedCheckCount
+ : 0;
+ return checkCount === 0
+ ? {
+ code: "RENDERED_AUDIT_FAILED",
+ message:
+ "The static audit completed, but the requested rendered audit completed no rendered checks.",
+ }
+ : {
+ code: "RENDERED_AUDIT_PARTIAL",
+ message:
+ "The static audit completed, but some requested rendered checks failed.",
+ };
+};
+
const toResourceContent = (
envelope: Parameters<typeof serializeProjectSessionMeta>[0]
) => ({
@@ -4556,15 +4829,34 @@ const getScreenshotInput = (input: unknown): ProjectSessionScreenshotInput => {
) {
throw new Error("screenshot port must be an integer between 1 and 65535.");
}
+ const imageDomains = input.imageDomains;
+ if (
+ imageDomains !== undefined &&
+ (Array.isArray(imageDomains) === false ||
+ imageDomains.some(
+ (domain) =>
+ typeof domain !== "string" ||
+ /^[a-z0-9.-]+(?::\d+)?$/i.test(domain) === false
+ ))
+ ) {
+ throw new Error(
+ "screenshot imageDomains must contain hostnames without a protocol or path."
+ );
+ }
if (baseUrl !== undefined) {
try {
new URL(baseUrl);
} catch {
throw new Error("screenshot baseUrl must be an absolute URL.");
}
- if (host !== undefined || port !== undefined || source !== undefined) {
+ if (
+ host !== undefined ||
+ port !== undefined ||
+ source !== undefined ||
+ imageDomains !== undefined
+ ) {
throw new Error(
- "screenshot baseUrl uses an existing preview/site and cannot be combined with host, port, or source."
+ "screenshot baseUrl uses an existing preview/site and cannot be combined with host, port, source, or imageDomains."
);
}
}
@@ -4575,6 +4867,7 @@ const getScreenshotInput = (input: unknown): ProjectSessionScreenshotInput => {
output: typeof input.output === "string" ? input.output : undefined,
host,
port,
+ imageDomains,
source,
viewport: { width, height },
fullPage: input.fullPage === true,
@@ -4757,10 +5050,25 @@ const getPreviewInput = (input: unknown): ProjectSessionPreviewInput => {
if (source !== undefined && source !== "local" && source !== "session") {
throw new Error("preview source must be local or session.");
}
+ const imageDomains = input.imageDomains;
+ if (
+ imageDomains !== undefined &&
+ (Array.isArray(imageDomains) === false ||
+ imageDomains.some(
+ (domain) =>
+ typeof domain !== "string" ||
+ /^[a-z0-9.-]+(?::\d+)?$/i.test(domain) === false
+ ))
+ ) {
+ throw new Error(
+ "preview imageDomains must contain hostnames without a protocol or path."
+ );
+ }
return {
host,
port,
source,
+ imageDomains,
};
};
@@ -4789,6 +5097,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
executeOperation,
importProject,
captureScreenshot,
+ capturePageScreenshots,
diffScreenshots,
installOcr,
startPreview,
@@ -4796,12 +5105,14 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
stopPreview,
guidance,
reportToolProgress,
+ storeRenderedAuditArtifacts,
}: {
operations: readonly (PublicMcpOperation & { command: Command })[];
createProjectSession: CreateProjectSession;
executeOperation: ExecuteMcpOperation<Command>;
importProject?: ImportProject;
captureScreenshot?: CaptureScreenshot;
+ capturePageScreenshots?: CapturePageScreenshots;
diffScreenshots?: DiffScreenshots;
installOcr?: InstallOcr;
startPreview?: StartPreview;
@@ -4809,6 +5120,9 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
stopPreview?: StopPreview;
guidance?: ProjectSessionMcpGuidance;
reportToolProgress?: (message: string) => void;
+ storeRenderedAuditArtifacts?: (
+ manifest: RenderedAuditArtifactManifest
+ ) => Promise<string>;
}) => {
let session: ReturnType<CreateProjectSession> | undefined;
let pendingCheckpoint: ProjectSessionMcpCheckpoint | undefined;
@@ -4904,6 +5218,17 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
],
};
}
+ if (uri === "webstudio://project/expressions") {
+ return {
+ contents: [
+ {
+ uri,
+ mimeType: "text/markdown",
+ text: expressionsGuide,
+ },
+ ],
+ };
+ }
if (uri === "webstudio://project/accessibility-review") {
return {
contents: [
@@ -4935,10 +5260,12 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
name,
input = {},
dryRun = false,
+ signal,
}: {
name: string;
input?: unknown;
dryRun?: boolean;
+ signal?: AbortSignal;
}): Promise<ProjectSessionMcpToolResult> {
name = resolveToolName(name);
if (name === "checkpoint.ack") {
@@ -5015,7 +5342,6 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
await getComponentCoverageStatus({
input,
executeOperation: executeOperation as ExecuteMcpOperation,
- dryRun,
})
);
}
@@ -5121,7 +5447,70 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
) {
throw new Error("audit input.rendered must be a boolean.");
}
+ if (
+ isAuditInput &&
+ input.routeExamples !== undefined &&
+ (Array.isArray(input.routeExamples) === false ||
+ input.routeExamples.some(
+ (example) =>
+ isRecord(example) === false ||
+ typeof example.pageId !== "string" ||
+ example.pageId.length === 0 ||
+ typeof example.path !== "string" ||
+ /^\/(?!\/)/.test(example.path) === false ||
+ example.path.includes(":") ||
+ example.path.includes("*")
+ ))
+ ) {
+ throw new Error(
+ "audit input.routeExamples must contain { pageId, path } objects with concrete paths beginning with one slash."
+ );
+ }
const isRenderedAudit = isAuditInput && input.rendered === true;
+ const renderedOnlyInputFields = [
+ "confirmLargeRun",
+ "confirmationToken",
+ "imageDomains",
+ "routeExamples",
+ ] as const;
+ const providedRenderedOnlyInput = renderedOnlyInputFields.find(
+ (field) => isAuditInput && input[field] !== undefined
+ );
+ if (isAuditInput && isRenderedAudit === false) {
+ if (providedRenderedOnlyInput !== undefined) {
+ throw new Error(
+ `audit input.${providedRenderedOnlyInput} requires rendered: true.`
+ );
+ }
+ }
+ if (
+ isAuditInput &&
+ input.confirmLargeRun !== undefined &&
+ typeof input.confirmLargeRun !== "boolean"
+ ) {
+ throw new Error("audit input.confirmLargeRun must be a boolean.");
+ }
+ if (
+ isAuditInput &&
+ input.confirmationToken !== undefined &&
+ typeof input.confirmationToken !== "string"
+ ) {
+ throw new Error("audit input.confirmationToken must be a string.");
+ }
+ if (
+ isAuditInput &&
+ input.imageDomains !== undefined &&
+ (Array.isArray(input.imageDomains) === false ||
+ input.imageDomains.some(
+ (domain) =>
+ typeof domain !== "string" ||
+ /^[a-z0-9.-]+(?::\d+)?$/i.test(domain) === false
+ ))
+ ) {
+ throw new Error(
+ "audit input.imageDomains must contain hostnames without a protocol or path."
+ );
+ }
if (
isRenderedAudit &&
(startPreview === undefined ||
@@ -5141,7 +5530,14 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
operation,
isAuditInput
? Object.fromEntries(
- Object.entries(input).filter(([key]) => key !== "rendered")
+ Object.entries(input).filter(
+ ([key]) =>
+ key !== "rendered" &&
+ key !== "confirmLargeRun" &&
+ key !== "confirmationToken" &&
+ key !== "imageDomains" &&
+ key !== "routeExamples"
+ )
)
: input
);
@@ -5150,22 +5546,42 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
input: operationInput,
dryRun,
});
- return toCallResult(
- name === "audit"
- ? await augmentAuditWithRenderedChecks({
- envelope,
- input:
- isRenderedAudit && isRecord(operationInput)
- ? { ...operationInput, rendered: true }
- : operationInput,
- executeRead,
- startPreview,
- stopPreview,
- captureScreenshot,
- reportProgress: reportToolProgress,
- })
- : envelope
- );
+ if (name === "audit") {
+ const auditedEnvelope = await augmentAuditWithRenderedChecks({
+ envelope,
+ input:
+ isRenderedAudit && isRecord(operationInput)
+ ? {
+ ...operationInput,
+ rendered: true,
+ ...(input.confirmLargeRun === true
+ ? { confirmLargeRun: true }
+ : {}),
+ ...(typeof input.confirmationToken === "string"
+ ? { confirmationToken: input.confirmationToken }
+ : {}),
+ ...(Array.isArray(input.imageDomains)
+ ? { imageDomains: input.imageDomains }
+ : {}),
+ ...(Array.isArray(input.routeExamples)
+ ? { routeExamples: input.routeExamples }
+ : {}),
+ }
+ : operationInput,
+ executeRead,
+ startPreview,
+ stopPreview,
+ captureScreenshot,
+ capturePageScreenshots,
+ reportProgress: reportToolProgress,
+ storeRenderedAuditArtifacts,
+ signal,
+ });
+ return toCallResult(auditedEnvelope, {
+ error: getRenderedAuditError(auditedEnvelope, isRenderedAudit),
+ });
+ }
+ return toCallResult(envelope);
},
};
};
@@ -5299,12 +5715,21 @@ const getZodErrorMessage = (
return `${issues}. Expected input shape example: ${JSON.stringify(example)}`;
};
+const getZodFieldIssues = (error: z.ZodError) =>
+ error.issues.map((issue) => ({
+ path: issue.path.map(String),
+ message: issue.message,
+ }));
+
const toToolErrorResult = (
error: unknown,
getErrorCode: McpErrorCodeResolver | undefined,
inputSchema?: InputJsonSchema
): ProjectSessionMcpErrorResult => {
- const code = getErrorCode?.(error) ?? "MCP_TOOL_FAILED";
+ const code =
+ error instanceof z.ZodError
+ ? "INVALID_INPUT"
+ : (getErrorCode?.(error) ?? "MCP_TOOL_FAILED");
const message =
code === "PROJECT_SESSION_BUSY"
? projectSessionBusyMessage
@@ -5318,6 +5743,9 @@ const toToolErrorResult = (
error: {
message,
code,
+ ...(error instanceof z.ZodError
+ ? { issues: getZodFieldIssues(error) }
+ : {}),
},
meta: {},
};
@@ -5336,6 +5764,7 @@ export const createProjectSessionMcpServer = async <
executeOperation,
importProject,
captureScreenshot,
+ capturePageScreenshots,
diffScreenshots,
installOcr,
startPreview,
@@ -5344,6 +5773,7 @@ export const createProjectSessionMcpServer = async <
guidance,
getErrorCode,
reportLog,
+ storeRenderedAuditArtifacts,
toolHeartbeatIntervalMs = 10_000,
}: {
operations: readonly (PublicMcpOperation & { command: Command })[];
@@ -5351,6 +5781,7 @@ export const createProjectSessionMcpServer = async <
executeOperation: ExecuteMcpOperation<Command>;
importProject?: ImportProject;
captureScreenshot?: CaptureScreenshot;
+ capturePageScreenshots?: CapturePageScreenshots;
diffScreenshots?: DiffScreenshots;
installOcr?: InstallOcr;
startPreview?: StartPreview;
@@ -5359,6 +5790,9 @@ export const createProjectSessionMcpServer = async <
guidance?: ProjectSessionMcpGuidance;
getErrorCode?: McpErrorCodeResolver;
reportLog?: (level: McpLogLevel, message: string) => void;
+ storeRenderedAuditArtifacts?: (
+ manifest: RenderedAuditArtifactManifest
+ ) => Promise<string>;
toolHeartbeatIntervalMs?: number;
}) => {
const server = new Server(
@@ -5386,12 +5820,14 @@ export const createProjectSessionMcpServer = async <
executeOperation,
importProject,
captureScreenshot,
+ capturePageScreenshots,
diffScreenshots,
installOcr,
startPreview,
getPreviewStatus,
stopPreview,
guidance,
+ storeRenderedAuditArtifacts,
reportToolProgress: (message) => {
sendLog("info", message);
},
@@ -5446,7 +5882,7 @@ export const createProjectSessionMcpServer = async <
}
});
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
const params = getRequestParams(request);
const name = typeof params.name === "string" ? params.name : "";
const { input, dryRun } = getToolCallInput(params.arguments ?? {});
@@ -5466,6 +5902,7 @@ export const createProjectSessionMcpServer = async <
name,
input,
dryRun,
+ signal: extra.signal,
});
sendLog("info", `tool ${name} succeeded in ${Date.now() - startedAt}ms`);
return result;
diff --git a/packages/project-build/src/project-session.test.ts b/packages/project-build/src/project-session.test.ts
index a30e88757f..cd83e9e458 100644
--- a/packages/project-build/src/project-session.test.ts
+++ b/packages/project-build/src/project-session.test.ts
@@ -20,6 +20,7 @@ import type {
} from "./project-session";
import { createBuilderStateFromSnapshot } from "./state/adapters";
import { createBuilderStateFreshness } from "./state/freshness";
+import { applyBuilderPatchTransactions } from "./state/patch";
import { build } from "./state/fixtures.test-utils";
const compatibilityVersion = "test-session";
@@ -137,16 +138,18 @@ const createSession = ({
}: {
storage?: ProjectSessionStorage;
transport?: ProjectSessionTransport;
-} = {}) =>
- createProjectSession({
+} = {}) => {
+ let generatedId = 0;
+ return createProjectSession({
projectId: "project-1",
storage,
transport,
compatibilityVersion,
runtimeContext: {
- createId: () => "generated-id",
+ createId: () => `generated-id-${generatedId++}`,
},
});
+};
describe("project session", () => {
test("derives default compatibility from the full runtime contract shape", () => {
@@ -176,7 +179,7 @@ describe("project session", () => {
expect(result.source).toBe("local");
expect(result.state.committed).toBe(false);
- expect(result.namespaces.read).toEqual(["pages", "projectSettings"]);
+ expect(result.namespaces.read).toEqual(["pages"]);
expect(transport.loadedNamespaces).toEqual([]);
});
@@ -205,10 +208,113 @@ describe("project session", () => {
const result = await session.read("pages.list", { projectId: "project-1" });
expect(result.source).toBe("local");
- expect(transport.loadedNamespaces).toEqual([["pages", "projectSettings"]]);
+ expect(transport.loadedNamespaces).toEqual([["pages"]]);
expect(storage.saved).toHaveLength(1);
});
+ test("duplicates a page from a cold session with assets hydrated", async () => {
+ const remote = createSnapshot({
+ state: createBuilderStateFromSnapshot({
+ ...build,
+ assets: [
+ [
+ "asset-hero",
+ {
+ id: "asset-hero",
+ projectId: "project-1",
+ name: "hero.png",
+ type: "image",
+ size: 128,
+ format: "png",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ description: "Product hero",
+ meta: { width: 1200, height: 800 },
+ },
+ ],
+ ],
+ instances: [
+ [
+ "instance-root",
+ {
+ type: "instance",
+ id: "instance-root",
+ component: "Body",
+ children: [{ type: "id", value: "instance-image" }],
+ },
+ ],
+ [
+ "instance-image",
+ {
+ type: "instance",
+ id: "instance-image",
+ component: "Image",
+ children: [],
+ },
+ ],
+ ],
+ props: [
+ ...build.props,
+ [
+ "prop-image-src",
+ {
+ id: "prop-image-src",
+ instanceId: "instance-image",
+ name: "src",
+ type: "asset",
+ value: "asset-hero",
+ },
+ ],
+ ],
+ }),
+ });
+ const transport = createTransport(remote);
+ const session = createSession({ transport });
+
+ const result = await session.mutate(
+ "pages.duplicate",
+ {
+ projectId: "project-1",
+ pageId: "page-home",
+ name: "Home copy",
+ path: "/home-copy",
+ },
+ { dryRun: true }
+ );
+
+ expect(result.state.committed).toBe(false);
+ expect(result.diagnostics).toEqual([
+ expect.objectContaining({ code: "DRY_RUN" }),
+ ]);
+ expect(transport.loadedNamespaces[0]).toEqual(
+ expect.arrayContaining(["pages", "assets", "instances", "props"])
+ );
+ expect(result.transaction).toBeDefined();
+ const plannedState = applyBuilderPatchTransactions(remote.state, [
+ result.transaction!,
+ ]).state;
+ const duplicatedPage = Array.from(
+ plannedState.pages?.pages.values() ?? []
+ ).find((page) => page.name === "Home copy");
+ expect(duplicatedPage).toBeDefined();
+ const duplicateRoot = plannedState.instances?.get(
+ duplicatedPage!.rootInstanceId
+ );
+ const duplicateImageId = duplicateRoot?.children.find(
+ (child) => child.type === "id"
+ )?.value;
+ expect(duplicateImageId).toBeDefined();
+ const duplicateAssetProp = Array.from(
+ plannedState.props?.values() ?? []
+ ).find(
+ (prop) => prop.instanceId === duplicateImageId && prop.name === "src"
+ );
+ expect(duplicateAssetProp).toMatchObject({
+ type: "asset",
+ value: "asset-hero",
+ });
+ expect(plannedState.assets?.has("asset-hero")).toBe(true);
+ });
+
test("retries namespace refresh once when local snapshot changes on disk", async () => {
const remote = createSnapshot();
let current: ProjectSessionPersistedSnapshot | undefined;
@@ -476,7 +582,9 @@ describe("project session", () => {
expect.objectContaining({ code: "CONFLICT" }),
expect.objectContaining({ code: "CONFLICT_REFRESHED" }),
]);
- expect(transport.loadedNamespaces).toEqual([["instances", "props"]]);
+ expect(transport.loadedNamespaces).toEqual([
+ ["instances", "props", "dataSources"],
+ ]);
});
test("retries retry-safe mutations once after conflict refresh", async () => {
diff --git a/packages/project-build/src/runtime/assets.test.ts b/packages/project-build/src/runtime/assets.test.ts
index 9444af9e4d..d759c67305 100644
--- a/packages/project-build/src/runtime/assets.test.ts
+++ b/packages/project-build/src/runtime/assets.test.ts
@@ -16,6 +16,7 @@ import type {
import type { BuilderState } from "../state/builder-state";
import {
addAsset,
+ assetAddInput,
calculateUsagesByAssetId,
createAssetDeletePayload,
createAssetReplacementPayload,
@@ -226,8 +227,9 @@ describe("asset upload helpers", () => {
describe("asset runtime operations", () => {
test("adds uploaded assets", () => {
const asset = imageAsset("new-asset", "new.png");
+ const { projectId, ...assetInput } = asset;
- expect(addAsset(state, { asset })).toEqual({
+ expect(addAsset(state, { asset: assetInput }, { projectId })).toEqual({
kind: "mutation",
noop: false,
result: { assetId: "new-asset" },
@@ -242,7 +244,8 @@ describe("asset runtime operations", () => {
});
test("rejects adding duplicate assets", () => {
- expect(() => addAsset(state, { asset: imageAsset("asset") })).toThrow(
+ const { projectId, ...asset } = imageAsset("asset");
+ expect(() => addAsset(state, { asset }, { projectId })).toThrow(
"Asset already exists"
);
});
@@ -897,6 +900,51 @@ const createAsset = (id: string): Asset =>
description: null,
}) as Asset;
+describe("addAsset", () => {
+ const assetInput = {
+ id: "asset-1",
+ name: "asset-1.png",
+ type: "image" as const,
+ size: 1,
+ format: "png",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ description: null,
+ meta: { width: 100, height: 100 },
+ };
+
+ test("uses the configured project instead of caller-owned identity", () => {
+ const input = assetAddInput.parse({
+ asset: { ...assetInput, projectId: "another-project" },
+ });
+ const result = addAsset({ assets: new Map() }, input, {
+ projectId: "configured-project",
+ });
+
+ expect(result.payload).toEqual([
+ {
+ namespace: "assets",
+ patches: [
+ {
+ op: "add",
+ path: ["asset-1"],
+ value: { ...assetInput, projectId: "configured-project" },
+ },
+ ],
+ },
+ ]);
+ });
+
+ test("requires configured project ownership", () => {
+ expect(() =>
+ addAsset(
+ { assets: new Map() },
+ { asset: assetInput },
+ { projectId: undefined }
+ )
+ ).toThrow("A configured project is required to add an asset");
+ });
+});
+
test("creates asset delete payload", () => {
expect(createAssetDeletePayload([createAsset("asset-1")])).toEqual([
{
diff --git a/packages/project-build/src/runtime/assets.ts b/packages/project-build/src/runtime/assets.ts
index 53edbd8f75..bea57b3b19 100644
--- a/packages/project-build/src/runtime/assets.ts
+++ b/packages/project-build/src/runtime/assets.ts
@@ -15,8 +15,10 @@ import {
type Resource,
type StyleDecl,
type Styles,
- asset as assetSchema,
assetType,
+ fileAsset,
+ fontAsset,
+ imageAsset,
} from "@webstudio-is/sdk";
import type { BuilderPatchChange } from "../contracts/patch";
import type { BuilderState } from "../state/builder-state";
@@ -119,9 +121,13 @@ export const imageDescriptionsSetInput = z
});
});
-export const assetAddInput = z.object({
- asset: assetSchema,
-});
+const addableAsset = z.union([
+ fontAsset.omit({ projectId: true }),
+ imageAsset.omit({ projectId: true }),
+ fileAsset.omit({ projectId: true }),
+]);
+
+export const assetAddInput = z.object({ asset: addableAsset });
export const parseAssetType = (value: string | null) => {
const result = assetType.safeParse(value);
@@ -543,20 +549,28 @@ export const getAssetDisplayFilename = (asset: Asset) =>
export const addAsset = (
state: Pick<BuilderState, "assets">,
- input: z.infer<typeof assetAddInput>
+ input: z.infer<typeof assetAddInput>,
+ context: { projectId?: string }
) => {
const assets = getRequiredAssets(state);
+ if (context.projectId === undefined) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "A configured project is required to add an asset"
+ );
+ }
if (assets.has(input.asset.id)) {
return throwBuilderRuntimeError("CONFLICT", "Asset already exists");
}
+ const asset: Asset = { ...input.asset, projectId: context.projectId };
return createRuntimeMutation({
payload: [
{
namespace: "assets",
- patches: [{ op: "add", path: [input.asset.id], value: input.asset }],
+ patches: [{ op: "add", path: [asset.id], value: asset }],
},
],
- result: { assetId: input.asset.id },
+ result: { assetId: asset.id },
invalidatesNamespaces: ["assets"],
});
};
diff --git a/packages/project-build/src/runtime/audit.test.ts b/packages/project-build/src/runtime/audit.test.ts
index a4d5b71cce..f78756d641 100644
--- a/packages/project-build/src/runtime/audit.test.ts
+++ b/packages/project-build/src/runtime/audit.test.ts
@@ -115,7 +115,7 @@ describe("project audit and analysis", () => {
expect(result.summary.selectedTotal).toBe(result.summary.total);
expect(result.summary.bySeverity.info).toBe(result.summary.total);
expect(result.findings).toHaveLength(1);
- expect(result.contractVersion).toBe(1);
+ expect(result.contractVersion).toBe(2);
expect(result.projectVersion).toBe(7);
expect(result.nextCursor).not.toBeNull();
expect(result.findings[0]).toMatchObject({
@@ -163,6 +163,37 @@ describe("project audit and analysis", () => {
).toThrow(/cursor does not match/i);
});
+ test("returns one finding for a CSS variable declared at multiple breakpoints", () => {
+ const styles = new Map<string, StyleDecl>(state.styles);
+ styles.set("local:base::--unused", {
+ styleSourceId: "local",
+ breakpointId: "base",
+ state: undefined,
+ property: "--unused",
+ value: { type: "keyword", value: "red" },
+ });
+ styles.set("local:desktop::--unused", {
+ styleSourceId: "local",
+ breakpointId: "desktop",
+ state: undefined,
+ property: "--unused",
+ value: { type: "keyword", value: "blue" },
+ });
+
+ const result = audit(
+ { ...state, styles },
+ { scopes: ["styles"], verbose: true, limit: 200 },
+ { projectVersion: 1 }
+ );
+ const findings = result.findings.filter(
+ (finding) =>
+ finding.ruleId === "unused-css-variable" &&
+ finding.location.cssVariableName === "--unused"
+ );
+
+ expect(findings).toHaveLength(1);
+ });
+
test("runs all audit scopes deterministically without mutating state", () => {
const before = structuredClone(state);
@@ -202,7 +233,7 @@ describe("project audit and analysis", () => {
);
expect(compact).toMatchObject({
- contractVersion: 1,
+ contractVersion: 2,
verbose: false,
skippedCheckCount: expect.any(Number),
manualCheckCount: 0,
@@ -217,7 +248,7 @@ describe("project audit and analysis", () => {
expect(compact.findings[0]).not.toHaveProperty("evidence");
expect(verbose).toMatchObject({
- contractVersion: 1,
+ contractVersion: 2,
verbose: true,
skippedCheckCount: compact.skippedCheckCount,
manualCheckCount: compact.manualCheckCount,
@@ -240,6 +271,71 @@ describe("project audit and analysis", () => {
});
});
+ test("includes verbose audit appendices only on the first findings page", () => {
+ const first = audit(
+ state,
+ { limit: 1, verbose: true },
+ { projectVersion: 1 }
+ );
+ expect(first.nextCursor).not.toBeNull();
+ expect(first.manualChecks.length).toBeGreaterThan(0);
+
+ const second = audit(
+ state,
+ { cursor: first.nextCursor ?? undefined, limit: 1, verbose: true },
+ { projectVersion: 1 }
+ );
+
+ expect(second.skippedCheckCount).toBe(first.skippedCheckCount);
+ expect(second.manualCheckCount).toBe(first.manualCheckCount);
+ expect(second.skippedChecks).toEqual([]);
+ expect(second.manualChecks).toEqual([]);
+ });
+
+ test("uses one homepage identity across page aliases and pagination", () => {
+ const inputs = [
+ { pagePath: "" },
+ { pagePath: "/" },
+ { pageId: "home" },
+ ] as const;
+ const firstPages = inputs.map((selector) =>
+ audit(
+ state,
+ { ...selector, scopes: ["assets", "styles"], limit: 1 },
+ { projectVersion: 1 }
+ )
+ );
+
+ for (const result of firstPages) {
+ expect(result.pageFilter).toEqual({
+ pageId: "home",
+ pagePath: "/",
+ projectWideScopes: ["assets", "styles"],
+ });
+ expect(result.nextCursor).not.toBeNull();
+ expect(
+ result.findings.flatMap(({ location }) => [
+ location.pagePath,
+ ...(location.pagePaths ?? []),
+ ])
+ ).not.toContain("");
+ }
+ expect(firstPages[1]).toEqual(firstPages[0]);
+ expect(firstPages[2]).toEqual(firstPages[0]);
+
+ const continued = audit(
+ state,
+ {
+ scopes: ["assets", "styles"],
+ pagePath: firstPages[0].pageFilter?.pagePath,
+ limit: 1,
+ cursor: firstPages[0].nextCursor ?? undefined,
+ },
+ { projectVersion: 1 }
+ );
+ expect(continued.findings[0]?.id).not.toBe(firstPages[0].findings[0]?.id);
+ });
+
test("validates mutually exclusive audit page selectors", () => {
expectRuntimeValidationError("project.audit", {
pageId: "home",
@@ -440,7 +536,7 @@ describe("project audit and analysis", () => {
expect(result.pageFilter).toEqual({
pageId: "home",
- pagePath: "",
+ pagePath: "/",
projectWideScopes: ["assets", "styles"],
});
expect(result.findings).toEqual(
@@ -1944,7 +2040,7 @@ describe("project audit and analysis", () => {
severity: "error",
location: expect.objectContaining({
pageId: "home",
- pagePath: "",
+ pagePath: "/",
}),
}),
])
diff --git a/packages/project-build/src/runtime/audit.ts b/packages/project-build/src/runtime/audit.ts
index 99d073c85b..c26aa6aacd 100644
--- a/packages/project-build/src/runtime/audit.ts
+++ b/packages/project-build/src/runtime/audit.ts
@@ -26,7 +26,26 @@ export const auditScope = z.enum([
]);
export const auditSeverity = z.enum(["error", "warning", "info"]);
-export const auditContractVersion = 1 as const;
+export const auditContractVersion = 2 as const;
+export const renderedAuditManifestVersion = 1 as const;
+const getAuditPagePath = (...args: Parameters<typeof getSerializedPagePath>) =>
+ getSerializedPagePath(...args) || "/";
+
+const canonicalizeAuditMatchPagePaths = (
+ match: Record<string, unknown>
+): Record<string, unknown> => ({
+ ...match,
+ ...(typeof match.pagePath === "string"
+ ? { pagePath: match.pagePath || "/" }
+ : {}),
+ ...(Array.isArray(match.pagePaths)
+ ? {
+ pagePaths: match.pagePaths.map((pagePath) =>
+ typeof pagePath === "string" ? pagePath || "/" : pagePath
+ ),
+ }
+ : {}),
+});
export const auditRuleId = z.enum([
"missing-alt",
@@ -187,6 +206,15 @@ export const manualAuditCheck = z.object({
workflow: z.string(),
});
+export const renderedAuditIssueKind = z.enum([
+ "horizontal-overflow",
+ "broken-image",
+ "eager-below-fold-image",
+ "oversized-image",
+ "render-blocking-resource",
+ "legacy-font-format",
+]);
+
export const renderedAuditCheck = z.object({
pageId: z.string(),
pagePath: z.string(),
@@ -196,6 +224,7 @@ export const renderedAuditCheck = z.object({
}),
screenshotPath: z.string(),
layout: z.object({
+ documentType: z.string().optional(),
viewportWidth: z.number().int().positive(),
viewportHeight: z.number().int().positive(),
contentWidth: z.number().int().positive(),
@@ -204,10 +233,13 @@ export const renderedAuditCheck = z.object({
images: z.array(
z.object({
instanceId: z.string().optional(),
+ sourcePathname: z.string().optional(),
loading: z.string(),
complete: z.boolean(),
naturalWidth: z.number().nonnegative(),
naturalHeight: z.number().nonnegative(),
+ selectedSourceWidth: z.number().nonnegative().optional(),
+ selectedSourceHeight: z.number().nonnegative().optional(),
renderedWidth: z.number().nonnegative(),
renderedHeight: z.number().nonnegative(),
top: z.number(),
@@ -225,16 +257,7 @@ export const renderedAuditCheck = z.object({
})
),
}),
- issues: z.array(
- z.enum([
- "horizontal-overflow",
- "broken-image",
- "eager-below-fold-image",
- "oversized-image",
- "render-blocking-resource",
- "legacy-font-format",
- ])
- ),
+ issues: z.array(renderedAuditIssueKind),
imageIssues: z.array(
z.object({
kind: z.enum([
@@ -243,9 +266,12 @@ export const renderedAuditCheck = z.object({
"oversized-image",
]),
instanceId: z.string().optional(),
+ sourcePathname: z.string().optional(),
loading: z.string(),
naturalWidth: z.number().nonnegative(),
naturalHeight: z.number().nonnegative(),
+ selectedSourceWidth: z.number().nonnegative().optional(),
+ selectedSourceHeight: z.number().nonnegative().optional(),
renderedWidth: z.number().nonnegative(),
renderedHeight: z.number().nonnegative(),
top: z.number(),
@@ -266,6 +292,31 @@ export const renderedAuditCheck = z.object({
});
export const renderedAuditFailure = z.object({
+ code: z.enum([
+ "RENDERED_AUDIT_PREPARATION_FAILED",
+ "RENDERED_AUDIT_NO_STATIC_PAGES",
+ "RENDERED_AUDIT_CAPTURE_LIMIT_EXCEEDED",
+ "RENDERED_AUDIT_CONFIRMATION_REQUIRED",
+ "RENDERED_AUDIT_CONFIRMATION_INVALID",
+ "RENDERED_AUDIT_PREVIEW_START_FAILED",
+ "RENDERED_AUDIT_LAYOUT_METRICS_MISSING",
+ "RENDERED_AUDIT_HTTP_ERROR",
+ "RENDERED_AUDIT_NAVIGATION_EVIDENCE_MISSING",
+ "RENDERED_AUDIT_ORIGIN_MISMATCH",
+ "RENDERED_AUDIT_ROUTE_MISMATCH",
+ "RENDERED_AUDIT_DOCUMENT_NOT_GENERATED_SITE",
+ "RENDERED_AUDIT_LAYOUT_UNSTABLE",
+ "RENDERED_AUDIT_SCREENSHOT_FAILED",
+ "RENDERED_AUDIT_CAPTURE_TIMEOUT",
+ "RENDERED_AUDIT_PAGE_TIMEOUT",
+ "RENDERED_AUDIT_OVERALL_TIMEOUT",
+ "RENDERED_AUDIT_CANCELLED",
+ "RENDERED_AUDIT_PREVIEW_STOP_FAILED",
+ "RENDERED_AUDIT_ARTIFACT_WRITE_FAILED",
+ ]),
+ phase: z.enum(["planning", "preview-start", "capture", "preview-stop"]),
+ retryable: z.boolean(),
+ remediation: z.string(),
pageId: z.string().optional(),
pagePath: z.string().optional(),
viewport: z
@@ -274,9 +325,83 @@ export const renderedAuditFailure = z.object({
height: z.number().int().positive(),
})
.optional(),
+ screenshotPath: z.string().optional(),
message: z.string(),
});
+export const renderedAuditCaptureStatus = z.object({
+ pageId: z.string(),
+ pagePath: z.string(),
+ viewport: z.object({
+ width: z.number().int().positive(),
+ height: z.number().int().positive(),
+ }),
+ status: z.enum(["passed", "issues", "skipped", "failed"]),
+ screenshotPath: z.string().optional(),
+ failureCode: renderedAuditFailure.shape.code.optional(),
+});
+
+export const renderedAuditCaptureSummary = z.object({
+ planned: z.number().int().nonnegative(),
+ passed: z.number().int().nonnegative(),
+ issues: z.number().int().nonnegative(),
+ skipped: z.number().int().nonnegative(),
+ failed: z.number().int().nonnegative(),
+});
+
+export const renderedAuditArtifactManifestSummary = z.object({
+ version: z.literal(renderedAuditManifestVersion),
+ path: z.string(),
+ screenshotCount: z.number().int().nonnegative(),
+});
+
+export const renderedAuditFailureSummary = renderedAuditFailure
+ .pick({
+ code: true,
+ phase: true,
+ remediation: true,
+ })
+ .extend({ count: z.number().int().positive() });
+
+export const renderedAuditIssueSummary = z.object({
+ kind: renderedAuditIssueKind,
+ count: z.number().int().positive(),
+ captureCount: z.number().int().positive(),
+ pagePaths: z.array(z.string()).max(5),
+});
+
+export const renderedAuditPlan = z.object({
+ version: z.literal(1),
+ pages: z.array(z.object({ pageId: z.string(), pagePath: z.string() })),
+ excludedPages: z.array(
+ z.object({
+ pageId: z.string(),
+ pagePath: z.string(),
+ reason: z.literal("dynamic-route-needs-example"),
+ })
+ ),
+ viewports: z.array(
+ z.object({
+ width: z.number().int().positive(),
+ height: z.number().int().positive(),
+ purposes: z.array(z.string()).min(1),
+ })
+ ),
+ checks: z.array(
+ z.enum([
+ "horizontal-overflow",
+ "broken-image",
+ "eager-below-fold-image",
+ "oversized-image",
+ "render-blocking-resource",
+ "legacy-font-format",
+ ])
+ ),
+ captureCount: z.number().int().nonnegative(),
+ confirmationToken: z.string().optional(),
+ confirmationExpiresAt: z.string().datetime().optional(),
+});
+
const auditResultBase = z.object({
contractVersion: z.literal(auditContractVersion),
projectVersion: z.number().int().nonnegative(),
@@ -294,12 +419,18 @@ const auditResultBase = z.object({
renderedCheckCount: z.number().int().nonnegative(),
renderedIssueCount: z.number().int().nonnegative(),
renderedFailureCount: z.number().int().nonnegative(),
+ renderedPlan: renderedAuditPlan.nullable(),
+ renderedCaptureSummary: renderedAuditCaptureSummary,
+ renderedCaptureStatuses: z.array(renderedAuditCaptureStatus),
+ renderedArtifactManifest: renderedAuditArtifactManifestSummary.nullable(),
nextCursor: z.string().nullable(),
});
export const compactAuditResult = auditResultBase.extend({
verbose: z.literal(false),
findings: z.array(compactAuditFinding),
+ renderedIssueSummaries: z.array(renderedAuditIssueSummary),
+ renderedFailureSummaries: z.array(renderedAuditFailureSummary),
});
export const verboseAuditResult = auditResultBase.extend({
@@ -908,7 +1039,7 @@ const getSkippedChecks = (
message: `${field} is expression-backed and cannot be audited statically.`,
location: {
pageId: page.id,
- pagePath: getSerializedPagePath(pages, page),
+ pagePath: getAuditPagePath(pages, page),
},
});
}
@@ -958,20 +1089,34 @@ export function audit(
}
const scopes = input.scopes ?? auditScope.options;
const selectedSeverities = input.severities ?? auditSeverity.options;
+ let selectedPage: ReturnType<typeof findSerializedPageByInput> | undefined;
+ let normalizedInput = input;
+ if (input.pageId !== undefined || input.pagePath !== undefined) {
+ const pages = getSerializedPages(state);
+ selectedPage = findSerializedPageByInput(pages, input);
+ if (selectedPage === undefined) {
+ return throwBuilderRuntimeError("NOT_FOUND", "Page not found");
+ }
+ normalizedInput = {
+ ...input,
+ pageId: selectedPage.id,
+ pagePath: undefined,
+ };
+ }
const cursorSignature = JSON.stringify({
scopes: [...scopes].sort(),
severities: [...selectedSeverities].sort(),
- pageId: input.pageId,
- pagePath: input.pagePath,
+ pageId: selectedPage?.id,
verbose: input.verbose === true,
});
const raw = analyzeProject(state, {
scopes,
- pageId: input.pageId,
- pagePath: input.pagePath,
+ pageId: normalizedInput.pageId,
+ pagePath: normalizedInput.pagePath,
limit: Number.MAX_SAFE_INTEGER,
});
- const allFindings = raw.matches
+ const normalizedFindings = raw.matches
+ .map(canonicalizeAuditMatchPagePaths)
.map(normalizeAuditFinding)
.sort(
(left, right) =>
@@ -983,6 +1128,11 @@ export function audit(
) ||
left.id.localeCompare(right.id)
);
+ const allFindings = Array.from(
+ new Map(
+ normalizedFindings.map((finding) => [finding.id, finding] as const)
+ ).values()
+ );
const severities = new Set(selectedSeverities);
const findings = allFindings.filter((finding) =>
severities.has(finding.severity)
@@ -1024,22 +1174,18 @@ export function audit(
])
) as AuditSummary["byScope"];
let pageFilter: AuditResult["pageFilter"] = null;
- if (input.pageId !== undefined || input.pagePath !== undefined) {
+ if (selectedPage !== undefined) {
const pages = getSerializedPages(state);
- const page = findSerializedPageByInput(pages, input);
- if (page === undefined) {
- return throwBuilderRuntimeError("NOT_FOUND", "Page not found");
- }
pageFilter = {
- pageId: page.id,
- pagePath: getSerializedPagePath(pages, page),
+ pageId: selectedPage.id,
+ pagePath: getAuditPagePath(pages, selectedPage),
projectWideScopes: scopes.filter(
(scope) =>
scope === "assets" || scope === "styles" || scope === "performance"
),
};
}
- const skippedChecks = getSkippedChecks(state, input, scopes);
+ const skippedChecks = getSkippedChecks(state, normalizedInput, scopes);
const manualChecks = [
...(scopes.some((scope) =>
["accessibility", "styles", "performance"].includes(scope)
@@ -1050,7 +1196,7 @@ export function audit(
message:
"Check responsive layout, overflow, clipping, and text wrapping at project breakpoints.",
workflow:
- "Preview the project and capture screenshots at desktop and every breakpoint edge. Treat screenshot.layout.horizontalOverflow as deterministic overflow evidence, then inspect clipping and text wrapping with vision.",
+ "Preview the project and capture a familiar device viewport inside every breakpoint range. Treat screenshot.layout.horizontalOverflow as deterministic overflow evidence, then inspect clipping and text wrapping with vision.",
},
]
: []),
@@ -1089,7 +1235,19 @@ export function audit(
manualCheckCount: manualChecks.length,
renderedCheckCount: 0,
renderedIssueCount: 0,
+ renderedIssueSummaries: [],
renderedFailureCount: 0,
+ renderedFailureSummaries: [],
+ renderedPlan: null,
+ renderedCaptureSummary: {
+ planned: 0,
+ passed: 0,
+ issues: 0,
+ skipped: 0,
+ failed: 0,
+ },
+ renderedCaptureStatuses: [],
+ renderedArtifactManifest: null,
nextCursor:
offset + limit < findings.length
? encodeCursor(context.projectVersion, offset + limit, cursorSignature)
@@ -1100,8 +1258,8 @@ export function audit(
...resultBase,
verbose: true,
findings: paginatedFindings,
- skippedChecks,
- manualChecks,
+ skippedChecks: offset === 0 ? skippedChecks : [],
+ manualChecks: offset === 0 ? manualChecks : [],
renderedChecks: [],
renderedFailures: [],
});
diff --git a/packages/project-build/src/runtime/components.test.ts b/packages/project-build/src/runtime/components.test.ts
index a62514e5de..997552820f 100644
--- a/packages/project-build/src/runtime/components.test.ts
+++ b/packages/project-build/src/runtime/components.test.ts
@@ -1,6 +1,8 @@
import { expect, test } from "vitest";
import {
+ collectionComponent,
elementComponent,
+ encodeDataVariableId,
getStyleDeclKey,
type Instance,
type Page,
@@ -187,6 +189,37 @@ test("inserts ws.element component with tag", async () => {
);
});
+test("keeps Collection item expressions linked to each inserted parameter", () => {
+ for (let insertion = 0; insertion < 2; insertion += 1) {
+ const parent = createParent();
+ const mutation = insertComponent(
+ createState(parent),
+ {
+ parentInstanceId: parent.id,
+ component: collectionComponent,
+ },
+ { createId: createIdFactory() }
+ );
+ const props = getAddedValues<{
+ name: string;
+ type: string;
+ value: string;
+ }>(mutation, "props");
+ const itemParameterId = props.find(
+ (prop) => prop.name === "item" && prop.type === "parameter"
+ )?.value;
+ const expressions = getAddedValues<Instance>(mutation, "instances").flatMap(
+ (instance) =>
+ instance.children.flatMap((child) =>
+ child.type === "expression" ? [child.value] : []
+ )
+ );
+
+ expect(itemParameterId).toBeDefined();
+ expect(expressions).toContain(encodeDataVariableId(itemParameterId ?? ""));
+ }
+});
+
test("inserts fragment into page template", async () => {
const parent = createParent();
const root: Instance = {
@@ -235,6 +268,45 @@ test("rejects tag when inserting non-element component", async () => {
).toThrow('"tag" can only be used with component "ws:element"');
});
+test("rejects unknown Webstudio core components", () => {
+ const parent = createParent();
+
+ expect(() =>
+ insertComponent(
+ createState(parent),
+ {
+ parentInstanceId: parent.id,
+ component: "ws:div",
+ },
+ {
+ createId: createIdFactory(),
+ }
+ )
+ ).toThrow(
+ 'Component "ws:div" does not exist. The "ws:" namespace contains Webstudio core components, not HTML tag shorthands.'
+ );
+});
+
+test("rejects unknown Webstudio core components in JSX fragments", async () => {
+ const parent = createParent();
+ const fragment = await parseWebstudioJsxFragment(`<ws.div />`);
+
+ expect(() =>
+ insertFragment(
+ createState(parent),
+ {
+ parentInstanceId: parent.id,
+ fragment,
+ },
+ {
+ createId: createIdFactory(),
+ }
+ )
+ ).toThrow(
+ 'Component "ws:div" does not exist. The "ws:" namespace contains Webstudio core components, not HTML tag shorthands.'
+ );
+});
+
test("inserts registered component template", async () => {
const parent = createParent();
const mutation = await insertComponent(
diff --git a/packages/project-build/src/runtime/components.ts b/packages/project-build/src/runtime/components.ts
index d6d8d9fe6b..1a0fe9ce94 100644
--- a/packages/project-build/src/runtime/components.ts
+++ b/packages/project-build/src/runtime/components.ts
@@ -52,7 +52,9 @@ const conflictResolutionInput = z.enum(["ours", "theirs", "merge"]);
export const insertComponentInput = z.object({
parentInstanceId: z.string(),
- component: instanceComponent,
+ component: instanceComponent.describe(
+ 'Exact component id returned by components.search, components.get, or templates.get. Do not derive HTML shorthands such as "ws:div" or "ws:form". For a native HTML element, use "ws:element" and set "tag".'
+ ),
tag: z
.string()
.min(1)
@@ -150,6 +152,22 @@ const getStandaloneInsertError = (component: Instance["component"]) => {
return `Component "${component}" cannot be inserted standalone because its contentModel.category is "none". ${suggestion} Required provider/parent components must be created by the template.`;
};
+const getUnknownCoreComponentError = ({
+ component,
+ templates,
+}: {
+ component: Instance["component"];
+ templates: ComponentTemplateRegistry;
+}) => {
+ if (
+ component.startsWith("ws:") &&
+ componentMetas.has(component) === false &&
+ templates.has(component) === false
+ ) {
+ return `Component "${component}" does not exist. The "ws:" namespace contains Webstudio core components, not HTML tag shorthands. To create a native HTML element, use component "ws:element" with its "tag" property, for example <ws.element ws:tag="div">...</ws.element>.`;
+ }
+};
+
type ComponentInsertState = Pick<
BuilderState,
(typeof componentInsertReadNamespaces)[number]
@@ -459,6 +477,13 @@ const validateFragmentComponent = ({
}) => {
const { component } = instance;
const meta = componentMetas.get(component);
+ const unknownCoreComponentError = getUnknownCoreComponentError({
+ component,
+ templates,
+ });
+ if (unknownCoreComponentError !== undefined) {
+ return throwBuilderRuntimeError("BAD_REQUEST", unknownCoreComponentError);
+ }
if (
component === "ws:element" &&
(typeof instance.tag !== "string" || instance.tag.length === 0)
@@ -799,6 +824,13 @@ export const insertComponent = (
const templates = getComponentTemplates();
const template = templates.get(input.component);
const meta = componentMetas.get(input.component);
+ const unknownCoreComponentError = getUnknownCoreComponentError({
+ component: input.component,
+ templates,
+ });
+ if (unknownCoreComponentError !== undefined) {
+ return throwBuilderRuntimeError("BAD_REQUEST", unknownCoreComponentError);
+ }
const insertCategory = template?.category ?? meta?.category;
const page = getInsertionPage(mutationState, parent);
if (
diff --git a/packages/project-build/src/runtime/data.test.tsx b/packages/project-build/src/runtime/data.test.tsx
index 37731cdd0a..99f588ed39 100644
--- a/packages/project-build/src/runtime/data.test.tsx
+++ b/packages/project-build/src/runtime/data.test.tsx
@@ -138,6 +138,28 @@ test("rejects client-supplied ids on data create inputs", () => {
).toBe(false);
});
+test("requires a scope for explicit render-time resource exposure", () => {
+ const result = resourceCreateInput.safeParse({
+ resource: {
+ name: "Submit",
+ method: "post",
+ url: '"https://api.example.com/submit"',
+ headers: [],
+ },
+ exposeAsDataSource: true,
+ });
+
+ expect(result.success).toBe(false);
+ if (result.success === false) {
+ expect(result.error.issues).toContainEqual(
+ expect.objectContaining({
+ path: ["scopeInstanceId"],
+ message: "scopeInstanceId is required when exposeAsDataSource is true.",
+ })
+ );
+ }
+});
+
test("encode data variable name when necessary", () => {
expect(encodeDataVariableName("formState")).toEqual("formState");
expect(encodeDataVariableName("Collection Item")).toEqual(
@@ -2346,6 +2368,133 @@ describe("resource patch helpers", () => {
},
],
});
+ expect(result.payload).not.toContainEqual(
+ expect.objectContaining({ namespace: "dataSources" })
+ );
+ });
+
+ test("exposes scoped GET resources as render data by default", () => {
+ const state = createResourceState();
+ state.instances.set("body", {
+ type: "instance",
+ id: "body",
+ component: "Body",
+ children: [],
+ });
+ const ids = ["resource-id", "data-source-id"];
+
+ const result = createResource(
+ state,
+ {
+ resource: resourceFieldsInput.parse({
+ name: "Users",
+ method: "get",
+ url: "https://example.com/users",
+ headers: [],
+ }),
+ scopeInstanceId: "body",
+ },
+ { createId: () => ids.shift() ?? "unexpected-id" }
+ );
+
+ expect(result.result).toMatchObject({
+ resourceId: "resource-id",
+ dataSourceId: "data-source-id",
+ warnings: [],
+ });
+ expect(result.payload).toContainEqual(
+ expect.objectContaining({ namespace: "dataSources" })
+ );
+ });
+
+ test("warns when a write resource is explicitly exposed as render data", () => {
+ const state = createResourceState();
+ state.instances.set("body", {
+ type: "instance",
+ id: "body",
+ component: "Body",
+ children: [],
+ });
+ const ids = ["resource-id", "data-source-id"];
+
+ const result = createResource(
+ state,
+ {
+ resource: resourceFieldsInput.parse({
+ name: "Submit",
+ method: "post",
+ url: "https://example.com/submit",
+ headers: [],
+ }),
+ scopeInstanceId: "body",
+ exposeAsDataSource: true,
+ },
+ { createId: () => ids.shift() ?? "unexpected-id" }
+ );
+
+ expect(result.result).toMatchObject({
+ dataSourceId: "data-source-id",
+ warnings: [
+ "The POST resource is explicitly exposed as render-time data and may execute while rendering the page.",
+ ],
+ });
+ expect(result.payload).toContainEqual(
+ expect.objectContaining({ namespace: "dataSources" })
+ );
+ });
+
+ test.each(["post", "put", "delete"] as const)(
+ "does not expose scoped %s resources as render data by default",
+ (method) => {
+ const state = createResourceState();
+ state.instances.set("body", {
+ type: "instance",
+ id: "body",
+ component: "Body",
+ children: [],
+ });
+
+ const result = createResource(
+ state,
+ {
+ resource: resourceFieldsInput.parse({
+ name: "Write action",
+ method,
+ url: "https://example.com/action",
+ headers: [],
+ }),
+ scopeInstanceId: "body",
+ },
+ { createId: () => "resource-id" }
+ );
+
+ expect(result.result).toMatchObject({
+ resourceId: "resource-id",
+ dataSourceId: undefined,
+ warnings: [],
+ });
+ expect(result.payload).not.toContainEqual(
+ expect.objectContaining({ namespace: "dataSources" })
+ );
+ }
+ );
+
+ test("rejects render-time exposure at an unknown scope instance", () => {
+ expect(() =>
+ createResource(
+ createResourceState(),
+ {
+ resource: resourceFieldsInput.parse({
+ name: "Users",
+ method: "get",
+ url: "https://example.com/users",
+ headers: [],
+ }),
+ scopeInstanceId: "missing",
+ },
+ { createId: () => "resource-id" }
+ )
+ ).toThrow("Scope instance not found");
});
test("does not invalidate resources when text replacement finds no matches", () => {
@@ -2917,25 +3066,33 @@ describe("resource patch helpers", () => {
};
expect(() =>
- updateResource(state, {
- resourceId: "resource",
- values: { url: `"not-a-url"` },
- })
+ updateResource(
+ state,
+ {
+ resourceId: "resource",
+ values: { url: `"not-a-url"` },
+ },
+ { createId: () => "unused-id" }
+ )
).toThrow("url: URL is invalid");
expect(
- updateResource(state, {
- resourceId: "resource",
- values: resourceFieldsUpdateInput.parse({
- headers: [
- {
- name: "Content-Type",
- value: { type: "literal", value: "application/json" },
- },
- ],
- body: { type: "literal", value: "Plain text body" },
- }),
- }).payload
+ updateResource(
+ state,
+ {
+ resourceId: "resource",
+ values: resourceFieldsUpdateInput.parse({
+ headers: [
+ {
+ name: "Content-Type",
+ value: { type: "literal", value: "application/json" },
+ },
+ ],
+ body: { type: "literal", value: "Plain text body" },
+ }),
+ },
+ { createId: () => "unused-id" }
+ ).payload
).toEqual(
expect.arrayContaining([
expect.objectContaining({
@@ -2963,10 +3120,14 @@ describe("resource patch helpers", () => {
body: '"request body"',
});
- const result = updateResource(state, {
- resourceId: "resource",
- values: { name: "Renamed" },
- });
+ const result = updateResource(
+ state,
+ {
+ resourceId: "resource",
+ values: { name: "Renamed" },
+ },
+ { createId: () => "unused-id" }
+ );
const resourcePatch = result.payload
.find(({ namespace }) => namespace === "resources")
?.patches.find(({ path }) => path[0] === "resource");
@@ -2980,6 +3141,155 @@ describe("resource patch helpers", () => {
});
});
+ test("keeps an empty resource update as a no-op", () => {
+ const state = createResourceState();
+ state.resources.set("resource", resource);
+
+ const result = updateResource(
+ state,
+ { resourceId: "resource", values: {} },
+ { createId: () => "unused-id" }
+ );
+
+ expect(result).toMatchObject({
+ payload: [],
+ noop: true,
+ invalidatesNamespaces: [],
+ result: { resourceId: "resource" },
+ });
+ });
+
+ test("detaches render data when a resource becomes a write action", () => {
+ const state = createResourceState();
+ state.instances.set("body", {
+ type: "instance",
+ id: "body",
+ component: "Body",
+ children: [],
+ });
+ state.resources.set("resource", resource);
+ state.dataSources.set("data-source", {
+ id: "data-source",
+ scopeInstanceId: "body",
+ name: "Users",
+ type: "resource",
+ resourceId: "resource",
+ });
+
+ const result = updateResource(
+ state,
+ {
+ resourceId: "resource",
+ values: { method: "post" },
+ },
+ { createId: () => "unused-id" }
+ );
+
+ expect(result.result).toMatchObject({
+ resourceId: "resource",
+ dataSourceId: undefined,
+ warnings: [],
+ });
+ expect(result.payload).toContainEqual({
+ namespace: "dataSources",
+ patches: [{ op: "remove", path: ["data-source"] }],
+ });
+ });
+
+ test("preserves explicit write-resource exposure during unrelated updates", () => {
+ const state = createResourceState();
+ state.instances.set("body", {
+ type: "instance",
+ id: "body",
+ component: "Body",
+ children: [],
+ });
+ state.resources.set("resource", { ...resource, method: "post" });
+ state.dataSources.set("data-source", {
+ id: "data-source",
+ scopeInstanceId: "body",
+ name: "Users",
+ type: "resource",
+ resourceId: "resource",
+ });
+
+ const result = updateResource(
+ state,
+ {
+ resourceId: "resource",
+ values: { name: "Renamed" },
+ },
+ { createId: () => "unused-id" }
+ );
+
+ expect(result.result).toMatchObject({
+ resourceId: "resource",
+ dataSourceId: "data-source",
+ warnings: [],
+ });
+ expect(result.payload).not.toContainEqual({
+ namespace: "dataSources",
+ patches: [{ op: "remove", path: ["data-source"] }],
+ });
+ });
+
+ test("can explicitly attach and detach render data on update", () => {
+ const state = createResourceState();
+ state.instances.set("body", {
+ type: "instance",
+ id: "body",
+ component: "Body",
+ children: [],
+ });
+ state.resources.set("resource", { ...resource, method: "post" });
+
+ const attached = updateResource(
+ state,
+ {
+ resourceId: "resource",
+ values: {},
+ scopeInstanceId: "body",
+ exposeAsDataSource: true,
+ },
+ { createId: () => "data-source" }
+ );
+
+ expect(attached.result).toMatchObject({
+ dataSourceId: "data-source",
+ warnings: [
+ "The POST resource is explicitly exposed as render-time data and may execute while rendering the page.",
+ ],
+ });
+ expect(attached.payload).toContainEqual(
+ expect.objectContaining({ namespace: "dataSources" })
+ );
+
+ const attachedState = createResourceState();
+ attachedState.instances.set("body", state.instances.get("body")!);
+ attachedState.resources.set("resource", { ...resource, method: "post" });
+ attachedState.dataSources.set("data-source", {
+ id: "data-source",
+ scopeInstanceId: "body",
+ name: "Users",
+ type: "resource",
+ resourceId: "resource",
+ });
+ const detached = updateResource(
+ attachedState,
+ {
+ resourceId: "resource",
+ values: {},
+ exposeAsDataSource: false,
+ },
+ { createId: () => "unused-id" }
+ );
+
+ expect(detached.payload).toContainEqual({
+ namespace: "dataSources",
+ patches: [{ op: "remove", path: ["data-source"] }],
+ });
+ });
+
test("reports resource create id conflicts", () => {
expect(
createResourceCreatePayload({
diff --git a/packages/project-build/src/runtime/data.ts b/packages/project-build/src/runtime/data.ts
index 5234e28452..9fd3362802 100644
--- a/packages/project-build/src/runtime/data.ts
+++ b/packages/project-build/src/runtime/data.ts
@@ -608,6 +608,43 @@ export const findAvailableVariables = ({
return availableVariables;
};
+export const bindExpressionToInstanceScope = ({
+ expression,
+ instanceId,
+ instances,
+ dataSources,
+}: {
+ expression: string;
+ instanceId: Instance["id"];
+ instances: Instances;
+ dataSources: DataSources;
+}) => {
+ const maskedIdByName = findMaskedVariablesByInstanceId({
+ startingInstanceId: instanceId,
+ parentInstanceById: getParentInstanceById(instances),
+ instances,
+ dataSources,
+ });
+ const boundExpression = restoreExpressionVariables({
+ expression,
+ maskedIdByName,
+ });
+ const availableDataSourceIds = new Set(maskedIdByName.values());
+ for (const identifier of getExpressionIdentifiers(boundExpression)) {
+ const dataSourceId = decodeDataVariableId(identifier);
+ if (
+ dataSourceId !== undefined &&
+ availableDataSourceIds.has(dataSourceId) === false
+ ) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ `Expression references data source "${dataSourceId}", which is not available to instance "${instanceId}". Read the target instance and its current Collection subtree again, then use an in-scope variable name or parameter from that subtree.`
+ );
+ }
+ }
+ return boundExpression;
+};
+
const traverseExpressions = ({
startingInstanceId,
pages,
@@ -1503,7 +1540,7 @@ const resourceExpressionInput = z
z.object({ type: z.literal("literal"), value: z.string() }),
])
.describe(
- 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.'
+ 'One dynamic Webstudio JavaScript expression, or { type: "literal", value: string } for fixed text. Read webstudio://project/expressions for syntax, scope, resource-result shape, and supported methods.'
);
const resourceExpressionEntryInput = z.object({
@@ -1580,19 +1617,41 @@ const normalizeResourceFieldsInput = (
const normalizeResourceFieldsUpdateInput = normalizeResourceFields;
-export const resourceCreateInput = z.object({
- resourceId: runtimeGeneratedIdInput,
- resource: resourceFieldsInput,
- dataSourceId: runtimeGeneratedIdInput,
- scopeInstanceId: z.string().optional(),
- dataSourceName: z.string().optional(),
-});
+const exposeAsDataSourceInput = z
+ .boolean()
+ .optional()
+ .describe(
+ "Expose the resource as render-time data. Scoped GET resources default to true; write resources default to false."
+ );
+
+export const resourceCreateInput = z
+ .object({
+ resourceId: runtimeGeneratedIdInput,
+ resource: resourceFieldsInput,
+ dataSourceId: runtimeGeneratedIdInput,
+ scopeInstanceId: z.string().optional(),
+ dataSourceName: z.string().optional(),
+ exposeAsDataSource: exposeAsDataSourceInput,
+ })
+ .superRefine((input, context) => {
+ if (
+ input.exposeAsDataSource === true &&
+ input.scopeInstanceId === undefined
+ ) {
+ context.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["scopeInstanceId"],
+ message: "scopeInstanceId is required when exposeAsDataSource is true.",
+ });
+ }
+ });
export const resourceUpdateInput = z.object({
resourceId: z.string(),
values: resourceFieldsUpdateInput,
dataSourceName: z.string().optional(),
scopeInstanceId: z.string().optional(),
+ exposeAsDataSource: exposeAsDataSourceInput,
});
export const replaceResourceTextInput = z.object({
@@ -1916,6 +1975,7 @@ export const upsertResourceMutable = ({
dataSourceId,
scopeInstanceId,
dataSourceName,
+ exposeAsDataSource = scopeInstanceId !== undefined,
}: {
data: Pick<
WebstudioData,
@@ -1927,9 +1987,34 @@ export const upsertResourceMutable = ({
dataSourceId?: DataSource["id"];
scopeInstanceId?: Instance["id"];
dataSourceName?: DataSource["name"];
+ exposeAsDataSource?: boolean;
}) => {
data.resources.set(resource.id, resource);
- if (dataSourceId !== undefined && scopeInstanceId !== undefined) {
+ const previousDataSource = Array.from(data.dataSources.values()).find(
+ (dataSource) =>
+ dataSource.type === "resource" && dataSource.resourceId === resource.id
+ );
+ if (previousDataSource !== undefined && exposeAsDataSource === false) {
+ data.dataSources.delete(previousDataSource.id);
+ if (previousDataSource.scopeInstanceId !== undefined) {
+ rebindTreeVariablesMutable({
+ startingInstanceId: previousDataSource.scopeInstanceId,
+ ...data,
+ });
+ if (data.pages !== undefined) {
+ rebindTreeVariablesMutable({
+ startingInstanceId: previousDataSource.scopeInstanceId,
+ ...data,
+ pages: undefined,
+ });
+ }
+ }
+ }
+ if (
+ exposeAsDataSource &&
+ dataSourceId !== undefined &&
+ scopeInstanceId !== undefined
+ ) {
data.dataSources.set(
dataSourceId,
createResourceDataSource({
@@ -1959,6 +2044,7 @@ export const createResourceUpsertPatchPayload = ({
dataSourceId,
scopeInstanceId,
dataSourceName,
+ exposeAsDataSource,
}: {
build: Pick<
CompactBuild,
@@ -1976,6 +2062,7 @@ export const createResourceUpsertPatchPayload = ({
dataSourceId?: DataSource["id"];
scopeInstanceId?: Instance["id"];
dataSourceName?: DataSource["name"];
+ exposeAsDataSource?: boolean;
}) => {
const before = createWebstudioDataFromBuild({ build });
return produceWebstudioDataMutation(before, (draft) => {
@@ -1985,6 +2072,7 @@ export const createResourceUpsertPatchPayload = ({
dataSourceId,
scopeInstanceId,
dataSourceName,
+ exposeAsDataSource,
});
}).payload;
};
@@ -2261,8 +2349,18 @@ export const createResource = (
validateResourceFields(resourceInput);
const build = getRequiredBuildData(state);
const resourceId = context.createId();
- const dataSourceId =
- input.scopeInstanceId === undefined ? undefined : context.createId();
+ const exposeAsDataSource =
+ input.exposeAsDataSource ??
+ (resourceInput.method === "get" && input.scopeInstanceId !== undefined);
+ if (
+ exposeAsDataSource &&
+ build.instances.some(
+ (instance) => instance.id === input.scopeInstanceId
+ ) === false
+ ) {
+ return throwBuilderRuntimeError("NOT_FOUND", "Scope instance not found");
+ }
+ const dataSourceId = exposeAsDataSource ? context.createId() : undefined;
const resultPayload = createResourceCreatePayload({
resourceId,
resource: resourceInput,
@@ -2299,8 +2397,18 @@ export const createResource = (
dataSourceId,
scopeInstanceId: input.scopeInstanceId,
dataSourceName: input.dataSourceName,
+ exposeAsDataSource,
}),
- result: { resourceId, dataSourceId },
+ result: {
+ resourceId,
+ dataSourceId,
+ warnings:
+ exposeAsDataSource && resourceInput.method !== "get"
+ ? [
+ `The ${resourceInput.method.toUpperCase()} resource is explicitly exposed as render-time data and may execute while rendering the page.`,
+ ]
+ : [],
+ },
invalidatesNamespaces: [
"pages",
"instances",
@@ -2328,7 +2436,8 @@ export const updateResource = (
| "styleSourceSelections"
| "styles"
>,
- input: z.infer<typeof resourceUpdateInput>
+ input: z.infer<typeof resourceUpdateInput>,
+ context: BuilderRuntimeContext
) => {
const values = normalizeResourceFieldsUpdateInput(input.values);
validateResourceFields(values);
@@ -2337,14 +2446,12 @@ export const updateResource = (
if (resource === undefined) {
return throwBuilderRuntimeError("NOT_FOUND", "Resource not found");
}
- const directPayload = createResourceUpdatePayload({
- resource,
- values,
- dataSources: build.dataSources,
- dataSourceName: input.dataSourceName,
- scopeInstanceId: input.scopeInstanceId,
- });
- if (directPayload.length === 0) {
+ if (
+ Object.values(values).every((value) => value === undefined) &&
+ input.dataSourceName === undefined &&
+ input.scopeInstanceId === undefined &&
+ input.exposeAsDataSource === undefined
+ ) {
return createRuntimeMutation({
payload: [],
result: { resourceId: resource.id },
@@ -2359,15 +2466,48 @@ export const updateResource = (
(dataSource) =>
dataSource.type === "resource" && dataSource.resourceId === resource.id
);
+ const scopeInstanceId = input.scopeInstanceId ?? dataSource?.scopeInstanceId;
+ const exposeAsDataSource =
+ input.exposeAsDataSource ??
+ (values.method !== undefined && nextResource.method !== "get"
+ ? false
+ : dataSource !== undefined ||
+ (nextResource.method === "get" && scopeInstanceId !== undefined));
+ if (exposeAsDataSource && scopeInstanceId === undefined) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "scopeInstanceId is required when exposeAsDataSource is true."
+ );
+ }
+ if (
+ exposeAsDataSource &&
+ build.instances.some((instance) => instance.id === scopeInstanceId) ===
+ false
+ ) {
+ return throwBuilderRuntimeError("NOT_FOUND", "Scope instance not found");
+ }
+ const dataSourceId = exposeAsDataSource
+ ? (dataSource?.id ?? context.createId())
+ : dataSource?.id;
return createRuntimeMutation({
payload: createResourceUpsertPatchPayload({
build,
resource: nextResource,
- dataSourceId: dataSource?.id,
- scopeInstanceId: input.scopeInstanceId ?? dataSource?.scopeInstanceId,
+ dataSourceId,
+ scopeInstanceId,
dataSourceName: input.dataSourceName ?? dataSource?.name,
+ exposeAsDataSource,
}),
- result: { resourceId: resource.id },
+ result: {
+ resourceId: resource.id,
+ dataSourceId: exposeAsDataSource ? dataSourceId : undefined,
+ warnings:
+ input.exposeAsDataSource === true && nextResource.method !== "get"
+ ? [
+ `The ${nextResource.method.toUpperCase()} resource is explicitly exposed as render-time data and may execute while rendering the page.`,
+ ]
+ : [],
+ },
invalidatesNamespaces: [
"pages",
"instances",
diff --git a/packages/project-build/src/runtime/instances.test.ts b/packages/project-build/src/runtime/instances.test.ts
index 7f3f5cadd7..31738999cf 100644
--- a/packages/project-build/src/runtime/instances.test.ts
+++ b/packages/project-build/src/runtime/instances.test.ts
@@ -1606,28 +1606,26 @@ describe("fillGrid", () => {
describe("setInstanceTag", () => {
test("sets instance tag and deletes legacy tag prop", () => {
- const result = setInstanceTag(
- {
- instances: new Map([["box", createInstance("box", "Box")]]),
- props: new Map([
- [
- "tag-prop",
- {
- id: "tag-prop",
- instanceId: "box",
- name: "tag",
- type: "string",
- value: "div",
- },
- ],
- ]),
- },
- {
- instanceId: "box",
- tag: "section",
- legacyPropName: "tag",
- }
- );
+ const data = {
+ instances: new Map([["box", createInstance("box", "Box")]]),
+ props: new Map([
+ [
+ "tag-prop",
+ {
+ id: "tag-prop",
+ instanceId: "box",
+ name: "tag",
+ type: "string" as const,
+ value: "div",
+ },
+ ],
+ ]),
+ };
+ const result = setInstanceTag(data, {
+ instanceId: "box",
+ tag: "section",
+ legacyPropName: "tag",
+ });
expect(result.result).toEqual({
instanceId: "box",
@@ -1642,13 +1640,19 @@ describe("setInstanceTag", () => {
namespace: "instances",
patches: [
{
- op: "replace",
+ op: "add",
path: ["box", "tag"],
value: "section",
},
],
},
]);
+ applyBuilderPatchPayloadMutable(
+ (namespace) => data[namespace as keyof typeof data],
+ result.payload
+ );
+ expect(data.instances.get("box")?.tag).toBe("section");
+ expect(data.props.has("tag-prop")).toBe(false);
});
test("does not mutate unchanged tag", () => {
diff --git a/packages/project-build/src/runtime/instances.ts b/packages/project-build/src/runtime/instances.ts
index 5af58dbb54..f22de67468 100644
--- a/packages/project-build/src/runtime/instances.ts
+++ b/packages/project-build/src/runtime/instances.ts
@@ -162,7 +162,7 @@ export const updateTextInstanceInput = z.object({
text: z
.string()
.describe(
- "Replacement visible text when mode is text, or JavaScript expression source when mode is expression."
+ "Replacement visible text when mode is text, or one Webstudio JavaScript expression when mode is expression. Read webstudio://project/expressions for syntax and scope rules."
),
mode: z
.enum(["text", "expression"])
@@ -176,7 +176,11 @@ export const setTextContentInput = z.discriminatedUnion("operation", [
z.object({
operation: z.literal("set"),
instanceId: z.string().describe("Instance id to receive text content."),
- text: z.string().describe("Visible text or JavaScript expression source."),
+ text: z
+ .string()
+ .describe(
+ "Visible text, or one Webstudio JavaScript expression when mode is expression. Read webstudio://project/expressions for syntax and scope rules."
+ ),
mode: z
.enum(["text", "expression"])
.default("text")
@@ -2843,7 +2847,7 @@ export const setInstanceTag = (
namespace: "instances",
patches: [
{
- op: "replace",
+ op: instance.tag === undefined ? "add" : "replace",
path: [input.instanceId, "tag"],
value: input.tag,
},
diff --git a/packages/project-build/src/runtime/migrations.ts b/packages/project-build/src/runtime/migrations.ts
index 214e4c0b0e..31846f6501 100644
--- a/packages/project-build/src/runtime/migrations.ts
+++ b/packages/project-build/src/runtime/migrations.ts
@@ -2,26 +2,13 @@ import { produceWithPatches } from "immer";
import { z } from "zod";
import type { WebstudioData } from "@webstudio-is/sdk";
import { migrateWebstudioDataMutable } from "@webstudio-is/project-migrations";
-import type { BuilderNamespace } from "../contracts/namespaces";
+import { webstudioDataNamespaces } from "../contracts/namespaces";
import { createBuilderPatchPayloadFromImmerPatches } from "../state/patch";
import type { BuilderState } from "../state/builder-state";
import "../state/immer";
import { breakCyclesMutable, findCycles } from "../shared/graph-utils";
import { createRuntimeMutation } from "./mutation";
-const webstudioDataNamespaces = [
- "pages",
- "instances",
- "props",
- "styles",
- "styleSources",
- "styleSourceSelections",
- "dataSources",
- "resources",
- "assets",
- "breakpoints",
-] as const satisfies BuilderNamespace[];
-
export const migrateLoadedDataInput = z.object({}).strict();
export const migrateLoadedData = (state: BuilderState) => {
diff --git a/packages/project-build/src/runtime/page-copy.ts b/packages/project-build/src/runtime/page-copy.ts
index ecefe522af..bfa953907f 100644
--- a/packages/project-build/src/runtime/page-copy.ts
+++ b/packages/project-build/src/runtime/page-copy.ts
@@ -33,6 +33,7 @@ import {
} from "@webstudio-is/sdk";
import type { ConflictResolution } from "./style-copy";
import type { BuilderState } from "../state/builder-state";
+import { webstudioDataNamespaces } from "../contracts/namespaces";
import { throwBuilderRuntimeError } from "./errors";
import { createRuntimeMutation } from "./mutation";
import {
@@ -65,10 +66,36 @@ export const pageDuplicateInput = z.object({
path: z.string().optional(),
});
+const isHydratedWebstudioData = (value: unknown): value is WebstudioData => {
+ if (typeof value !== "object" || value === null) {
+ return false;
+ }
+ const data = value as Partial<WebstudioData>;
+ return webstudioDataNamespaces.every((namespace) => {
+ if (namespace === "pages") {
+ return (
+ data.pages?.pages instanceof Map && data.pages.folders instanceof Map
+ );
+ }
+ return data[namespace] instanceof Map;
+ });
+};
+
+const sourceWebstudioDataInput = z
+ .custom<WebstudioData>(isHydratedWebstudioData, {
+ message:
+ "sourceData must be a hydrated WebstudioData object from the source project",
+ })
+ .describe(
+ "Required hydrated WebstudioData from the source project. This is a low-level cross-project transfer command; use duplicate-page to copy a page within the configured project."
+ );
+
export const pageCopyInput = z.object({
projectId: z.string(),
- sourceData: z.custom<WebstudioData>(),
- pageId: z.string(),
+ sourceData: sourceWebstudioDataInput,
+ pageId: z
+ .string()
+ .describe("ID of the page in sourceData to copy into this project."),
parentFolderId: z.string().optional(),
conflictResolution: z.enum(["ours", "theirs", "merge"]).optional(),
});
@@ -129,19 +156,7 @@ const contentModePageMetaFields = new Set([
]);
const getRequiredWebstudioData = (state: BuilderState): WebstudioData => {
- const required = [
- "pages",
- "assets",
- "dataSources",
- "resources",
- "instances",
- "props",
- "breakpoints",
- "styles",
- "styleSources",
- "styleSourceSelections",
- ] as const;
- for (const namespace of required) {
+ for (const namespace of webstudioDataNamespaces) {
if (state[namespace] === undefined) {
return throwBuilderRuntimeError(
"BAD_REQUEST",
@@ -152,18 +167,7 @@ const getRequiredWebstudioData = (state: BuilderState): WebstudioData => {
return state as WebstudioData;
};
-const pageCopyInvalidatesNamespaces = [
- "pages",
- "assets",
- "dataSources",
- "resources",
- "instances",
- "props",
- "breakpoints",
- "styles",
- "styleSources",
- "styleSourceSelections",
-] as const;
+const pageCopyInvalidatesNamespaces = webstudioDataNamespaces;
const parseCopyNumberSuffix = (value: string) => {
const { name = value, copyNumber = "0" } =
diff --git a/packages/project-build/src/runtime/pages.ts b/packages/project-build/src/runtime/pages.ts
index ead1fd7a3d..b86d98d811 100644
--- a/packages/project-build/src/runtime/pages.ts
+++ b/packages/project-build/src/runtime/pages.ts
@@ -795,7 +795,7 @@ const pageMetaExpressionFields = [
] as const satisfies readonly (keyof PageMetaPatchInput)[];
export const pageExpressionFieldHint =
- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.';
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.';
const jsExpressionStartPattern =
/^\s*(?:["'`[{(]|(?:await|new|typeof|void)\b|(?:undefined|null|true|false)\s*$)/;
diff --git a/packages/project-build/src/runtime/props.ts b/packages/project-build/src/runtime/props.ts
index 64e17c1bc9..4f6b739d37 100644
--- a/packages/project-build/src/runtime/props.ts
+++ b/packages/project-build/src/runtime/props.ts
@@ -183,7 +183,11 @@ const propValueInputVariants = [
z.object({
...propValueBaseInput,
type: z.literal("expression"),
- value: z.string().describe("JavaScript expression source."),
+ value: z
+ .string()
+ .describe(
+ "One Webstudio JavaScript expression, not a statement or function. Read webstudio://project/expressions for syntax and scope rules."
+ ),
}),
z.object({
...propValueBaseInput,
@@ -220,7 +224,14 @@ export const propBindingInput = z
instanceId: z.string(),
name: z.string(),
binding: z.discriminatedUnion("type", [
- z.object({ type: z.literal("expression"), value: z.string() }),
+ z.object({
+ type: z.literal("expression"),
+ value: z
+ .string()
+ .describe(
+ "One Webstudio JavaScript expression. Read webstudio://project/expressions before using unfamiliar scope or syntax."
+ ),
+ }),
z.object({ type: z.literal("parameter"), value: z.string() }),
z.object({ type: z.literal("resource"), value: z.string() }),
z.object({
diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.ts
index 595f490bef..1322561064 100644
--- a/packages/project-build/src/runtime/registry.test.ts
+++ b/packages/project-build/src/runtime/registry.test.ts
@@ -528,6 +528,193 @@ describe("builder runtime read families", () => {
});
});
+ test("binds readable expression names to data sources at write time", () => {
+ const propResult = executeBuilderRuntimeOperation({
+ id: "instances.bindProps",
+ state,
+ input: {
+ bindings: [
+ {
+ instanceId: "heading",
+ name: "title",
+ binding: { type: "expression", value: "Title" },
+ },
+ ],
+ },
+ context,
+ });
+ expect(propResult).toMatchObject({
+ payload: [
+ {
+ namespace: "props",
+ patches: [
+ {
+ value: {
+ type: "expression",
+ value: "$ws$dataSource$variable",
+ },
+ },
+ ],
+ },
+ ],
+ });
+
+ const textResult = executeBuilderRuntimeOperation({
+ id: "instances.updateText",
+ state,
+ input: {
+ instanceId: "heading",
+ childIndex: 0,
+ text: 'Title ?? "Untitled"',
+ mode: "expression",
+ },
+ context,
+ });
+ expect(textResult).toMatchObject({
+ payload: [
+ {
+ namespace: "instances",
+ patches: [
+ {
+ value: {
+ type: "expression",
+ value: '$ws$dataSource$variable ?? "Untitled"',
+ },
+ },
+ ],
+ },
+ ],
+ });
+
+ expect(() =>
+ executeBuilderRuntimeOperation({
+ id: "instances.updateText",
+ state,
+ input: {
+ instanceId: "heading",
+ childIndex: 0,
+ text: "$ws$dataSource$stale.name",
+ mode: "expression",
+ },
+ context,
+ })
+ ).toThrow(/data source "stale".*not available/);
+ });
+
+ test("binds Collection data and item names in their respective scopes", () => {
+ const collectionState = {
+ ...state,
+ instances: new Map([
+ [
+ "body",
+ {
+ type: "instance" as const,
+ id: "body",
+ component: "Body",
+ children: [{ type: "id" as const, value: "collection" }],
+ },
+ ],
+ [
+ "collection",
+ {
+ type: "instance" as const,
+ id: "collection",
+ component: "ws:collection",
+ children: [{ type: "id" as const, value: "item" }],
+ },
+ ],
+ [
+ "item",
+ {
+ type: "instance" as const,
+ id: "item",
+ component: "Text",
+ children: [{ type: "text" as const, value: "Item" }],
+ },
+ ],
+ ]),
+ props: new Map(),
+ dataSources: new Map([
+ [
+ "plans",
+ {
+ id: "plans",
+ type: "variable" as const,
+ name: "Plans",
+ scopeInstanceId: "body",
+ value: { type: "json" as const, value: [{ name: "Starter" }] },
+ },
+ ],
+ [
+ "item-parameter",
+ {
+ id: "item-parameter",
+ type: "parameter" as const,
+ name: "collectionItem",
+ scopeInstanceId: "collection",
+ },
+ ],
+ ]),
+ } satisfies BuilderState;
+
+ expect(
+ executeBuilderRuntimeOperation({
+ id: "instances.bindProps",
+ state: collectionState,
+ input: {
+ bindings: [
+ {
+ instanceId: "collection",
+ name: "data",
+ binding: { type: "expression", value: "Plans" },
+ },
+ ],
+ },
+ context,
+ })
+ ).toMatchObject({
+ payload: [
+ {
+ namespace: "props",
+ patches: [
+ {
+ value: {
+ value: "$ws$dataSource$plans",
+ },
+ },
+ ],
+ },
+ ],
+ });
+
+ expect(
+ executeBuilderRuntimeOperation({
+ id: "instances.updateText",
+ state: collectionState,
+ input: {
+ instanceId: "item",
+ childIndex: 0,
+ text: "collectionItem.name",
+ mode: "expression",
+ },
+ context,
+ })
+ ).toMatchObject({
+ payload: [
+ {
+ namespace: "instances",
+ patches: [
+ {
+ value: {
+ value: "$ws$dataSource$item__DASH__parameter.name",
+ },
+ },
+ ],
+ },
+ ],
+ });
+ });
+
test("replaces bounded static prop text without changing dynamic bindings", () => {
const replaceState = {
...state,
@@ -1243,6 +1430,54 @@ describe("builder runtime registry", () => {
}
});
+ test("publishes truthful inputs for asset, page-copy, style-source, and resource operations", () => {
+ const addAssetOperation = getBuilderRuntimeOperation("assets.add");
+ const addAssetSchema = toInputJsonSchemaObject(
+ addAssetOperation.inputJsonSchema
+ );
+ const assetSchema = toInputJsonSchemaObject(
+ addAssetSchema?.properties?.asset
+ );
+ expect(JSON.stringify(assetSchema)).not.toContain("projectId");
+
+ for (const operationId of [
+ "resources.create",
+ "resources.update",
+ ] as const) {
+ const operation = getBuilderRuntimeOperation(operationId);
+ const schema = toInputJsonSchemaObject(operation.inputJsonSchema);
+ expect(
+ toInputJsonSchemaObject(schema?.properties?.exposeAsDataSource)
+ ?.description
+ ).toContain("write resources default to false");
+ }
+
+ const copyPageOperation = getBuilderRuntimeOperation("pages.copy");
+ const copyPageSchema = toInputJsonSchemaObject(
+ copyPageOperation.inputJsonSchema
+ );
+ expect(copyPageSchema?.required).toContain("sourceData");
+ expect(
+ toInputJsonSchemaObject(copyPageSchema?.properties?.sourceData)
+ ?.description
+ ).toContain("use duplicate-page");
+ expect(() =>
+ copyPageOperation.execute({ state, input: { pageId: "home" }, context })
+ ).toThrow("sourceData");
+
+ const duplicateStyleSourceOperation = getBuilderRuntimeOperation(
+ "styleSources.duplicate"
+ );
+ const duplicateStyleSourceSchema = toInputJsonSchemaObject(
+ duplicateStyleSourceOperation.inputJsonSchema
+ );
+ expect(
+ toInputJsonSchemaObject(
+ duplicateStyleSourceSchema?.properties?.styleSourceId
+ )?.description
+ ).toContain("Local style sources cannot be duplicated");
+ });
+
test("keeps router adapter policy in runtime metadata", () => {
for (const operation of builderRuntimeOperations) {
expect(operation.requiresAssets).toBe(
diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.ts
index 17db23b0d1..a9073b9d92 100644
--- a/packages/project-build/src/runtime/registry.ts
+++ b/packages/project-build/src/runtime/registry.ts
@@ -106,6 +106,22 @@ const parseOperationInput = <Schema extends z.ZodTypeAny>(
throw result.error;
};
+const bindExpressionInput = (
+ state: BuilderState,
+ instanceId: string,
+ expression: string
+) => {
+ if (state.instances === undefined || state.dataSources === undefined) {
+ return expression;
+ }
+ return data.bindExpressionToInstanceScope({
+ expression,
+ instanceId,
+ instances: state.instances,
+ dataSources: state.dataSources,
+ });
+};
+
const runtimeOperation = <
Id extends string,
Schema extends z.ZodTypeAny,
@@ -312,7 +328,7 @@ export const builderRuntimeOperations = [
runtimeOperation(
"pages.list",
api("list-pages", "listPages"),
- readContract(["pages", "projectSettings"]),
+ readContract(["pages"]),
pageListInput,
({ state, input }) => pages.listPages(state, input)
),
@@ -956,11 +972,29 @@ export const builderRuntimeOperations = [
"instances.updateProps",
api("update-props", "updateProps", "edit"),
mutationContract({
- readNamespaces: ["instances", "props"],
+ readNamespaces: ["instances", "props", "dataSources"],
writeNamespaces: ["props"],
}),
props.propUpdatesInput,
- ({ state, input, context }) => props.updateProps(state, input, context)
+ ({ state, input, context }) =>
+ props.updateProps(
+ state,
+ {
+ updates: input.updates.map((update) =>
+ update.type === "expression"
+ ? {
+ ...update,
+ value: bindExpressionInput(
+ state,
+ update.instanceId,
+ update.value
+ ),
+ }
+ : update
+ ),
+ },
+ context
+ )
),
runtimeOperation(
"instances.replacePropText",
@@ -991,7 +1025,28 @@ export const builderRuntimeOperations = [
writeNamespaces: ["props"],
}),
props.propBindingsInput,
- ({ state, input, context }) => props.bindProps(state, input, context)
+ ({ state, input, context }) =>
+ props.bindProps(
+ state,
+ {
+ bindings: input.bindings.map((binding) =>
+ binding.binding.type === "expression"
+ ? {
+ ...binding,
+ binding: {
+ ...binding.binding,
+ value: bindExpressionInput(
+ state,
+ binding.instanceId,
+ binding.binding.value
+ ),
+ },
+ }
+ : binding
+ ),
+ },
+ context
+ )
),
runtimeOperation(
"instances.listTexts",
@@ -1004,12 +1059,21 @@ export const builderRuntimeOperations = [
"instances.updateText",
api("update-text", "updateText", "edit"),
mutationContract({
- readNamespaces: ["instances"],
+ readNamespaces: ["instances", "dataSources"],
writeNamespaces: ["instances"],
retryOnConflict: true,
}),
instances.updateTextInstanceInput,
- ({ state, input }) => instances.updateTextInstance(state, input)
+ ({ state, input }) =>
+ instances.updateTextInstance(
+ state,
+ input.mode === "expression"
+ ? {
+ ...input,
+ text: bindExpressionInput(state, input.instanceId, input.text),
+ }
+ : input
+ )
),
runtimeOperation(
"instances.replaceText",
@@ -1026,12 +1090,21 @@ export const builderRuntimeOperations = [
"instances.setTextContent",
api("set-text-content", "setTextContent", "edit"),
mutationContract({
- readNamespaces: ["instances"],
+ readNamespaces: ["instances", "dataSources"],
writeNamespaces: ["instances"],
retryOnConflict: true,
}),
instances.setTextContentInput,
- ({ state, input }) => instances.setTextContent(state, input)
+ ({ state, input }) =>
+ instances.setTextContent(
+ state,
+ input.operation === "set" && input.mode === "expression"
+ ? {
+ ...input,
+ text: bindExpressionInput(state, input.instanceId, input.text),
+ }
+ : input
+ )
),
runtimeOperation(
"instances.updateTextTree",
@@ -1446,7 +1519,7 @@ export const builderRuntimeOperations = [
],
}),
data.resourceUpdateInput,
- ({ state, input }) => data.updateResource(state, input)
+ ({ state, input, context }) => data.updateResource(state, input, context)
),
runtimeOperation(
"resources.replaceText",
@@ -1570,7 +1643,7 @@ export const builderRuntimeOperations = [
retryOnConflict: true,
}),
assets.assetAddInput,
- ({ state, input }) => assets.addAsset(state, input)
+ ({ state, input, context }) => assets.addAsset(state, input, context)
),
runtimeOperation(
"assets.replace",
diff --git a/packages/project-build/src/runtime/styles.test.ts b/packages/project-build/src/runtime/styles.test.ts
index 6256ab6678..58b43d7546 100644
--- a/packages/project-build/src/runtime/styles.test.ts
+++ b/packages/project-build/src/runtime/styles.test.ts
@@ -1382,6 +1382,23 @@ describe("runtime style operations", () => {
},
]);
+ expect(() =>
+ duplicateStyleSource(
+ {
+ instances,
+ styles: createStyleDeclMap([]),
+ styleSources: sources([local("local")]),
+ styleSourceSelections: new Map([
+ ["box", { instanceId: "box", values: ["local"] }],
+ ]),
+ },
+ { instanceId: "box", styleSourceId: "local" },
+ { createId }
+ )
+ ).toThrow(
+ "Local style sources cannot be duplicated. Convert the local style source to a design token first."
+ );
+
const convertMutation = convertLocalStyleSourceToToken(
{
instances,
diff --git a/packages/project-build/src/runtime/styles.ts b/packages/project-build/src/runtime/styles.ts
index 0eb0fa4ac6..6747f8947f 100644
--- a/packages/project-build/src/runtime/styles.ts
+++ b/packages/project-build/src/runtime/styles.ts
@@ -1158,7 +1158,11 @@ export const styleSourceClearStylesInput = z.object({
export const styleSourceDuplicateInput = z.object({
instanceId: z.string(),
- styleSourceId: z.string(),
+ styleSourceId: z
+ .string()
+ .describe(
+ "ID of an attached design token to duplicate. Local style sources cannot be duplicated; convert the local source to a design token first."
+ ),
});
export const styleSourceConvertLocalToTokenInput = z.object({
@@ -2206,9 +2210,15 @@ export const duplicateStyleSource = (
const styleState = getRequiredStyleMutationState(state);
assertStyleInstances(styleState.instances, [input.instanceId]);
const styleSource = styleState.styleSources.get(input.styleSourceId);
- if (styleSource?.type !== "token") {
+ if (styleSource === undefined) {
return throwBuilderRuntimeError("NOT_FOUND", "Style source not found");
}
+ if (styleSource.type === "local") {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "Local style sources cannot be duplicated. Convert the local style source to a design token first."
+ );
+ }
const styleSourceSelection = styleState.styleSourceSelections.get(
input.instanceId
);
diff --git a/packages/protocol/src/builder-api/operations.test.ts b/packages/protocol/src/builder-api/operations.test.ts
index 59731f15dc..8ca9dcdfaa 100644
--- a/packages/protocol/src/builder-api/operations.test.ts
+++ b/packages/protocol/src/builder-api/operations.test.ts
@@ -61,6 +61,7 @@ describe("public api operation catalog", () => {
"resource",
"scopeInstanceId",
"dataSourceName",
+ "exposeAsDataSource",
]);
expect(getPublicApiOperation("create-domain").inputFields).toEqual([
"domain",
diff --git a/packages/protocol/src/builder-api/operations.ts b/packages/protocol/src/builder-api/operations.ts
index 192b335700..3ed32dfa20 100644
--- a/packages/protocol/src/builder-api/operations.ts
+++ b/packages/protocol/src/builder-api/operations.ts
@@ -1,3 +1,4 @@
+import hash from "@emotion/hash";
import { serverOnlyRouterOperationMetadata } from "./__generated__/server-only-router-operation-metadata";
import { localOnlyOperationInputs } from "./local-operation-inputs";
import { publicApiOperationDocumentation } from "./operation-docs";
@@ -164,6 +165,34 @@ export const publicApiOperations = publicApiOperationDocumentation.map(
({ command }) => withDefaultPermit(getOperationInputByCommand(command))
);
+const operationsRequiringNegotiatedServerSupport = new Set([
+ "instances.insertComponent",
+ "instances.insertFragment",
+]);
+
+export const publicApiOperationRequiresServerSupport = (operation: {
+ id: string;
+ serverOnly: boolean;
+}) =>
+ operation.serverOnly ||
+ operationsRequiringNegotiatedServerSupport.has(operation.id);
+
+export const publicApiContractVersion = `public-api:${hash(
+ JSON.stringify(
+ publicApiOperations.map(({ command, id, method, path, serverOnly }) => ({
+ command,
+ id,
+ method,
+ path,
+ serverOnly,
+ requiresServerSupport: publicApiOperationRequiresServerSupport({
+ id,
+ serverOnly,
+ }),
+ }))
+ )
+)}`;
+
const publicApiOperationByCommand = new Map(
publicApiOperations.map((operation) => [operation.command, operation])
);
diff --git a/packages/react-sdk/package.json b/packages/react-sdk/package.json
index 010fa75b49..7019571c07 100644
--- a/packages/react-sdk/package.json
+++ b/packages/react-sdk/package.json
@@ -20,7 +20,7 @@
"react-dom": "18.3.0-canary-14898b6a9-20240318",
"strip-indent": "^4.0.0",
"type-fest": "^4.37.0",
- "typescript": "npm:@typescript/typescript6@^6.0.2",
+ "typescript": "7.0.2",
"vitest": "^3.1.2",
"zod": "^4.4.3"
},
diff --git a/packages/react-sdk/src/component-generator.test.tsx b/packages/react-sdk/src/component-generator.test.tsx
index 4f10d17e05..ededd245f4 100644
--- a/packages/react-sdk/src/component-generator.test.tsx
+++ b/packages/react-sdk/src/component-generator.test.tsx
@@ -1,5 +1,5 @@
-import ts from "typescript";
-import { expect, test } from "vitest";
+import { API, type Snapshot } from "typescript/unstable/sync";
+import { afterAll, beforeAll, expect, test } from "vitest";
import stripIndent from "strip-indent";
import {
createScope,
@@ -26,45 +26,54 @@ import {
generateWebstudioComponent,
} from "./component-generator";
-const isValidJSX = (code: string): boolean => {
- // Create a "virtual" TypeScript program
- const compilerHost = ts.createCompilerHost({});
- const fileName = "virtual.tsx";
-
- compilerHost.getSourceFile = (filename) => {
- if (filename === fileName) {
- return ts.createSourceFile(
- filename,
- code,
- ts.ScriptTarget.Latest,
- true,
- ts.ScriptKind.TSX
- );
- }
- return;
- };
-
- const program = ts.createProgram(
- [fileName],
- {
- jsx: ts.JsxEmit.React,
- strict: true,
+const virtualRoot = "/component-generator-test";
+const virtualConfig = `${virtualRoot}/tsconfig.json`;
+const virtualFile = `${virtualRoot}/virtual.tsx`;
+let virtualCode = "";
+const typeScriptApi = new API({
+ cwd: virtualRoot,
+ fs: {
+ readFile(fileName) {
+ if (fileName === virtualConfig) {
+ return JSON.stringify({
+ compilerOptions: { jsx: "preserve", strict: true },
+ files: [virtualFile],
+ });
+ }
+ if (fileName === virtualFile) {
+ return virtualCode;
+ }
},
- compilerHost
- );
-
- const sourceFile = program.getSourceFile(fileName);
+ fileExists(fileName) {
+ return fileName === virtualConfig || fileName === virtualFile;
+ },
+ directoryExists(directoryName) {
+ return directoryName === virtualRoot;
+ },
+ },
+});
+let typeScriptSnapshot: Snapshot;
- if (!sourceFile) {
- return false;
- }
+beforeAll(() => {
+ typeScriptSnapshot = typeScriptApi.updateSnapshot({
+ openProjects: [virtualConfig],
+ });
+});
- const diagnostics = [
- ...program.getSyntacticDiagnostics(sourceFile),
- // ...program.getSemanticDiagnostics(sourceFile),
- ];
+afterAll(() => {
+ typeScriptSnapshot.dispose();
+ typeScriptApi.close();
+});
- return diagnostics.length === 0;
+const isValidJSX = (code: string): boolean => {
+ virtualCode = code;
+ const previousSnapshot = typeScriptSnapshot;
+ typeScriptSnapshot = typeScriptApi.updateSnapshot({
+ fileChanges: { changed: [virtualFile] },
+ });
+ previousSnapshot.dispose();
+ const project = typeScriptSnapshot.getProject(virtualConfig);
+ return project?.program.getSyntacticDiagnostics(virtualFile).length === 0;
};
const validateJSX = (code: string) => {
diff --git a/packages/sdk-components-react-remix/package.json b/packages/sdk-components-react-remix/package.json
index 1c85be83d9..7ddaa9d0c7 100644
--- a/packages/sdk-components-react-remix/package.json
+++ b/packages/sdk-components-react-remix/package.json
@@ -40,6 +40,7 @@
"@types/react-dom": "^18.2.25",
"@webstudio-is/tsconfig": "workspace:*",
"react": "18.3.0-canary-14898b6a9-20240318",
- "react-dom": "18.3.0-canary-14898b6a9-20240318"
+ "react-dom": "18.3.0-canary-14898b6a9-20240318",
+ "typescript": "7.0.2"
}
}
diff --git a/packages/sdk/src/core-metas.ts b/packages/sdk/src/core-metas.ts
index d7e2f4816e..3159b8af88 100644
--- a/packages/sdk/src/core-metas.ts
+++ b/packages/sdk/src/core-metas.ts
@@ -43,8 +43,12 @@ export const portalComponent = "Slot";
export const collectionComponent = "ws:collection";
+export const collectionDescription =
+ "Use Collection when an array or object from a resource or data variable should render repeated UI. Collection iterates the complete value and renders its child structure once for every item, exposing the current item and key to descendants.";
+
const collectionMeta: WsComponentMeta = {
label: "Collection",
+ description: collectionDescription,
icon: ListViewIcon,
contentModel: {
category: "instance",
diff --git a/packages/sdk/src/core-templates.tsx b/packages/sdk/src/core-templates.tsx
index 02982b5969..12d3178c51 100644
--- a/packages/sdk/src/core-templates.tsx
+++ b/packages/sdk/src/core-templates.tsx
@@ -15,6 +15,7 @@ import {
import {
blockComponent,
collectionComponent,
+ collectionDescription,
descendantComponent,
elementComponent,
} from "./core-metas";
@@ -48,6 +49,7 @@ const collectionItemKey = new Parameter("collectionItemKey");
const collectionMeta: TemplateMeta = {
category: "data",
order: 2,
+ description: collectionDescription,
template: (
<ws.collection
data={["Collection Item 1", "Collection Item 2", "Collection Item 3"]}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c6c12aefa7..01c1937749 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -512,16 +512,16 @@ importers:
'@react-router/dev':
specifier: ^7.5.3
'@react-router/fs-routes':
specifier: ^7.5.3
'@react-router/node':
specifier: ^7.5.3
'@react-router/serve':
specifier: ^7.5.3
'@webstudio-is/image':
specifier: workspace:*
version: link:../../packages/image
@@ -575,23 +575,23 @@ importers:
specifier: ^18.2.25
version: 18.2.25
typescript:
- specifier: 5.8.2
- version: 5.8.2
+ specifier: 7.0.2
+ version: 7.0.2
fixtures/react-router-docker:
dependencies:
'@react-router/dev':
specifier: ^7.5.3
'@react-router/fs-routes':
specifier: ^7.5.3
'@react-router/node':
specifier: ^7.5.3
'@react-router/serve':
specifier: ^7.5.3
'@webstudio-is/image':
specifier: workspace:*
version: link:../../packages/image
@@ -648,26 +648,26 @@ importers:
specifier: ^18.2.25
version: 18.2.25
typescript:
- specifier: 5.8.2
- version: 5.8.2
+ specifier: 7.0.2
+ version: 7.0.2
fixtures/react-router-netlify:
dependencies:
'@netlify/vite-plugin-react-router':
specifier: ^1.0.1
'@react-router/dev':
specifier: ^7.5.3
'@react-router/fs-routes':
specifier: ^7.5.3
'@react-router/node':
specifier: ^7.5.3
'@react-router/serve':
specifier: ^7.5.3
'@webstudio-is/image':
specifier: workspace:*
version: link:../../packages/image
@@ -718,26 +718,26 @@ importers:
specifier: ^18.2.25
version: 18.2.25
typescript:
- specifier: 5.8.2
- version: 5.8.2
+ specifier: 7.0.2
+ version: 7.0.2
fixtures/react-router-vercel:
dependencies:
'@react-router/dev':
specifier: ^7.5.3
'@react-router/fs-routes':
specifier: ^7.5.3
'@react-router/node':
specifier: ^7.5.3
'@react-router/serve':
specifier: ^7.5.3
'@vercel/react-router':
specifier: ^1.1.0
'@webstudio-is/image':
specifier: workspace:*
version: link:../../packages/image
@@ -788,8 +788,8 @@ importers:
specifier: ^18.2.25
version: 18.2.25
typescript:
- specifier: 5.8.2
- version: 5.8.2
+ specifier: 7.0.2
+ version: 7.0.2
fixtures/ssg-cloudflare-pages:
dependencies:
@@ -836,12 +836,9 @@ importers:
'@vitejs/plugin-react':
specifier: ^4.4.1
- prettier:
- specifier: 3.5.3
- version: 3.5.3
typescript:
- specifier: 5.8.2
- version: 5.8.2
+ specifier: 7.0.2
+ version: 7.0.2
vite:
specifier: 6.3.4
@@ -894,12 +891,9 @@ importers:
'@vitejs/plugin-react':
specifier: ^4.4.1
- prettier:
- specifier: 3.5.3
- version: 3.5.3
typescript:
- specifier: 5.8.2
- version: 5.8.2
+ specifier: 7.0.2
+ version: 7.0.2
vite:
specifier: 6.3.4
@@ -911,19 +905,19 @@ importers:
dependencies:
'@remix-run/cloudflare':
specifier: 2.16.5
- version: 2.16.5(@cloudflare/[email protected])([email protected])
+ version: 2.16.5(@cloudflare/[email protected])([email protected])
'@remix-run/cloudflare-pages':
specifier: 2.16.5
- version: 2.16.5(@cloudflare/[email protected])([email protected])
+ version: 2.16.5(@cloudflare/[email protected])([email protected])
'@remix-run/node':
specifier: 2.16.5
- version: 2.16.5([email protected])
+ version: 2.16.5([email protected])
'@remix-run/react':
specifier: 2.16.5
'@remix-run/server-runtime':
specifier: 2.16.5
- version: 2.16.5([email protected])
+ version: 2.16.5([email protected])
'@webstudio-is/image':
specifier: workspace:*
version: link:../../packages/image
@@ -972,7 +966,7 @@ importers:
version: 4.20240701.0
'@remix-run/dev':
specifier: 2.16.5
'@types/react':
specifier: ^18.2.70
version: 18.2.79
@@ -983,8 +977,8 @@ importers:
specifier: ^3.3.2
version: 3.3.2
typescript:
- specifier: 5.8.2
- version: 5.8.2
+ specifier: 7.0.2
+ version: 7.0.2
vite:
specifier: 6.3.4
@@ -999,16 +993,16 @@ importers:
version: 2.14.4
'@react-router/dev':
specifier: ^7.5.3
'@react-router/fs-routes':
specifier: ^7.5.3
'@react-router/node':
specifier: ^7.5.3
'@react-router/serve':
specifier: ^7.5.3
'@webstudio-is/image':
specifier: workspace:*
version: link:../../packages/image
@@ -1062,8 +1056,8 @@ importers:
specifier: ^3.3.2
version: 3.3.2
typescript:
- specifier: 5.8.2
- version: 5.8.2
+ specifier: 7.0.2
+ version: 7.0.2
packages/asset-uploader:
dependencies:
@@ -1165,9 +1159,6 @@ importers:
'@webstudio-is/protocol':
specifier: workspace:*
version: link:../protocol
- '@webstudio-is/sdk-components-registry':
- specifier: workspace:*
- version: link:../sdk-components-registry
'@webstudio-is/sync-client':
specifier: workspace:*
version: link:../sync-client
@@ -1319,6 +1310,9 @@ importers:
'@webstudio-is/sdk-components-react-router':
specifier: workspace:*
version: link:../sdk-components-react-router
+ '@webstudio-is/sdk-components-registry':
+ specifier: workspace:*
+ version: link:../sdk-components-registry
'@webstudio-is/tsconfig':
specifier: workspace:*
version: link:../tsconfig
@@ -1346,9 +1340,9 @@ importers:
micromark-extension-directive:
specifier: ^4.0.0
version: 4.0.0
- prettier:
- specifier: 3.5.3
- version: 3.5.3
+ oxfmt:
+ specifier: 0.58.0
+ version: 0.58.0
react:
specifier: 18.3.0-canary-14898b6a9-20240318
version: 18.3.0-canary-14898b6a9-20240318
@@ -1723,12 +1717,6 @@ importers:
fast-glob:
specifier: ^3.3.2
version: 3.3.2
- react-docgen-typescript:
- specifier: ^2.2.2
- version: 2.2.2([email protected])
- typescript:
- specifier: 5.8.2
- version: 5.8.2
zod:
specifier: ^4.4.3
version: 4.4.3
@@ -1736,6 +1724,12 @@ importers:
'@webstudio-is/tsconfig':
specifier: workspace:*
version: link:../tsconfig
+ react-docgen-typescript:
+ specifier: 2.2.2
+ version: 2.2.2([email protected])
+ typescript:
+ specifier: 5.8.2
+ version: 5.8.2
packages/html-data:
devDependencies:
@@ -2191,11 +2185,11 @@ importers:
specifier: ^4.37.0
version: 4.37.0
typescript:
- specifier: npm:@typescript/typescript6@^6.0.2
- version: '@typescript/[email protected]'
+ specifier: 7.0.2
+ version: 7.0.2
vitest:
specifier: ^3.1.2
zod:
specifier: ^4.4.3
version: 4.4.3
@@ -2537,7 +2531,7 @@ importers:
devDependencies:
'@remix-run/react':
specifier: ^2.16.5
'@types/react':
specifier: ^18.2.70
version: 18.2.79
@@ -2553,6 +2547,9 @@ importers:
react-dom:
specifier: 18.3.0-canary-14898b6a9-20240318
version: 18.3.0-canary-14898b6a9-20240318([email protected])
+ typescript:
+ specifier: 7.0.2
+ version: 7.0.2
packages/sdk-components-react-router:
dependencies:
@@ -6445,10 +6442,6 @@ packages:
cpu: [x64]
os: [win32]
- '@typescript/[email protected]':
- resolution: {integrity: sha512-mbCddXd+jm7hfx7w2YU64/Av4/NqqeG3GoRZgxPcgoTxYjhrcfJRw9ULch71SS4G+Q3bOXFhRvPqjguN0Hyp5w==}
- hasBin: true
-
'@unocss/[email protected]':
resolution: {integrity: sha512-P9IlQfgms+8/nka7fBhiiWU4SPwrTNKbTdK0z1SLnttXMHHjsB2zpG+Vi1JQDpICfY9Y1/2pWtguPE+zeOVu9Q==}
@@ -10549,11 +10542,6 @@ packages:
engines: {node: '>=14.17'}
hasBin: true
- resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==}
- engines: {node: '>=14.17'}
- hasBin: true
-
resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==}
engines: {node: '>=16.20.0'}
@@ -13070,17 +13058,6 @@ snapshots:
nanostores: 0.11.3
react: 18.3.0-canary-14898b6a9-20240318
- dependencies:
- isbot: 5.1.25
- transitivePeerDependencies:
- - react
- - react-dom
- - typescript
-
dependencies:
@@ -14140,7 +14117,7 @@ snapshots:
react: 18.3.0-canary-14898b6a9-20240318
react-dom: 18.3.0-canary-14898b6a9-20240318([email protected])
dependencies:
'@babel/core': 7.29.7
'@babel/generator': 7.29.7
@@ -14151,7 +14128,7 @@ snapshots:
'@babel/traverse': 7.29.7
'@babel/types': 7.29.7
'@npmcli/package-json': 4.0.1
arg: 5.0.2
babel-dead-code-elimination: 1.0.8
chokidar: 4.0.3
@@ -14168,13 +14145,13 @@ snapshots:
semver: 7.7.1
set-cookie-parser: 2.7.2
- valibot: 0.41.0([email protected])
+ valibot: 0.41.0([email protected])
optionalDependencies:
- typescript: 5.8.2
- wrangler: 4.14.1
+ typescript: 7.0.2
+ wrangler: 3.63.2(@cloudflare/[email protected])
transitivePeerDependencies:
- '@types/node'
- babel-plugin-macros
@@ -14191,7 +14168,7 @@ snapshots:
- tsx
- yaml
dependencies:
'@babel/core': 7.29.7
'@babel/generator': 7.29.7
@@ -14225,7 +14202,7 @@ snapshots:
optionalDependencies:
typescript: 7.0.2
- wrangler: 3.63.2(@cloudflare/[email protected])
+ wrangler: 4.14.1
transitivePeerDependencies:
- '@types/node'
- babel-plugin-macros
@@ -14242,14 +14219,6 @@ snapshots:
- tsx
- yaml
- dependencies:
- express: 4.21.1
- optionalDependencies:
- typescript: 5.8.2
-
dependencies:
@@ -14258,13 +14227,6 @@ snapshots:
optionalDependencies:
typescript: 7.0.2
- dependencies:
- minimatch: 9.0.4
- optionalDependencies:
- typescript: 5.8.2
-
dependencies:
@@ -14272,15 +14234,12 @@ snapshots:
optionalDependencies:
typescript: 7.0.2
dependencies:
- '@mjackson/node-fetch-server': 0.2.0
- source-map-support: 0.5.21
- stream-slice: 0.1.2
- undici: 6.21.2
+ minimatch: 9.0.4
optionalDependencies:
- typescript: 5.8.2
+ typescript: 7.0.2
dependencies:
@@ -14292,20 +14251,6 @@ snapshots:
optionalDependencies:
typescript: 7.0.2
- dependencies:
- compression: 1.7.4
- express: 4.21.1
- get-port: 5.1.1
- morgan: 1.10.0
- source-map-support: 0.5.21
- transitivePeerDependencies:
- - supports-color
- - typescript
-
dependencies:
@@ -14334,12 +14279,12 @@ snapshots:
cluster-key-slot: 1.1.2
optional: true
dependencies:
'@cloudflare/workers-types': 4.20240701.0
- '@remix-run/cloudflare': 2.16.5(@cloudflare/[email protected])([email protected])
+ '@remix-run/cloudflare': 2.16.5(@cloudflare/[email protected])([email protected])
optionalDependencies:
- typescript: 5.8.2
+ typescript: 7.0.2
dependencies:
@@ -14348,13 +14293,13 @@ snapshots:
optionalDependencies:
typescript: 7.0.2
dependencies:
'@cloudflare/kv-asset-handler': 0.1.3
'@cloudflare/workers-types': 4.20240701.0
- '@remix-run/server-runtime': 2.16.5([email protected])
+ '@remix-run/server-runtime': 2.16.5([email protected])
optionalDependencies:
- typescript: 5.8.2
+ typescript: 7.0.2
dependencies:
@@ -14364,7 +14309,7 @@ snapshots:
optionalDependencies:
typescript: 7.0.2
dependencies:
'@babel/core': 7.26.10
'@babel/generator': 7.27.0
@@ -14376,10 +14321,10 @@ snapshots:
'@babel/types': 7.27.0
'@mdx-js/mdx': 2.3.0
'@npmcli/package-json': 4.0.1
- '@remix-run/node': 2.16.5([email protected])
+ '@remix-run/node': 2.16.5([email protected])
'@remix-run/router': 1.23.0
- '@remix-run/server-runtime': 2.16.5([email protected])
+ '@remix-run/server-runtime': 2.16.5([email protected])
'@types/mdx': 2.0.13
'@vanilla-extract/integration': 6.5.0(@types/[email protected])([email protected])([email protected])([email protected])
arg: 5.0.2
@@ -14420,12 +14365,12 @@ snapshots:
set-cookie-parser: 2.6.0
tar-fs: 2.1.1
tsconfig-paths: 4.2.0
- valibot: 0.41.0([email protected])
+ valibot: 0.41.0([email protected])
ws: 7.5.10
optionalDependencies:
- '@remix-run/serve': 2.16.5([email protected])
- typescript: 5.8.2
+ '@remix-run/serve': 2.16.5([email protected])
+ typescript: 7.0.2
wrangler: 3.63.2(@cloudflare/[email protected])
transitivePeerDependencies:
@@ -14530,14 +14475,6 @@ snapshots:
- utf-8-validate
- yaml
- dependencies:
- '@remix-run/node': 2.16.5([email protected])
- express: 4.21.1
- optionalDependencies:
- typescript: 5.8.2
- optional: true
-
dependencies:
'@remix-run/node': 2.16.5([email protected])
@@ -14545,18 +14482,6 @@ snapshots:
optionalDependencies:
typescript: 7.0.2
- dependencies:
- '@remix-run/server-runtime': 2.16.5([email protected])
- '@remix-run/web-fetch': 4.4.2
- '@web3-storage/multipart-parser': 1.0.0
- cookie-signature: 1.2.0
- source-map-support: 0.5.21
- stream-slice: 0.1.2
- undici: 6.21.2
- optionalDependencies:
- typescript: 5.8.2
-
dependencies:
'@remix-run/server-runtime': 2.16.5([email protected])
@@ -14569,18 +14494,6 @@ snapshots:
optionalDependencies:
typescript: 7.0.2
- dependencies:
- '@remix-run/router': 1.23.0
- '@remix-run/server-runtime': 2.16.5([email protected])
- react: 18.3.0-canary-14898b6a9-20240318
- react-dom: 18.3.0-canary-14898b6a9-20240318([email protected])
- react-router: 6.30.0([email protected])
- turbo-stream: 2.4.0
- optionalDependencies:
- typescript: 5.8.2
-
dependencies:
'@remix-run/router': 1.23.0
@@ -14595,21 +14508,6 @@ snapshots:
'@remix-run/[email protected]': {}
- dependencies:
- '@remix-run/express': 2.16.5([email protected])([email protected])
- '@remix-run/node': 2.16.5([email protected])
- chokidar: 3.6.0
- compression: 1.7.4
- express: 4.21.1
- get-port: 5.1.1
- morgan: 1.10.0
- source-map-support: 0.5.21
- transitivePeerDependencies:
- - supports-color
- - typescript
- optional: true
-
dependencies:
'@remix-run/express': 2.16.5([email protected])([email protected])
@@ -14624,18 +14522,6 @@ snapshots:
- supports-color
- typescript
- dependencies:
- '@remix-run/router': 1.23.0
- '@types/cookie': 0.6.0
- '@web3-storage/multipart-parser': 1.0.0
- cookie: 0.7.2
- set-cookie-parser: 2.6.0
- source-map: 0.7.4
- turbo-stream: 2.4.0
- optionalDependencies:
- typescript: 5.8.2
-
dependencies:
'@remix-run/router': 1.23.0
@@ -15306,10 +15192,6 @@ snapshots:
'@typescript/[email protected]':
optional: true
- '@typescript/[email protected]':
- dependencies:
- '@typescript/old': [email protected]
-
'@unocss/[email protected]': {}
'@unocss/[email protected]':
@@ -15381,19 +15263,19 @@ snapshots:
'@vanilla-extract/[email protected]': {}
dependencies:
'@vercel/static-config': 3.0.0
isbot: 5.1.25
react: 18.3.0-canary-14898b6a9-20240318
react-dom: 18.3.0-canary-14898b6a9-20240318([email protected])
ts-morph: 12.0.0
dependencies:
'@vercel/static-config': 3.0.0
isbot: 5.1.25
@@ -15429,26 +15311,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- dependencies:
- '@testing-library/dom': 10.4.0
- '@testing-library/user-event': 14.6.1(@testing-library/[email protected])
- '@vitest/utils': 3.1.2
- magic-string: 0.30.21
- sirv: 3.0.1
- tinyrainbow: 2.0.0
- ws: 8.21.0
- optionalDependencies:
- playwright: 1.50.1
- transitivePeerDependencies:
- - bufferutil
- - msw
- - utf-8-validate
- - vite
- optional: true
-
dependencies:
'@testing-library/dom': 10.4.0
@@ -15495,15 +15357,6 @@ snapshots:
chai: 5.2.0
tinyrainbow: 2.0.0
- dependencies:
- '@vitest/spy': 3.1.2
- estree-walker: 3.0.3
- magic-string: 0.30.17
- optionalDependencies:
- msw: 2.13.2(@types/[email protected])(@typescript/[email protected])
-
dependencies:
'@vitest/spy': 3.1.2
@@ -18579,32 +18432,6 @@ snapshots:
- dependencies:
- '@inquirer/confirm': 5.1.5(@types/[email protected])
- '@mswjs/interceptors': 0.41.3
- '@open-draft/deferred-promise': 2.2.0
- '@types/statuses': 2.0.6
- cookie: 1.1.1
- graphql: 16.13.2
- headers-polyfill: 4.0.3
- is-node-process: 1.2.0
- outvariant: 1.4.3
- path-to-regexp: 6.3.0
- picocolors: 1.1.1
- rettime: 0.10.1
- statuses: 2.0.2
- strict-event-emitter: 0.5.1
- tough-cookie: 6.0.1
- type-fest: 5.5.0
- until-async: 3.0.2
- yargs: 17.7.2
- optionalDependencies:
- typescript: '@typescript/[email protected]'
- transitivePeerDependencies:
- - '@types/node'
- optional: true
-
dependencies:
'@inquirer/confirm': 5.1.5(@types/[email protected])
@@ -19107,7 +18934,8 @@ snapshots:
+ optional: true
@@ -20175,8 +20003,6 @@ snapshots:
-
optionalDependencies:
'@typescript/typescript-aix-ppc64': 7.0.2
@@ -20433,10 +20259,6 @@ snapshots:
kleur: 4.1.5
sade: 1.8.1
- optionalDependencies:
- typescript: 5.8.2
-
optionalDependencies:
typescript: 7.0.2
@@ -20573,48 +20395,6 @@ snapshots:
lightningcss: 1.31.1
tsx: 4.19.3
- dependencies:
- '@vitest/expect': 3.1.2
- '@vitest/pretty-format': 3.1.2
- '@vitest/runner': 3.1.2
- '@vitest/snapshot': 3.1.2
- '@vitest/spy': 3.1.2
- '@vitest/utils': 3.1.2
- chai: 5.2.0
- debug: 4.4.0
- expect-type: 1.2.1
- magic-string: 0.30.17
- pathe: 2.0.3
- std-env: 3.9.0
- tinybench: 2.9.0
- tinyexec: 0.3.2
- tinyglobby: 0.2.13
- tinypool: 1.0.2
- tinyrainbow: 2.0.0
- why-is-node-running: 2.3.0
- optionalDependencies:
- '@types/debug': 4.1.12
- '@types/node': 22.13.10
- jsdom: 20.0.3
- transitivePeerDependencies:
- - jiti
- - less
- - lightningcss
- - msw
- - sass
- - sass-embedded
- - stylus
- - sugarss
- - supports-color
- - terser
- - tsx
- - yaml
-
dependencies:
'@vitest/expect': 3.1.2