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 authoring, auditing, and verification (#5886)

Oleg Isonen12ad74584acb
diff --git a/.github/workflows/cli-release-smoke.yml b/.github/workflows/cli-release-smoke.yml
new file mode 100644
index 0000000000..189200854b
--- /dev/null
+++ b/.github/workflows/cli-release-smoke.yml
@@ -0,0 +1,52 @@
+name: CLI release smoke
+
+on:
+ workflow_dispatch:
+ schedule:
+ - cron: "30 4 * * 1"
+
+permissions:
+ contents: read
+
+jobs:
+ release-smoke:
+ timeout-minutes: 20
+ runs-on: ubuntu-24.04
+ environment:
+ name: development
+ env:
+ DATABASE_URL: postgres://
+ AUTH_SECRET: test
+ WEBSTUDIO_RELEASE_SMOKE_TOKEN_BUDGET: 6000
+ WEBSTUDIO_RELEASE_SMOKE_REPORT: ${{ github.workspace }}/artifacts/cli-release-smoke.json
+ WEBSTUDIO_RELEASE_SMOKE_AGENT_COMMAND: ${{ vars.CLI_RELEASE_SMOKE_AGENT_COMMAND }}
+ WEBSTUDIO_RELEASE_SMOKE_AGENT_REPORT: ${{ github.workspace }}/artifacts/cli-release-smoke-model.json
+ CLI_RELEASE_SMOKE_AGENT_API_KEY: ${{ secrets.CLI_RELEASE_SMOKE_AGENT_API_KEY }}
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: ./.github/actions/submodules-checkout
+ with:
+ submodules-ssh-key: ${{ secrets.PRIVATE_GITHUB_DEPLOY_TOKEN }}
+
+ - uses: ./.github/actions/ci-setup
+
+ - name: Run packaged CLI and agent onboarding smoke
+ run: pnpm --filter webstudio test:release-smoke
+
+ - name: Upload compact comparison report
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: cli-release-smoke-comparison
+ path: artifacts/cli-release-smoke.json
+ if-no-files-found: error
+
+ - name: Upload dual-package model evaluation report
+ if: ${{ always() && vars.CLI_RELEASE_SMOKE_AGENT_COMMAND != '' }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: cli-release-smoke-model-evaluation
+ path: artifacts/cli-release-smoke-model.json
+ if-no-files-found: error
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 51e4b56691..f729c752dd 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -81,6 +81,9 @@ jobs:
- id: version
run: echo "value=$(echo ${{ github.ref }} | sed 's/refs\/tags\///')" >> $GITHUB_OUTPUT
+ - id: registry-baseline
+ name: Resolve pre-publish CLI baseline
+ run: echo "value=$(npm view webstudio@latest version)" >> "$GITHUB_OUTPUT"
- name: bump version to ${{ steps.version.outputs.value }}
run: |
pnpx replace-in-files-cli \
@@ -101,3 +104,37 @@ jobs:
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- run: pnpm -r publish --access public --no-git-checks
+
+ - name: Wait for exact CLI registry artifact
+ env:
+ VERSION: ${{ steps.version.outputs.value }}
+ run: |
+ for attempt in $(seq 1 30); do
+ integrity=$(npm view "webstudio@$VERSION" dist.integrity --json 2>/dev/null || true)
+ if [ -n "$integrity" ] && [ "$integrity" != "null" ]; then
+ exit 0
+ fi
+ sleep 10
+ done
+ echo "Exact registry artifact webstudio@$VERSION was not observable with integrity metadata." >&2
+ exit 1
+
+ - name: Gate exact published CLI against baseline
+ id: registry-smoke
+ env:
+ DATABASE_URL: postgres://
+ AUTH_SECRET: test
+ WEBSTUDIO_RELEASE_SMOKE_TOKEN_BUDGET: 6000
+ WEBSTUDIO_RELEASE_SMOKE_CANDIDATE: webstudio@${{ steps.version.outputs.value }}
+ WEBSTUDIO_RELEASE_SMOKE_BASELINE: webstudio@${{ steps.registry-baseline.outputs.value }}
+ WEBSTUDIO_RELEASE_SMOKE_EXPECT_REGISTRY_VERSION: ${{ steps.version.outputs.value }}
+ WEBSTUDIO_RELEASE_SMOKE_REPORT: ${{ github.workspace }}/artifacts/cli-release-smoke.json
+ run: pnpm --filter webstudio test:release-smoke:registry
+
+ - name: Upload published CLI comparison report
+ if: ${{ always() && (steps.registry-smoke.outcome == 'success' || steps.registry-smoke.outcome == 'failure') }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: cli-release-smoke-${{ steps.version.outputs.value }}
+ path: artifacts/cli-release-smoke.json
+ if-no-files-found: error
diff --git a/apps/builder/app/builder/features/style-panel/shared/use-style-data.test.ts b/apps/builder/app/builder/features/style-panel/shared/use-style-data.test.ts
index a417c2bcf9..46417e6085 100644
--- a/apps/builder/app/builder/features/style-panel/shared/use-style-data.test.ts
+++ b/apps/builder/app/builder/features/style-panel/shared/use-style-data.test.ts
@@ -1,6 +1,6 @@
import { enableMapSet } from "immer";
import { describe, expect, test } from "vitest";
-import { registerContainers } from "~/shared/sync/sync-stores";
+import { registerContainers, serverSyncStore } from "~/shared/sync/sync-stores";
import {
$selectedBreakpointId,
$selectedStyleSources,
@@ -18,13 +18,20 @@ import {
$styles,
} from "~/shared/sync/data-stores";
import { $selectedPageId, selectInstance } from "~/shared/nano-states";
-import { deleteProperty, setProperty } from "./use-style-data";
+import {
+ createBatchUpdate,
+ deleteProperty,
+ setProperty,
+} from "./use-style-data";
import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";
enableMapSet();
registerContainers();
const setupBaseStores = () => {
+ serverSyncStore.transactionManager.currentStack = [];
+ serverSyncStore.transactionManager.undoneStack = [];
+ serverSyncStore.popAll();
const pages = createDefaultPages({ rootInstanceId: "body" });
$pages.set(pages);
$selectedPageId.set(pages.homePageId);
@@ -155,4 +162,29 @@ describe("use-style-data", () => {
},
]);
});
+
+ test("commits mixed batch updates in one undoable transaction", () => {
+ setupSelection({ id: "token1", type: "token", name: "Primary" });
+ const color: StyleDecl = {
+ breakpointId: "base",
+ styleSourceId: "token1",
+ property: "color",
+ value: { type: "keyword", value: "red" },
+ };
+ $styles.set(new Map([[getStyleDeclKey(color), color]]));
+
+ const batch = createBatchUpdate();
+ batch.deleteProperty("color");
+ batch.setProperty("display")({ type: "keyword", value: "grid" });
+ batch.publish();
+
+ expect(Array.from($styles.get().values())).toEqual([
+ expect.objectContaining({
+ property: "display",
+ value: { type: "keyword", value: "grid" },
+ }),
+ ]);
+ serverSyncStore.undo();
+ expect(Array.from($styles.get().values())).toEqual([color]);
+ });
});
diff --git a/apps/builder/app/builder/features/style-panel/shared/use-style-data.ts b/apps/builder/app/builder/features/style-panel/shared/use-style-data.ts
index e3c514e9b9..4a17a73ea6 100644
--- a/apps/builder/app/builder/features/style-panel/shared/use-style-data.ts
+++ b/apps/builder/app/builder/features/style-panel/shared/use-style-data.ts
@@ -8,7 +8,10 @@ import {
import { $ephemeralStyles } from "~/canvas/stores";
import { $selectedInstance } from "~/shared/nano-states";
import { isStyleSourceLocked } from "@webstudio-is/project-build/runtime";
-import { executeRuntimeMutation } from "~/shared/instance-utils/data";
+import {
+ executeRuntimeMutationSequence,
+ type RuntimeMutationOperation,
+} from "~/shared/instance-utils/data";
type StyleUpdate =
| {
@@ -98,6 +101,7 @@ const publishUpdates = (
(update) => update.operation === "delete"
);
+ const operations: RuntimeMutationOperation[] = [];
if (setUpdates.length > 0) {
const inputUpdates = setUpdates.map((update) => ({
instanceId,
@@ -107,7 +111,7 @@ const publishUpdates = (
value: update.value,
listed: options.listed,
}));
- executeRuntimeMutation({
+ operations.push({
id:
selectedStyleSource.type === "local"
? "styles.updateDeclarations"
@@ -131,7 +135,7 @@ const publishUpdates = (
state,
property: camelCaseProperty(update.property),
}));
- executeRuntimeMutation({
+ operations.push({
id:
selectedStyleSource.type === "local"
? "styles.deleteDeclarations"
@@ -147,6 +151,7 @@ const publishUpdates = (
},
});
}
+ executeRuntimeMutationSequence(operations);
};
export const setProperty: SetProperty = (property) => {
diff --git a/apps/builder/app/services/api-build.server.ts b/apps/builder/app/services/api-build.server.ts
index eab5a4ac52..8db974eda2 100644
--- a/apps/builder/app/services/api-build.server.ts
+++ b/apps/builder/app/services/api-build.server.ts
@@ -6,7 +6,10 @@ import {
loadBuildById,
loadDevBuildByProjectId,
} from "@webstudio-is/project-build/server";
-import { buildPatchTransaction } from "@webstudio-is/protocol/schema";
+import {
+ buildPatchTransaction,
+ publicBuildIncludes,
+} from "@webstudio-is/protocol/schema";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
import { serializePages } from "@webstudio-is/project-migrations/pages";
import { assertApiProjectPermit } from "./api-permits.server";
@@ -45,22 +48,7 @@ export const loadReadableDevBuild = async (
return await loadDevBuildByProjectId(ctx, projectId);
};
-const buildInclude = z.enum([
- "pages",
- "folders",
- "instances",
- "props",
- "styles",
- "styleSources",
- "styleSourceSelections",
- "designTokens",
- "assets",
- "resources",
- "variables",
- "breakpoints",
- "projectSettings",
- "marketplaceProduct",
-]);
+const buildInclude = z.enum(publicBuildIncludes);
export type BuildInclude = z.infer<typeof buildInclude>;
diff --git a/apps/builder/app/services/api-router.server.test.ts b/apps/builder/app/services/api-router.server.test.ts
index 3a1f05a9d8..c66b878e2b 100644
--- a/apps/builder/app/services/api-router.server.test.ts
+++ b/apps/builder/app/services/api-router.server.test.ts
@@ -760,7 +760,6 @@ describe("api instance queries", () => {
projectId: "project-1",
pagePath: "",
mode: "expression",
- maxValueLength: 6,
})
).resolves.toEqual({
texts: [
@@ -770,9 +769,16 @@ describe("api instance queries", () => {
component: blockComponent,
label: "Hero",
mode: "expression",
- value: "system",
+ valuePreview: "system.params.slug",
+ valueLength: 18,
+ truncated: false,
},
],
+ detail: "compact",
+ total: 1,
+ returnedCount: 1,
+ nextCursor: null,
+ filters: { pagePath: "", mode: "expression" },
});
});
@@ -840,7 +846,7 @@ describe("api instance queries", () => {
const caller = createCaller(createContext(true));
await expect(
- caller.pages.list({ projectId: "project-1", includeFolders: true })
+ caller.pages.list({ projectId: "project-1" })
).resolves.toMatchObject({
pages: [
expect.objectContaining({ isHome: true, path: "" }),
@@ -850,9 +856,6 @@ describe("api instance queries", () => {
parentFolderId: "folder-1",
}),
],
- folders: expect.arrayContaining([
- expect.objectContaining({ id: "folder-1", slug: "blog" }),
- ]),
});
await expect(
caller.pages.getByPath({
@@ -864,18 +867,16 @@ describe("api instance queries", () => {
meta: { description: "Post description" },
});
await expect(
- caller.folders.list({ projectId: "project-1", includePages: true })
+ caller.folders.list({ projectId: "project-1" })
).resolves.toMatchObject({
folders: expect.arrayContaining([
expect.objectContaining({
id: "folder-1",
+ slug: "blog",
parentFolderId: build.pages.rootFolderId,
children: ["page-1"],
}),
]),
- pages: expect.arrayContaining([
- expect.objectContaining({ id: "page-1" }),
- ]),
});
await expect(
caller.designTokens.list({
@@ -905,9 +906,14 @@ describe("api instance queries", () => {
id: "variable-1",
name: "Title",
scopeInstanceId: "hero-1",
- value: { type: "string", value: "Hello" },
+ valueType: "string",
},
],
+ detail: "compact",
+ total: 1,
+ returnedCount: 1,
+ nextCursor: null,
+ filters: { scopeInstanceId: "hero-1" },
});
await expect(
caller.resources.list({
@@ -926,6 +932,11 @@ describe("api instance queries", () => {
dataSourceId: "resource-data-source-1",
},
],
+ detail: "compact",
+ total: 1,
+ returnedCount: 1,
+ nextCursor: null,
+ filters: { scopeInstanceId: "hero-1" },
});
});
});
diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.ts
index 880722e977..97cfed4bc2 100644
--- a/apps/builder/app/services/api-router.server.ts
+++ b/apps/builder/app/services/api-router.server.ts
@@ -22,7 +22,11 @@ import {
unpublishProjectDomains,
verifyProjectDomain,
} from "@webstudio-is/domain/index.server";
-import { getBuilderRuntimeOperationInputSchema } from "@webstudio-is/project-build/runtime";
+import {
+ getBuilderRuntimeOperationInputSchema,
+ paginateOutput,
+ paginatedOutputInputSchema,
+} from "@webstudio-is/project-build/runtime";
import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";
import { buildPatchTransaction } from "@webstudio-is/protocol/schema";
import {
@@ -93,6 +97,22 @@ const assertApiPublishDomains = ({
const projectIdInput = z.object({ projectId: z.string() });
+const paginatedProjectInput = projectIdInput.extend(
+ paginatedOutputInputSchema.shape
+);
+
+const paginateProjectItems = <Item>(
+ items: readonly Item[],
+ input: z.infer<typeof paginatedProjectInput>
+) =>
+ paginateOutput({
+ items,
+ cursor: input.cursor,
+ limit: input.limit,
+ verbose: input.verbose,
+ filters: {},
+ });
+
const withProjectId = <Schema extends z.ZodTypeAny>(
input: Schema
): z.ZodType<z.infer<Schema> & { projectId: string }> =>
@@ -646,10 +666,12 @@ export const apiRouter = router({
publish: router({
list: projectQuery(
- projectIdInput,
+ paginatedProjectInput,
"view",
async ({ ctx, input }) => {
- return await listProjectPublishes(input.projectId, ctx);
+ const { publishes } = await listProjectPublishes(input.projectId, ctx);
+ const { items, ...pagination } = paginateProjectItems(publishes, input);
+ return { publishes: items, ...pagination };
},
{ command: "list-publishes", client: "listPublishes" }
),
@@ -720,10 +742,14 @@ export const apiRouter = router({
domains: router({
list: projectQuery(
- projectIdInput,
+ paginatedProjectInput,
"view",
async ({ ctx, input }) => {
- return { domains: await listProjectDomains(input.projectId, ctx) };
+ const { items, ...pagination } = paginateProjectItems(
+ await listProjectDomains(input.projectId, ctx),
+ input
+ );
+ return { domains: items, ...pagination };
},
{ command: "list-domains", client: "listDomains" }
),
diff --git a/apps/builder/app/services/api-runtime.server.test.ts b/apps/builder/app/services/api-runtime.server.test.ts
index 4f2c1bd527..5e1e043f75 100644
--- a/apps/builder/app/services/api-runtime.server.test.ts
+++ b/apps/builder/app/services/api-runtime.server.test.ts
@@ -3,6 +3,7 @@ import { TRPCError } from "@trpc/server";
import { createDefaultPages } from "@webstudio-is/project-build";
import type { CompactBuild } from "@webstudio-is/project-build";
import { createEmptyWebstudioFragment } from "@webstudio-is/project-build/runtime";
+import { executeBuilderRuntimeOperation } from "@webstudio-is/project-build/runtime";
import type { Asset } from "@webstudio-is/sdk";
import {
createBuilderRuntimeState,
@@ -69,6 +70,30 @@ describe("api runtime adapter", () => {
).rejects.toThrow("Page not found");
});
+ test("preserves canonical mutation payloads across the API adapter", async () => {
+ const build = createBuild();
+ const pageId = build.pages.homePageId;
+ const input = {
+ projectId: build.projectId,
+ pageId,
+ values: { name: "Updated home" },
+ };
+ const direct = executeBuilderRuntimeOperation({
+ id: "pages.update",
+ state: createBuilderRuntimeState(build),
+ input,
+ context: {
+ createId: () => "unused",
+ projectId: build.projectId,
+ projectVersion: build.version,
+ },
+ });
+
+ await expect(
+ executeApiRuntimeOperation({ id: "pages.update", build, input })
+ ).resolves.toEqual(direct);
+ });
+
test("strips API transport fields before strict runtime validation", async () => {
await expect(
executeApiRuntimeOperation({
diff --git a/apps/builder/app/shared/instance-utils/data.test.tsx b/apps/builder/app/shared/instance-utils/data.test.tsx
index 87948e86d9..aed425ada2 100644
--- a/apps/builder/app/shared/instance-utils/data.test.tsx
+++ b/apps/builder/app/shared/instance-utils/data.test.tsx
@@ -1,4 +1,4 @@
-import { describe, expect, test } from "vitest";
+import { describe, expect, expectTypeOf, test } from "vitest";
import type { Asset, Instance, PageTemplate } from "@webstudio-is/sdk";
import { createDefaultPages } from "@webstudio-is/project-build";
import { findCycles } from "@webstudio-is/project-build/runtime";
@@ -6,8 +6,10 @@ import type { BuilderRuntimeOperationInput } from "@webstudio-is/project-build/r
import {
executeRuntimeMutation,
executeRuntimeMutationAsync,
+ executeRuntimeMutationSequence,
getWebstudioData,
migrateLoadedWebstudioData,
+ type RuntimeMutationOperation,
} from "./data";
import { registerContainers, serverSyncStore } from "../sync/sync-stores";
import {
@@ -36,6 +38,15 @@ const createInstance = (
registerContainers();
+test("accepts only mutation operation ids in the Builder commit helpers", () => {
+ expectTypeOf<
+ Extract<RuntimeMutationOperation, { id: "pages.create" }>
+ >().not.toBeNever();
+ expectTypeOf<
+ Extract<RuntimeMutationOperation, { id: "pages.list" }>
+ >().toBeNever();
+});
+
const setBaseStores = () => {
serverSyncStore.transactionManager.currentStack = [];
serverSyncStore.transactionManager.undoneStack = [];
@@ -166,6 +177,45 @@ describe("data store helpers", () => {
]);
});
+ test("commits a runtime mutation sequence as one undoable transaction", () => {
+ setBaseStores();
+
+ executeRuntimeMutationSequence([
+ {
+ id: "instances.updateProps",
+ input: {
+ updates: [
+ {
+ instanceId: "body",
+ name: "id",
+ type: "string",
+ value: "main",
+ },
+ ],
+ },
+ },
+ {
+ id: "instances.updateProps",
+ input: {
+ updates: [
+ {
+ instanceId: "body",
+ name: "title",
+ type: "string",
+ value: "Main content",
+ },
+ ],
+ },
+ },
+ ]);
+
+ expect(Array.from($props.get().values())).toHaveLength(2);
+ serverSyncStore.undo();
+ expect($props.get()).toEqual(new Map());
+ serverSyncStore.redo();
+ expect(Array.from($props.get().values())).toHaveLength(2);
+ });
+
test("runtime bridge keeps sync changes scoped to changed namespaces", () => {
setBaseStores();
serverSyncStore.popAll();
diff --git a/apps/builder/app/shared/instance-utils/data.ts b/apps/builder/app/shared/instance-utils/data.ts
index e4f224e799..ae1b3a467c 100644
--- a/apps/builder/app/shared/instance-utils/data.ts
+++ b/apps/builder/app/shared/instance-utils/data.ts
@@ -5,8 +5,9 @@ import { toast } from "@webstudio-is/design-system";
import { type WebstudioData, isPageTemplate } from "@webstudio-is/sdk";
import {
executeBuilderRuntimeOperation,
+ createRuntimeMutationAccumulator,
type BuilderRuntimeOperationInput,
- type BuilderRuntimeOperationId,
+ type BuilderRuntimeMutationOperationId,
type BuilderRuntimeOperationResult,
} from "@webstudio-is/project-build/runtime";
import { builderRuntimeContext } from "@webstudio-is/project-build/runtime";
@@ -29,10 +30,15 @@ import {
$styleSources,
} from "../sync/data-stores";
-type RuntimeMutationResult<Id extends BuilderRuntimeOperationId> = Extract<
- BuilderRuntimeOperationResult<Id>,
- BuilderRuntimeMutation
->;
+type RuntimeMutationResult<Id extends BuilderRuntimeMutationOperationId> =
+ Extract<BuilderRuntimeOperationResult<Id>, BuilderRuntimeMutation>;
+
+export type RuntimeMutationOperation = {
+ [Id in BuilderRuntimeMutationOperationId]: {
+ id: Id;
+ input: BuilderRuntimeOperationInput<Id>;
+ };
+}[BuilderRuntimeMutationOperationId];
export type WebstudioInstanceData = Pick<
WebstudioData,
@@ -63,7 +69,24 @@ export const migrateLoadedWebstudioData = () => {
}
};
-const createRuntimeMutationArgs = <Id extends BuilderRuntimeOperationId>({
+const getRuntimeMutationContext = () => ({
+ createId: builderRuntimeContext.createId,
+ projectId: $project.get()?.id,
+});
+
+const requireSynchronousResult = <Result>(
+ id: BuilderRuntimeMutationOperationId,
+ result: Result | Promise<Result>
+): Result => {
+ if (result instanceof Promise) {
+ throw Error(`Builder runtime operation "${id}" must be synchronous.`);
+ }
+ return result;
+};
+
+const createRuntimeMutationArgs = <
+ Id extends BuilderRuntimeMutationOperationId,
+>({
id,
input,
}: {
@@ -73,10 +96,7 @@ const createRuntimeMutationArgs = <Id extends BuilderRuntimeOperationId>({
id,
state: getWebstudioData(),
input,
- context: {
- createId: builderRuntimeContext.createId,
- projectId: $project.get()?.id,
- },
+ context: getRuntimeMutationContext(),
});
const commitRuntimeMutation = <Mutation extends BuilderRuntimeMutation>(
@@ -89,7 +109,9 @@ const commitRuntimeMutation = <Mutation extends BuilderRuntimeMutation>(
return result;
};
-export const executeRuntimeMutation = <Id extends BuilderRuntimeOperationId>({
+export const executeRuntimeMutation = <
+ Id extends BuilderRuntimeMutationOperationId,
+>({
id,
input,
}: {
@@ -99,17 +121,41 @@ export const executeRuntimeMutation = <Id extends BuilderRuntimeOperationId>({
if (canCommitWebstudioData() === false) {
return;
}
- const operationResult = executeBuilderRuntimeOperation<
- RuntimeMutationResult<Id>
- >(createRuntimeMutationArgs({ id, input }));
- if (operationResult instanceof Promise) {
- throw Error(`Builder runtime operation "${id}" must be synchronous.`);
+ return commitRuntimeMutation(
+ requireSynchronousResult(
+ id,
+ executeBuilderRuntimeOperation<RuntimeMutationResult<Id>>(
+ createRuntimeMutationArgs({ id, input })
+ )
+ )
+ );
+};
+
+export const executeRuntimeMutationSequence = (
+ operations: readonly RuntimeMutationOperation[]
+): void => {
+ if (canCommitWebstudioData() === false) {
+ return;
}
- return commitRuntimeMutation(operationResult);
+ const accumulator = createRuntimeMutationAccumulator(getWebstudioData());
+ const results = operations.map(({ id, input }) => {
+ return accumulator.stage(
+ requireSynchronousResult(
+ id,
+ executeBuilderRuntimeOperation<BuilderRuntimeMutation>({
+ id,
+ state: accumulator.state,
+ input,
+ context: getRuntimeMutationContext(),
+ })
+ )
+ );
+ });
+ commitRuntimeMutation(accumulator.complete({ results }));
};
export const executeRuntimeMutationAsync = async <
- Id extends BuilderRuntimeOperationId,
+ Id extends BuilderRuntimeMutationOperationId,
>({
id,
input,
diff --git a/apps/builder/app/shared/project-settings/section-connect-agent.tsx b/apps/builder/app/shared/project-settings/section-connect-agent.tsx
index 83a09e87ef..f49349356a 100644
--- a/apps/builder/app/shared/project-settings/section-connect-agent.tsx
+++ b/apps/builder/app/shared/project-settings/section-connect-agent.tsx
@@ -9,27 +9,16 @@ import {
} from "@webstudio-is/design-system";
import { CopyIcon } from "@webstudio-is/icons";
import {
- agentClients,
- createAgentClientConfiguration,
+ agentClientDefinitions,
+ createAgentQuickstart,
createAgentShareUrl,
- createAgentSetupCommand,
type AgentClient,
+ type AgentClientDefinition,
} from "@webstudio-is/protocol";
import { CopyToClipboard } from "~/shared/copy-to-clipboard";
import { $authToken } from "~/shared/nano-states";
import { sectionSpacing } from "./utils";
-const clientLabels: Record<AgentClient, string> = {
- claude: "Claude Code",
- codex: "Codex",
- cursor: "Cursor",
- vscode: "VS Code",
-};
-const clientOptions = agentClients.map((value) => ({
- value,
- label: clientLabels[value],
-}));
-
export const SectionConnectAgent = () => {
const authToken = useStore($authToken);
const [client, setClient] = useState<AgentClient>("claude");
@@ -48,21 +37,22 @@ export const SectionConnectAgent = () => {
);
}, [authToken]);
- const configuration = createAgentClientConfiguration(client);
- const setupCommand =
- shareUrl === undefined
- ? undefined
- : createAgentSetupCommand({ client, shareUrl });
+ const { configuration, setupCommand, completion } = createAgentQuickstart({
+ client,
+ shareUrl,
+ });
return (
<Grid gap={3} css={sectionSpacing}>
<Text variant="titles">Connect your Agent</Text>
<Select
- options={clientOptions}
- value={clientOptions.find(({ value }) => value === client)}
- getValue={({ value }) => value}
- getLabel={({ label }) => label}
- onChange={(option) => setClient(option.value)}
+ options={agentClientDefinitions}
+ value={agentClientDefinitions.find(
+ (option) => option.client === client
+ )}
+ getValue={({ client }: AgentClientDefinition) => client}
+ getLabel={({ label }: AgentClientDefinition) => label}
+ onChange={(option) => setClient(option.client)}
/>
{setupCommand === undefined ? (
<Text color="subtle">
@@ -88,7 +78,8 @@ export const SectionConnectAgent = () => {
readOnly
value={configuration.content}
/>
- <Text color="subtle">{configuration.hint}</Text>
+ <Text color="subtle">{completion.connection}</Text>
+ <Text color="subtle">{completion.firstRead}</Text>
</Grid>
</Grid>
);
diff --git a/packages/cli/evaluations/high-impact/agent-runner.test.ts b/packages/cli/evaluations/high-impact/agent-runner.test.ts
new file mode 100644
index 0000000000..301abd8488
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/agent-runner.test.ts
@@ -0,0 +1,86 @@
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { describe, expect, test } from "vitest";
+import { authenticatedPageFixture } from "./fixtures";
+import { designInputFixture } from "./fixtures";
+import {
+ createMinimalAgentTask,
+ getCliInvocation,
+ runHighImpactAgentEvaluation,
+} from "./agent-runner";
+
+describe("high-impact agent runner", () => {
+ test("points source evaluations at the local CLI", () => {
+ const root = resolve(import.meta.dirname, "../../../..");
+ expect(getCliInvocation({ kind: "source", repositoryRoot: root })).toEqual({
+ command: process.execPath,
+ args: [resolve(root, "packages/cli/local.js"), "mcp"],
+ });
+ const task = createMinimalAgentTask(authenticatedPageFixture, {
+ kind: "source",
+ repositoryRoot: root,
+ });
+ expect(task).not.toHaveProperty("project");
+ expect(task).toMatchObject({
+ constraints: [
+ expect.any(String),
+ expect.stringContaining("meta.guide"),
+ expect.any(String),
+ expect.any(String),
+ expect.stringContaining("meta.next"),
+ ],
+ });
+ expect(
+ createMinimalAgentTask(designInputFixture, {
+ kind: "source",
+ repositoryRoot: root,
+ })
+ ).toMatchObject({
+ designReference: {
+ desktop: { viewport: { width: 1440, height: 900 } },
+ mobile: { viewport: { width: 390, height: 844 } },
+ },
+ });
+ });
+
+ test("retains only a bounded privacy-safe result from a real process", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "high-impact-agent-"));
+ try {
+ const resultPath = join(directory, "result.json");
+ const taskPath = join(directory, "task.json");
+ const result = await runHighImpactAgentEvaluation({
+ fixture: authenticatedPageFixture,
+ target: { kind: "packaged", executable: "/tmp/webstudio" },
+ agentCommand: "node -e 'process.exit(0)'",
+ cwd: directory,
+ taskPath,
+ resultPath,
+ provider: "test-provider",
+ model: "test-model",
+ getCallSequence: () => ["meta.guide", "audit"],
+ evaluate: async () => ({
+ passed: true,
+ checks: { privacy: "passed", audit: "passed" },
+ failures: [],
+ metrics: { toolCallCount: 6, focusedReadCount: 2 },
+ }),
+ });
+ expect(result).toMatchObject({
+ outcome: "passed",
+ cli: "packaged",
+ toolCallCount: 6,
+ focusedReadCount: 2,
+ callSequence: ["meta.guide", "audit"],
+ });
+ const source = await readFile(resultPath, "utf8");
+ expect(source).not.toMatch(/transcript|stdout|stderr|credential/i);
+ expect(JSON.parse(await readFile(taskPath, "utf8"))).toMatchObject({
+ fixtureId: "authenticated-page-v1",
+ mcp: { args: ["mcp"] },
+ });
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/cli/evaluations/high-impact/agent-runner.ts b/packages/cli/evaluations/high-impact/agent-runner.ts
new file mode 100644
index 0000000000..ebd6543eef
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/agent-runner.ts
@@ -0,0 +1,153 @@
+import { createHash } from "node:crypto";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { dirname, resolve } from "node:path";
+import type { HighImpactFixture } from "./fixtures";
+import type { HighImpactEvaluationResult } from "./validate";
+import { runAgentCommand } from "../../scripts/run-agent-command";
+import { boundedIdentifierPattern } from "../../src/type-utils";
+
+export type AgentCliTarget =
+ | { kind: "source"; repositoryRoot: string }
+ | { kind: "packaged"; executable: string };
+
+export type AgentEvaluationResult = {
+ schemaVersion: 1;
+ kind: "high-impact-minimal-context-agent-evaluation-result";
+ fixtureId: HighImpactFixture["id"];
+ outcome: "passed" | "failed";
+ cli: "source" | "packaged";
+ provider: string;
+ model: string;
+ commandSha256: string;
+ durationMs: number;
+ exitCode: number;
+ toolCallCount: number;
+ focusedReadCount: number;
+ callSequence: string[];
+ checks: Record<string, "passed" | "failed">;
+};
+
+const forbiddenResultKeys =
+ /(?:prompt|transcript|stdout|stderr|token|secret|credential|payload)/i;
+
+export const getCliInvocation = (target: AgentCliTarget) =>
+ target.kind === "source"
+ ? {
+ command: process.execPath,
+ args: [resolve(target.repositoryRoot, "packages/cli/local.js"), "mcp"],
+ }
+ : { command: resolve(target.executable), args: ["mcp"] };
+
+export const createMinimalAgentTask = (
+ fixture: HighImpactFixture,
+ target: AgentCliTarget
+) => {
+ const designReference =
+ "designReference" in fixture
+ ? (fixture as HighImpactFixture & { designReference: unknown })
+ .designReference
+ : undefined;
+ return {
+ schemaVersion: 1,
+ fixtureId: fixture.id,
+ objective: fixture.objective,
+ ...(designReference === undefined ? {} : { designReference }),
+ mcp: getCliInvocation(target),
+ constraints: [
+ "Use the configured Webstudio project and local CLI.",
+ "Begin with meta.guide for the objective and follow its workflow.",
+ "Choose focused reads and semantic edits yourself.",
+ "Do not persist or report credentials or private session data.",
+ "Treat mutation meta.next steps as required. Do not report completion until audit and requested visual evidence pass.",
+ ],
+ };
+};
+
+const assertBoundedResult = (result: AgentEvaluationResult) => {
+ if (
+ boundedIdentifierPattern.test(result.provider) === false ||
+ boundedIdentifierPattern.test(result.model) === false
+ ) {
+ throw new Error("Agent provider and model must be bounded identifiers.");
+ }
+ const visit = (value: unknown): void => {
+ if (typeof value !== "object" || value === null) {
+ return;
+ }
+ for (const [key, child] of Object.entries(value)) {
+ if (forbiddenResultKeys.test(key)) {
+ throw new Error(`Agent result contains forbidden field ${key}.`);
+ }
+ visit(child);
+ }
+ };
+ visit(result);
+ if (JSON.stringify(result).length > 12_000) {
+ throw new Error("Agent result exceeds the bounded artifact limit.");
+ }
+};
+
+export const runHighImpactAgentEvaluation = async ({
+ fixture,
+ target,
+ agentCommand,
+ cwd,
+ taskPath,
+ resultPath,
+ provider,
+ model,
+ getCallSequence,
+ evaluate,
+ env = process.env,
+ timeoutMs = 10 * 60_000,
+}: {
+ fixture: HighImpactFixture;
+ target: AgentCliTarget;
+ agentCommand: string;
+ cwd: string;
+ taskPath: string;
+ resultPath: string;
+ provider: string;
+ model: string;
+ getCallSequence: () => string[];
+ evaluate: () => Promise<HighImpactEvaluationResult>;
+ env?: NodeJS.ProcessEnv;
+ timeoutMs?: number;
+}) => {
+ await mkdir(dirname(taskPath), { recursive: true });
+ await writeFile(
+ taskPath,
+ JSON.stringify(createMinimalAgentTask(fixture, target), undefined, 2),
+ "utf8"
+ );
+ const execution = await runAgentCommand({
+ command: agentCommand,
+ cwd,
+ env: { ...env, WEBSTUDIO_HIGH_IMPACT_AGENT_TASK: taskPath },
+ timeoutMs,
+ });
+ const evaluation = await evaluate();
+ const result: AgentEvaluationResult = {
+ schemaVersion: 1,
+ kind: "high-impact-minimal-context-agent-evaluation-result",
+ fixtureId: fixture.id,
+ outcome:
+ execution.exitCode === 0 && evaluation.passed ? "passed" : "failed",
+ cli: target.kind,
+ provider,
+ model,
+ commandSha256: createHash("sha256").update(agentCommand).digest("hex"),
+ durationMs: execution.durationMs,
+ exitCode: execution.exitCode,
+ toolCallCount: evaluation.metrics.toolCallCount,
+ focusedReadCount: evaluation.metrics.focusedReadCount,
+ callSequence: getCallSequence(),
+ checks: evaluation.checks,
+ };
+ assertBoundedResult(result);
+ await mkdir(dirname(resultPath), { recursive: true });
+ await writeFile(resultPath, JSON.stringify(result, undefined, 2), "utf8");
+ return JSON.parse(
+ await readFile(resultPath, "utf8")
+ ) as AgentEvaluationResult;
+};
diff --git a/packages/cli/evaluations/high-impact/artifacts.test.ts b/packages/cli/evaluations/high-impact/artifacts.test.ts
new file mode 100644
index 0000000000..282fa4dd41
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/artifacts.test.ts
@@ -0,0 +1,53 @@
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { expect, test } from "vitest";
+import { collectHighImpactArtifacts } from "./artifacts";
+
+test("collects bounded screenshot and rendered-audit evidence", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "high-impact-artifacts-"));
+ try {
+ const screenshots = join(directory, "screenshots");
+ const audits = join(directory, ".webstudio", "audits");
+ await Promise.all([
+ mkdir(screenshots, { recursive: true }),
+ mkdir(audits, { recursive: true }),
+ ]);
+ const png = Buffer.alloc(24);
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(png);
+ png.writeUInt32BE(1440, 16);
+ png.writeUInt32BE(900, 20);
+ await Promise.all([
+ writeFile(join(screenshots, "desktop.png"), png),
+ writeFile(
+ join(audits, "rendered-project-1.json"),
+ JSON.stringify({ checks: [{}], failures: [] })
+ ),
+ writeFile(
+ join(audits, "rendered-project-2.json"),
+ JSON.stringify({ checks: [], failures: [{ code: "FAILED" }] })
+ ),
+ ]);
+
+ expect(await collectHighImpactArtifacts(directory)).toEqual([
+ {
+ kind: "screenshot",
+ path: "screenshots/desktop.png",
+ viewport: { width: 1440, height: 900 },
+ passed: true,
+ },
+ {
+ kind: "audit",
+ path: ".webstudio/audits/rendered-project-1.json",
+ passed: true,
+ },
+ {
+ kind: "audit",
+ path: ".webstudio/audits/rendered-project-2.json",
+ passed: false,
+ },
+ ]);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
diff --git a/packages/cli/evaluations/high-impact/artifacts.ts b/packages/cli/evaluations/high-impact/artifacts.ts
new file mode 100644
index 0000000000..4ba5d8d014
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/artifacts.ts
@@ -0,0 +1,91 @@
+import { readFile, readdir } from "node:fs/promises";
+import { join, relative } from "node:path";
+import type { EvaluationArtifact } from "./validate";
+
+const byName = (left: { name: string }, right: { name: string }) =>
+ left.name.localeCompare(right.name);
+
+const collectScreenshots = async (directory: string) => {
+ const artifacts: EvaluationArtifact[] = [];
+ const visit = async (path: string) => {
+ for (const entry of (await readdir(path, { withFileTypes: true })).sort(
+ byName
+ )) {
+ if (entry.name === ".webstudio") {
+ continue;
+ }
+ const entryPath = join(path, entry.name);
+ if (entry.isDirectory()) {
+ await visit(entryPath);
+ continue;
+ }
+ if (entry.name.endsWith(".png") === false) {
+ continue;
+ }
+ const source = await readFile(entryPath);
+ if (
+ source.length >= 24 &&
+ source
+ .subarray(0, 8)
+ .equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
+ ) {
+ artifacts.push({
+ kind: "screenshot",
+ path: relative(directory, entryPath),
+ viewport: {
+ width: source.readUInt32BE(16),
+ height: source.readUInt32BE(20),
+ },
+ passed: true,
+ });
+ }
+ }
+ };
+ await visit(directory);
+ return artifacts;
+};
+
+const collectRenderedAudits = async (directory: string) => {
+ const auditDirectory = join(directory, ".webstudio", "audits");
+ const entries = await readdir(auditDirectory, { withFileTypes: true }).catch(
+ () => []
+ );
+ return await Promise.all(
+ entries
+ .filter(
+ (entry) =>
+ entry.isFile() &&
+ entry.name.startsWith("rendered-") &&
+ entry.name.endsWith(".json")
+ )
+ .sort(byName)
+ .map(async (entry): Promise<EvaluationArtifact> => {
+ const path = join(auditDirectory, entry.name);
+ let manifest: unknown;
+ try {
+ manifest = JSON.parse(await readFile(path, "utf8"));
+ } catch {
+ return {
+ kind: "audit",
+ path: relative(directory, path),
+ passed: false,
+ };
+ }
+ const value = manifest as { checks?: unknown; failures?: unknown };
+ return {
+ kind: "audit",
+ path: relative(directory, path),
+ passed:
+ Array.isArray(value.checks) &&
+ value.checks.length > 0 &&
+ Array.isArray(value.failures) &&
+ value.failures.length === 0,
+ };
+ })
+ );
+};
+
+export const collectHighImpactArtifacts = async (directory: string) => [
+ ...(await collectScreenshots(directory)),
+ ...(await collectRenderedAudits(directory)),
+];
diff --git a/packages/cli/evaluations/high-impact/binding-verification-agent.test.ts b/packages/cli/evaluations/high-impact/binding-verification-agent.test.ts
new file mode 100644
index 0000000000..8b7a5d99c6
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/binding-verification-agent.test.ts
@@ -0,0 +1,95 @@
+import { execFile } from "node:child_process";
+import { mkdir, mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { promisify } from "node:util";
+import { afterEach, expect, test } from "vitest";
+import { authenticatedPageFixture } from "./fixtures";
+import { startHighImpactFixtureApi } from "./fixture-api";
+
+const execFileAsync = promisify(execFile);
+const temporaryDirectories: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ temporaryDirectories
+ .splice(0)
+ .map((directory) => rm(directory, { recursive: true, force: true }))
+ );
+});
+
+test("runs verify-bindings through the local CLI with minimal MCP context", async () => {
+ const repositoryRoot = resolve(import.meta.dirname, "../../../..");
+ const directory = await mkdtemp(join(tmpdir(), "webstudio-binding-agent-"));
+ temporaryDirectories.push(directory);
+ const projectRoot = join(directory, "project");
+ const configDirectory = join(directory, "config");
+ const fixtureApi = await startHighImpactFixtureApi(authenticatedPageFixture);
+ const env = { ...process.env, WEBSTUDIO_CONFIG_DIR: configDirectory };
+
+ try {
+ await mkdir(projectRoot, { recursive: true });
+ const localCli = resolve(repositoryRoot, "packages/cli/local.js");
+ await execFileAsync(
+ process.execPath,
+ [localCli, "init", "--link", fixtureApi.shareLink, "--json"],
+ { cwd: projectRoot, env }
+ );
+
+ const runVerifyBindings = async (refresh = false) => {
+ if (refresh) {
+ await execFileAsync(
+ process.execPath,
+ [localCli, "mcp", "single-op-call", "refresh", "{}", "--json"],
+ { cwd: projectRoot, env }
+ );
+ }
+ const args = [
+ localCli,
+ "mcp",
+ "single-op-call",
+ "verify-bindings",
+ '{"pagePath":"/"}',
+ "--json",
+ ];
+ const result = await execFileAsync(process.execPath, args, {
+ cwd: projectRoot,
+ env,
+ });
+ return JSON.parse(result.stdout) as {
+ ok: boolean;
+ data: {
+ analysis: {
+ staticIntegrity: string;
+ renderedResolution: string;
+ externalResourcesExecuted: boolean;
+ };
+ findings: unknown[];
+ };
+ };
+ };
+
+ const first = await runVerifyBindings();
+ await execFileAsync(process.execPath, [localCli, "sync"], {
+ cwd: projectRoot,
+ env,
+ });
+ const refreshed = await runVerifyBindings(true);
+
+ expect(first).toMatchObject({
+ ok: true,
+ data: {
+ analysis: {
+ staticIntegrity: "complete",
+ renderedResolution: "not-evaluated",
+ externalResourcesExecuted: false,
+ },
+ findings: [],
+ },
+ });
+ expect(refreshed).toEqual(first);
+ expect(fixtureApi.getToolCalls()).toEqual([]);
+ } finally {
+ await fixtureApi.close();
+ }
+}, 120_000);
diff --git a/packages/cli/evaluations/high-impact/fixture-api.test.ts b/packages/cli/evaluations/high-impact/fixture-api.test.ts
new file mode 100644
index 0000000000..1e68ef2ca9
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/fixture-api.test.ts
@@ -0,0 +1,54 @@
+import { execFile } from "node:child_process";
+import { mkdir, mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { promisify } from "node:util";
+import { describe, expect, test } from "vitest";
+import { authenticatedPageFixture } from "./fixtures";
+import { startHighImpactFixtureApi } from "./fixture-api";
+
+const execFileAsync = promisify(execFile);
+
+describe("high-impact fixture API", () => {
+ test("links and reads through the source CLI without persisting credentials", async () => {
+ const fixtureApi = await startHighImpactFixtureApi(
+ authenticatedPageFixture
+ );
+ const directory = await mkdtemp(join(tmpdir(), "high-impact-fixture-api-"));
+ const configDirectory = join(directory, "config");
+ const projectDirectory = join(directory, "project");
+ const cli = resolve(import.meta.dirname, "../../local.js");
+ await mkdir(projectDirectory, { recursive: true });
+ const env = { ...process.env, WEBSTUDIO_CONFIG_DIR: configDirectory };
+ try {
+ const initialized = await execFileAsync(
+ process.execPath,
+ [cli, "init", "--link", fixtureApi.shareLink, "--json"],
+ { cwd: projectDirectory, env }
+ );
+ expect(JSON.parse(initialized.stdout)).toMatchObject({
+ ok: true,
+ data: { projectId: "high-impact-evaluation-project" },
+ });
+
+ const listed = await execFileAsync(
+ process.execPath,
+ [cli, "list-pages", "{}"],
+ { cwd: projectDirectory, env }
+ );
+ expect(JSON.parse(listed.stdout)).toMatchObject({
+ ok: true,
+ data: { pages: [expect.objectContaining({ name: "Home" })] },
+ meta: {
+ session: { buildId: "high-impact-evaluation-build" },
+ },
+ });
+ expect(JSON.stringify(fixtureApi.getProject())).not.toContain(
+ "fixture-only-not-persisted"
+ );
+ } finally {
+ await fixtureApi.close();
+ await rm(directory, { recursive: true, force: true });
+ }
+ }, 15_000);
+});
diff --git a/packages/cli/evaluations/high-impact/fixture-api.ts b/packages/cli/evaluations/high-impact/fixture-api.ts
new file mode 100644
index 0000000000..0297a4f1a4
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/fixture-api.ts
@@ -0,0 +1,229 @@
+import type { Server } from "node:http";
+import { migratePages } from "@webstudio-is/project-migrations/pages";
+import React from "react";
+import type { BuilderState } from "@webstudio-is/project-build/state";
+import { createBuilderStateFreshness } from "@webstudio-is/project-build/state";
+import type { BuilderRuntimeMutation } from "@webstudio-is/project-build/runtime";
+import type { BuilderPatchTransaction } from "@webstudio-is/project-build/contracts";
+import type { HighImpactFixture, EvaluationProject } from "./fixtures";
+import type { EvaluationToolCall } from "./validate";
+import {
+ createRuntimeFixtureBuildSnapshot,
+ publicApiCommandByOperationId,
+ runtimeFixturePermissions,
+ startRuntimeFixtureApi,
+} from "../../scripts/runtime-fixture-api";
+
+const projectId = "high-impact-evaluation-project";
+const buildId = "high-impact-evaluation-build";
+const initialVersion = 1;
+
+const createPersistedPages = (project: EvaluationProject) => ({
+ meta: { siteName: "High-impact evaluation", contactEmail: "" },
+ compiler: { atomicStyles: true },
+ redirects: [],
+ homePageId: "home",
+ rootFolderId: "root-folder",
+ pages: project.pages.map((page) => ({
+ ...page,
+ title: page.name,
+ meta: {},
+ })),
+ folders: [
+ {
+ id: "root-folder",
+ name: "Root",
+ slug: "",
+ children: project.pages.map((page) => page.id),
+ },
+ ],
+});
+
+const stateToProject = (state: BuilderState): EvaluationProject => ({
+ pages: Array.from(state.pages?.pages.values() ?? []).map((page) => ({
+ id: page.id,
+ name: page.name,
+ path: page.path,
+ rootInstanceId: page.rootInstanceId,
+ })),
+ instances: Array.from(
+ state.instances?.values() ?? []
+ ) as EvaluationProject["instances"],
+ props: Array.from(state.props?.values() ?? []) as EvaluationProject["props"],
+ dataSources: Array.from(state.dataSources?.values() ?? []) as Array<
+ Record<string, unknown>
+ >,
+ resources: Array.from(state.resources?.values() ?? []) as Array<
+ Record<string, unknown>
+ >,
+ breakpoints: Array.from(state.breakpoints?.values() ?? []),
+ styleSources: Array.from(state.styleSources?.values() ?? []),
+ styleSourceSelections: Array.from(
+ state.styleSourceSelections?.values() ?? []
+ ),
+ styles: Array.from(
+ state.styles?.values() ?? []
+ ) as EvaluationProject["styles"],
+});
+
+export type HighImpactFixtureApi = {
+ server: Server;
+ origin: string;
+ shareLink: string;
+ getProject: () => EvaluationProject;
+ getToolCalls: () => EvaluationToolCall[];
+ close: () => Promise<void>;
+};
+
+export const startHighImpactFixtureApi = async (
+ fixture: HighImpactFixture
+): Promise<HighImpactFixtureApi> => {
+ Object.assign(globalThis, { React });
+ const [stateAdapters, runtime, projectSession] = await Promise.all([
+ import("@webstudio-is/project-build/state"),
+ import("@webstudio-is/project-build/runtime"),
+ import("../../src/project-session"),
+ ]);
+ const { createBuilderStateFromBuildData, applyBuilderPatchTransactions } =
+ stateAdapters;
+ const { executeBuilderRuntimeOperation } = runtime;
+ const { createLocalProjectBundleFromSessionSnapshot } = projectSession;
+ const persistedPages = createPersistedPages(fixture.project);
+ const build = {
+ id: buildId,
+ projectId,
+ version: initialVersion,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ pages: migratePages(persistedPages),
+ instances: fixture.project.instances.map((instance) => ({
+ type: "instance" as const,
+ ...instance,
+ })),
+ props: fixture.project.props,
+ dataSources: fixture.project.dataSources,
+ resources: fixture.project.resources,
+ breakpoints: fixture.project.breakpoints,
+ styleSources: fixture.project.styleSources,
+ styleSourceSelections: fixture.project.styleSourceSelections,
+ styles: fixture.project.styles,
+ assets: [],
+ projectSettings: { meta: {}, compiler: {} },
+ };
+ let state = createBuilderStateFromBuildData(build as never);
+ let version = initialVersion;
+ let generatedId = 0;
+ const calls: EvaluationToolCall[] = [];
+ let origin = "";
+ const fixtureApi = await startRuntimeFixtureApi(
+ async ({ operationPath, readInput }) => {
+ let data: unknown;
+ if (operationPath === "build.loadProjectBundleByProjectId") {
+ data = createLocalProjectBundleFromSessionSnapshot(
+ {
+ projectId,
+ buildId,
+ version,
+ state,
+ freshness: createBuilderStateFreshness({ state, version }),
+ compatibilityVersion: "high-impact-fixture-v1",
+ compatibility: {
+ sessionVersion: "high-impact-fixture-v1",
+ runtimeContractVersion: "high-impact-fixture-v1",
+ projectSchemaVersion: "high-impact-fixture-v1",
+ },
+ },
+ { origin }
+ );
+ } else if (operationPath === "projects.get") {
+ data = {
+ id: projectId,
+ name: "High-impact evaluation",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ buildId,
+ version,
+ homePageId: "home",
+ features: {},
+ };
+ } else if (operationPath === "build.patch") {
+ const input = (await readInput()) as {
+ transactions?: BuilderPatchTransaction[];
+ };
+ state = applyBuilderPatchTransactions(
+ state,
+ input.transactions ?? []
+ ).state;
+ version += 1;
+ data = { version };
+ } else if (operationPath === "build.get") {
+ data = createRuntimeFixtureBuildSnapshot({
+ state,
+ projectId,
+ buildId,
+ version,
+ });
+ } else if (
+ operationPath === "projects.permissions" ||
+ operationPath === ""
+ ) {
+ data = runtimeFixturePermissions;
+ } else {
+ const input = await readInput();
+ const call: EvaluationToolCall = {
+ name:
+ publicApiCommandByOperationId.get(operationPath) ?? operationPath,
+ arguments:
+ typeof input === "object" && input !== null
+ ? (input as Record<string, unknown>)
+ : undefined,
+ };
+ calls.push(call);
+ try {
+ const result = await executeBuilderRuntimeOperation({
+ id: operationPath,
+ state,
+ input,
+ context: {
+ createId: () => `evaluation-${generatedId++}`,
+ projectId,
+ projectVersion: version,
+ },
+ });
+ if (
+ typeof result === "object" &&
+ result !== null &&
+ "kind" in result &&
+ (result as BuilderRuntimeMutation).kind === "mutation"
+ ) {
+ const mutation = result as BuilderRuntimeMutation;
+ state = applyBuilderPatchTransactions(state, [
+ {
+ id: `evaluation-transaction-${generatedId++}`,
+ payload: mutation.payload,
+ },
+ ]).state;
+ version += 1;
+ data = mutation.result;
+ } else {
+ data = result;
+ }
+ } catch (error) {
+ call.isError = true;
+ throw error;
+ }
+ }
+ return data;
+ }
+ );
+ const { server } = fixtureApi;
+ origin = fixtureApi.origin;
+ return {
+ server,
+ origin,
+ shareLink: `${origin}/builder/${projectId}?authToken=fixture-only-not-persisted`,
+ getProject: () => stateToProject(state),
+ getToolCalls: () => structuredClone(calls),
+ close: fixtureApi.close,
+ };
+};
diff --git a/packages/cli/evaluations/high-impact/fixtures.ts b/packages/cli/evaluations/high-impact/fixtures.ts
new file mode 100644
index 0000000000..2018a03cc0
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/fixtures.ts
@@ -0,0 +1,264 @@
+export type EvaluationPage = {
+ id: string;
+ name: string;
+ path: string;
+ rootInstanceId: string;
+};
+
+export type EvaluationInstance = {
+ id: string;
+ component: string;
+ tag?: string;
+ label?: string;
+ children: Array<
+ | { type: "id"; value: string }
+ | { type: "text"; value: string }
+ | { type: "expression"; value: string }
+ >;
+};
+
+export type EvaluationProp = {
+ id: string;
+ instanceId: string;
+ name: string;
+ type: string;
+ value: unknown;
+};
+
+export type EvaluationStyle = {
+ styleSourceId: string;
+ breakpointId: string;
+ property: string;
+ value: unknown;
+};
+
+export type EvaluationProject = {
+ pages: EvaluationPage[];
+ instances: EvaluationInstance[];
+ props: EvaluationProp[];
+ dataSources: Array<Record<string, unknown>>;
+ resources: Array<Record<string, unknown>>;
+ breakpoints: Array<{
+ id: string;
+ label: string;
+ minWidth?: number;
+ maxWidth?: number;
+ }>;
+ styleSources: Array<
+ { type: "token"; id: string; name: string } | { type: "local"; id: string }
+ >;
+ styleSourceSelections: Array<{ instanceId: string; values: string[] }>;
+ styles: EvaluationStyle[];
+};
+
+export type HighImpactFixture = {
+ id: "authenticated-page-v1" | "design-input-v1";
+ objective: string;
+ project: EvaluationProject;
+};
+
+const homePage: EvaluationPage = {
+ id: "home",
+ name: "Home",
+ path: "",
+ rootInstanceId: "home-root",
+};
+
+const emptyProject = (): EvaluationProject => ({
+ pages: [homePage],
+ instances: [
+ {
+ id: "home-root",
+ component: "Body",
+ tag: "body",
+ children: [{ type: "id", value: "home-main" }],
+ },
+ {
+ id: "home-main",
+ component: "Box",
+ tag: "main",
+ children: [{ type: "text", value: "Northstar workspace" }],
+ },
+ ],
+ props: [],
+ dataSources: [],
+ resources: [],
+ breakpoints: [
+ { id: "base", label: "Base" },
+ { id: "tablet", label: "Tablet", maxWidth: 991 },
+ { id: "mobile", label: "Mobile portrait", maxWidth: 479 },
+ ],
+ styleSources: [],
+ styleSourceSelections: [],
+ styles: [],
+});
+
+export const authenticatedPageFixture: HighImpactFixture = {
+ id: "authenticated-page-v1",
+ objective:
+ "Add an editable /account page using the project's existing authentication convention. Cover signed-out, loading, signed-in, and failed-auth UI states, then audit and visually verify the states. Do not persist credentials or private session data.",
+ project: {
+ ...emptyProject(),
+ resources: [
+ {
+ id: "supabase-session",
+ name: "Supabase session via server",
+ method: "get",
+ url: '"/api/auth/session"',
+ headers: [],
+ searchParams: [],
+ },
+ ],
+ dataSources: [
+ {
+ id: "supabase-session-data",
+ type: "resource",
+ name: "Supabase session",
+ scopeInstanceId: "home-root",
+ resourceId: "supabase-session",
+ },
+ {
+ id: "auth-preview-state",
+ type: "variable",
+ name: "Auth preview state",
+ scopeInstanceId: "home-root",
+ value: { type: "string", value: "signed-out" },
+ },
+ ],
+ },
+};
+
+export const designInputFixture: HighImpactFixture & {
+ designReference: {
+ desktop: Record<string, unknown>;
+ mobile: Record<string, unknown>;
+ };
+} = {
+ id: "design-input-v1",
+ objective:
+ "Build an editable /summer page from the supplied desktop and mobile design reference. Preserve and reuse the existing design system, implement responsive behavior with the project's breakpoints, then run rendered audit and inspect desktop/mobile screenshots.",
+ project: {
+ ...emptyProject(),
+ styleSources: [
+ { type: "token", id: "token-brand", name: "Brand / Coral" },
+ { type: "token", id: "token-ink", name: "Text / Ink" },
+ { type: "token", id: "token-heading", name: "Type / Heading" },
+ { type: "local", id: "home-main-local" },
+ ],
+ styleSourceSelections: [
+ {
+ instanceId: "home-main",
+ values: ["token-ink", "token-heading", "home-main-local"],
+ },
+ ],
+ styles: [
+ {
+ styleSourceId: "token-brand",
+ breakpointId: "base",
+ property: "background-color",
+ value: { type: "rgb", r: 238, g: 101, b: 82, alpha: 1 },
+ },
+ {
+ styleSourceId: "token-ink",
+ breakpointId: "base",
+ property: "color",
+ value: { type: "rgb", r: 30, g: 35, b: 41, alpha: 1 },
+ },
+ {
+ styleSourceId: "token-heading",
+ breakpointId: "base",
+ property: "font-family",
+ value: { type: "fontFamily", value: ["Manrope", "sans-serif"] },
+ },
+ {
+ styleSourceId: "home-main-local",
+ breakpointId: "base",
+ property: "max-width",
+ value: { type: "unit", unit: "px", value: 1200 },
+ },
+ ],
+ },
+ designReference: {
+ desktop: {
+ viewport: { width: 1440, height: 900 },
+ structure: ["header", "main", "hero", "featured trips", "footer"],
+ hero: {
+ heading: "Find your latitude",
+ alignment: "left",
+ columns: 2,
+ },
+ featuredTrips: { columns: 3 },
+ },
+ mobile: {
+ viewport: { width: 390, height: 844 },
+ structure: ["header", "main", "hero", "featured trips", "footer"],
+ hero: { alignment: "left", columns: 1 },
+ featuredTrips: { columns: 1 },
+ navigation: "collapsed",
+ },
+ },
+};
+
+export const highImpactFixtures = [
+ authenticatedPageFixture,
+ designInputFixture,
+] as const;
+
+export const validateHighImpactFixture = (fixture: HighImpactFixture) => {
+ const failures: string[] = [];
+ const instanceIds = new Set(
+ fixture.project.instances.map((instance) => instance.id)
+ );
+ if (
+ fixture.project.pages.some(
+ (page) => instanceIds.has(page.rootInstanceId) === false
+ )
+ ) {
+ failures.push(
+ "Every fixture page must reference an existing root instance."
+ );
+ }
+ if (
+ fixture.project.breakpoints.some(
+ (breakpoint) => breakpoint.id === "base"
+ ) === false
+ ) {
+ failures.push("Every fixture must define a base breakpoint.");
+ }
+ if (fixture.id === "authenticated-page-v1") {
+ const source = JSON.stringify(fixture.project).toLowerCase();
+ if (
+ source.includes("supabase") === false ||
+ source.includes("/api/auth/session") === false
+ ) {
+ failures.push(
+ "The auth fixture must expose its existing server-mediated Supabase convention."
+ );
+ }
+ }
+ if (fixture.id === "design-input-v1") {
+ const designFixture = fixture as typeof designInputFixture;
+ const desktopWidth = Number(
+ (designFixture.designReference.desktop.viewport as { width?: unknown })
+ .width
+ );
+ const mobileWidth = Number(
+ (designFixture.designReference.mobile.viewport as { width?: unknown })
+ .width
+ );
+ if (desktopWidth < 1200 || mobileWidth > 479) {
+ failures.push(
+ "The design fixture must include familiar desktop and mobile references."
+ );
+ }
+ if (
+ fixture.project.styleSources.some((source) => source.type === "token") ===
+ false
+ ) {
+ failures.push(
+ "The design fixture must include an existing design-token baseline."
+ );
+ }
+ }
+ return { valid: failures.length === 0, failures };
+};
diff --git a/packages/cli/evaluations/high-impact/mcp-trace-proxy.test.ts b/packages/cli/evaluations/high-impact/mcp-trace-proxy.test.ts
new file mode 100644
index 0000000000..70b32683c0
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/mcp-trace-proxy.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, test } from "vitest";
+import { getMcpTraceRequest, getMcpTraceResponse } from "./mcp-trace-proxy";
+
+describe("bounded MCP tracing", () => {
+ test("retains only the tool name and screenshot viewport", () => {
+ expect(
+ getMcpTraceRequest({
+ jsonrpc: "2.0",
+ id: 7,
+ method: "tools/call",
+ params: {
+ name: "screenshot",
+ arguments: {
+ viewport: { width: 390, height: 844 },
+ authToken: "private",
+ path: "/account",
+ },
+ },
+ })
+ ).toEqual({
+ id: 7,
+ call: {
+ name: "screenshot",
+ arguments: { viewport: { width: 390, height: 844 } },
+ },
+ });
+ });
+
+ test("records success or failure after the matching response", () => {
+ const pending = new Map([
+ [1, { name: "meta.guide" }],
+ [2, { name: "verify-bindings" }],
+ ]);
+
+ expect(getMcpTraceResponse({ id: 1, result: {} }, pending)).toEqual({
+ name: "meta.guide",
+ });
+ expect(
+ getMcpTraceResponse({ id: 2, result: { isError: true } }, pending)
+ ).toEqual({ name: "verify-bindings", isError: true });
+ expect(pending.size).toBe(0);
+ });
+});
diff --git a/packages/cli/evaluations/high-impact/mcp-trace-proxy.ts b/packages/cli/evaluations/high-impact/mcp-trace-proxy.ts
new file mode 100644
index 0000000000..ea8e62b205
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/mcp-trace-proxy.ts
@@ -0,0 +1,121 @@
+import { appendFileSync } from "node:fs";
+import { spawn } from "node:child_process";
+import { pathToFileURL } from "node:url";
+import { isPlainRecord } from "../../src/type-utils";
+
+type JsonRpcId = string | number;
+
+export type BoundedMcpCall = {
+ name: string;
+ arguments?: { viewport: { width: number; height: number } };
+ isError?: true;
+};
+
+export const getMcpTraceRequest = (value: unknown) => {
+ if (isPlainRecord(value) === false || value.method !== "tools/call") {
+ return;
+ }
+ const id = value.id;
+ const params = value.params;
+ if (
+ (typeof id !== "string" && typeof id !== "number") ||
+ isPlainRecord(params) === false ||
+ typeof params.name !== "string"
+ ) {
+ return;
+ }
+ const call: BoundedMcpCall = { name: params.name };
+ if (params.name === "screenshot" && isPlainRecord(params.arguments)) {
+ const viewport = params.arguments.viewport;
+ if (
+ isPlainRecord(viewport) &&
+ typeof viewport.width === "number" &&
+ typeof viewport.height === "number"
+ ) {
+ call.arguments = {
+ viewport: { width: viewport.width, height: viewport.height },
+ };
+ }
+ }
+ return { id, call };
+};
+
+export const getMcpTraceResponse = (
+ value: unknown,
+ pending: Map<JsonRpcId, BoundedMcpCall>
+) => {
+ if (isPlainRecord(value) === false) {
+ return;
+ }
+ const id = value.id;
+ if (typeof id !== "string" && typeof id !== "number") {
+ return;
+ }
+ const call = pending.get(id);
+ if (call === undefined) {
+ return;
+ }
+ pending.delete(id);
+ const result = value.result;
+ return value.error !== undefined ||
+ (isPlainRecord(result) && result.isError === true)
+ ? { ...call, isError: true as const }
+ : call;
+};
+
+const observeJsonLines = (
+ stream: NodeJS.ReadableStream,
+ visit: (value: unknown) => void
+) => {
+ let buffered = "";
+ stream.on("data", (chunk) => {
+ buffered += String(chunk);
+ const lines = buffered.split("\n");
+ buffered = lines.pop() ?? "";
+ for (const line of lines) {
+ try {
+ visit(JSON.parse(line));
+ } catch {}
+ }
+ });
+};
+
+const run = () => {
+ const [, , target, tracePath] = process.argv;
+ if (target === undefined || tracePath === undefined) {
+ throw new Error("Expected target CLI and trace file paths.");
+ }
+ const pending = new Map<JsonRpcId, BoundedMcpCall>();
+ const child = spawn(process.execPath, [target, "mcp"], {
+ env: process.env,
+ stdio: ["pipe", "pipe", "inherit"],
+ });
+ observeJsonLines(process.stdin, (value) => {
+ const request = getMcpTraceRequest(value);
+ if (request !== undefined) {
+ pending.set(request.id, request.call);
+ }
+ });
+ observeJsonLines(child.stdout, (value) => {
+ const call = getMcpTraceResponse(value, pending);
+ if (call !== undefined) {
+ appendFileSync(tracePath, `${JSON.stringify(call)}\n`, "utf8");
+ }
+ });
+ process.stdin.pipe(child.stdin);
+ child.stdout.pipe(process.stdout);
+ child.on("exit", (code, signal) => {
+ if (signal !== null) {
+ process.kill(process.pid, signal);
+ return;
+ }
+ process.exit(code ?? 1);
+ });
+};
+
+if (
+ process.argv[1] !== undefined &&
+ import.meta.url === pathToFileURL(process.argv[1]).href
+) {
+ run();
+}
diff --git a/packages/cli/evaluations/high-impact/results/authenticated-page-v1.json b/packages/cli/evaluations/high-impact/results/authenticated-page-v1.json
new file mode 100644
index 0000000000..7c6a4f8773
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/results/authenticated-page-v1.json
@@ -0,0 +1,49 @@
+{
+ "schemaVersion": 1,
+ "kind": "high-impact-minimal-context-agent-evaluation-result",
+ "fixtureId": "authenticated-page-v1",
+ "outcome": "passed",
+ "cli": "source",
+ "provider": "openai",
+ "model": "gpt-5.6-luna",
+ "commandSha256": "f61daff839ad1c7579976c4f442e2b83082498c075bcea0a51b7f7879acc3086",
+ "durationMs": 116865,
+ "exitCode": 0,
+ "toolCallCount": 20,
+ "focusedReadCount": 3,
+ "callSequence": [
+ "meta.guide",
+ "meta.get_more_tools",
+ "meta.get_more_tools",
+ "list-resources",
+ "list-pages",
+ "verify-bindings",
+ "list-instances",
+ "meta.get_more_tools",
+ "create-page",
+ "create-resource",
+ "create-resource",
+ "insert-fragment",
+ "meta.get_more_tools",
+ "audit",
+ "preview.start",
+ "preview.start",
+ "screenshot",
+ "screenshot",
+ "audit",
+ "verify-bindings"
+ ],
+ "checks": {
+ "guidance": "passed",
+ "privacy": "passed",
+ "expressions": "passed",
+ "boundedReads": "passed",
+ "bindingVerification": "passed",
+ "audit": "passed",
+ "visualEvidence": "passed",
+ "accountPage": "passed",
+ "authStates": "passed",
+ "providerConvention": "passed",
+ "editableStructure": "passed"
+ }
+}
diff --git a/packages/cli/evaluations/high-impact/results/design-input-v1.json b/packages/cli/evaluations/high-impact/results/design-input-v1.json
new file mode 100644
index 0000000000..af2415f0f8
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/results/design-input-v1.json
@@ -0,0 +1,55 @@
+{
+ "schemaVersion": 1,
+ "kind": "high-impact-minimal-context-agent-evaluation-result",
+ "fixtureId": "design-input-v1",
+ "outcome": "passed",
+ "cli": "source",
+ "provider": "openai",
+ "model": "gpt-5.6-luna",
+ "commandSha256": "a3c4c6dc81ed196ad8074222df7af560690d7334b0410e497b6e992ee63a6070",
+ "durationMs": 196834,
+ "exitCode": 0,
+ "toolCallCount": 26,
+ "focusedReadCount": 6,
+ "callSequence": [
+ "meta.guide",
+ "meta.index",
+ "list-design-tokens",
+ "list-breakpoints",
+ "meta.get_more_tools",
+ "list-assets",
+ "list-pages",
+ "list-instances",
+ "create-page",
+ "insert-fragment",
+ "list-instances",
+ "attach-design-token",
+ "attach-design-token",
+ "attach-design-token",
+ "audit",
+ "screenshot",
+ "screenshot",
+ "screenshot",
+ "screenshot",
+ "meta.get_more_tools",
+ "detach-design-token",
+ "audit",
+ "attach-design-token",
+ "audit",
+ "screenshot",
+ "screenshot"
+ ],
+ "checks": {
+ "guidance": "passed",
+ "privacy": "passed",
+ "expressions": "passed",
+ "boundedReads": "passed",
+ "audit": "passed",
+ "summerPage": "passed",
+ "semanticStructure": "passed",
+ "supportedComponents": "passed",
+ "designSystem": "passed",
+ "breakpointBehavior": "passed",
+ "viewportEvidence": "passed"
+ }
+}
diff --git a/packages/cli/evaluations/high-impact/run-local-agent.ts b/packages/cli/evaluations/high-impact/run-local-agent.ts
new file mode 100644
index 0000000000..afe102fe30
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/run-local-agent.ts
@@ -0,0 +1,122 @@
+import { execFile } from "node:child_process";
+import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+import { promisify } from "node:util";
+import {
+ authenticatedPageFixture,
+ designInputFixture,
+ type HighImpactFixture,
+} from "./fixtures";
+import { startHighImpactFixtureApi } from "./fixture-api";
+import { evaluateHighImpactOutcome } from "./validate";
+import { runHighImpactAgentEvaluation } from "./agent-runner";
+import { collectHighImpactArtifacts } from "./artifacts";
+import type { EvaluationToolCall } from "./validate";
+
+const execFileAsync = promisify(execFile);
+const require = createRequire(import.meta.url);
+
+const shellQuote = (value: string) => `'${value.replaceAll("'", `'"'"'`)}'`;
+
+const run = async () => {
+ const fixture: HighImpactFixture =
+ process.env.WEBSTUDIO_HIGH_IMPACT_FIXTURE === "design-input-v1"
+ ? designInputFixture
+ : authenticatedPageFixture;
+ const repositoryRoot = resolve(import.meta.dirname, "../../../..");
+ const localCli = resolve(repositoryRoot, "packages/cli/local.js");
+ const codex = process.env.WEBSTUDIO_HIGH_IMPACT_CODEX ?? "codex";
+ const model = process.env.WEBSTUDIO_HIGH_IMPACT_MODEL ?? "gpt-5.6-sol";
+ const resultPath = resolve(
+ process.env.WEBSTUDIO_HIGH_IMPACT_RESULT ??
+ join(import.meta.dirname, "results", `${fixture.id}.json`)
+ );
+ const directory = await mkdtemp(
+ join(tmpdir(), "webstudio-high-impact-agent-")
+ );
+ const projectDirectory = join(directory, "project");
+ const configDirectory = join(directory, "config");
+ const taskPath = join(directory, "task.json");
+ const tracePath = join(directory, "mcp-calls.jsonl");
+ const traceProxy = join(import.meta.dirname, "mcp-trace-proxy.ts");
+ const fixtureApi = await startHighImpactFixtureApi(fixture);
+ await mkdir(projectDirectory, { recursive: true });
+ const env = { ...process.env, WEBSTUDIO_CONFIG_DIR: configDirectory };
+ try {
+ await execFileAsync(
+ process.execPath,
+ [localCli, "init", "--link", fixtureApi.shareLink, "--json"],
+ { cwd: projectDirectory, env }
+ );
+ const mcpConfig = [
+ `mcp_servers.webstudio.command=${JSON.stringify(process.execPath)}`,
+ `mcp_servers.webstudio.args=${JSON.stringify([
+ `--import=${pathToFileURL(require.resolve("tsx")).href}`,
+ traceProxy,
+ localCli,
+ tracePath,
+ ])}`,
+ `mcp_servers.webstudio.cwd=${JSON.stringify(projectDirectory)}`,
+ `mcp_servers.webstudio.env={ WEBSTUDIO_CONFIG_DIR = ${JSON.stringify(configDirectory)} }`,
+ ];
+ const agentCommand = [
+ shellQuote(codex),
+ "exec",
+ "--ephemeral",
+ "--dangerously-bypass-approvals-and-sandbox",
+ "--skip-git-repo-check",
+ "--ignore-rules",
+ "--model",
+ shellQuote(model),
+ "--cd",
+ shellQuote(projectDirectory),
+ ...mcpConfig.flatMap((config) => ["--config", shellQuote(config)]),
+ shellQuote(
+ "Read the evaluation task at $WEBSTUDIO_HIGH_IMPACT_AGENT_TASK and complete its objective using the configured Webstudio MCP."
+ ),
+ ].join(" ");
+ let toolCalls: EvaluationToolCall[] = [];
+ const readToolCalls = async () =>
+ (await readFile(tracePath, "utf8").catch(() => ""))
+ .split("\n")
+ .filter(Boolean)
+ .map((line) => JSON.parse(line) as EvaluationToolCall);
+ const result = await runHighImpactAgentEvaluation({
+ fixture,
+ target: { kind: "source", repositoryRoot },
+ agentCommand,
+ cwd: projectDirectory,
+ taskPath,
+ resultPath,
+ provider: "openai",
+ model,
+ env,
+ getCallSequence: () => toolCalls.map(({ name }) => name),
+ evaluate: async () => {
+ toolCalls = await readToolCalls();
+ return evaluateHighImpactOutcome({
+ fixture,
+ project: fixtureApi.getProject(),
+ toolCalls,
+ artifacts: await collectHighImpactArtifacts(projectDirectory),
+ });
+ },
+ });
+ process.stdout.write(`${JSON.stringify(result, undefined, 2)}\n`);
+ if (result.outcome !== "passed") {
+ process.exitCode = 1;
+ }
+ } finally {
+ await fixtureApi.close();
+ if (process.env.WEBSTUDIO_HIGH_IMPACT_KEEP_WORKSPACE === "1") {
+ process.stderr.write(`Preserved evaluation workspace: ${directory}\n`);
+ } else {
+ await rm(directory, { recursive: true, force: true });
+ }
+ }
+};
+
+await run();
diff --git a/packages/cli/evaluations/high-impact/validate.test.ts b/packages/cli/evaluations/high-impact/validate.test.ts
new file mode 100644
index 0000000000..d2a377b70d
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/validate.test.ts
@@ -0,0 +1,269 @@
+import { describe, expect, test } from "vitest";
+import {
+ authenticatedPageFixture,
+ designInputFixture,
+ highImpactFixtures,
+ validateHighImpactFixture,
+ type EvaluationProject,
+} from "./fixtures";
+import { evaluateHighImpactOutcome, type EvaluationToolCall } from "./validate";
+
+const clone = <Value>(value: Value): Value => structuredClone(value);
+
+const addAuthPage = (): EvaluationProject => {
+ const project = clone(authenticatedPageFixture.project);
+ project.pages.push({
+ id: "account",
+ name: "Account",
+ path: "/account",
+ rootInstanceId: "account-root",
+ });
+ project.instances.push(
+ {
+ id: "account-root",
+ component: "Body",
+ tag: "body",
+ children: [{ type: "id", value: "account-main" }],
+ },
+ {
+ id: "account-main",
+ component: "Box",
+ tag: "main",
+ children: [
+ { type: "id", value: "signed-out" },
+ { type: "id", value: "loading" },
+ { type: "id", value: "signed-in" },
+ { type: "id", value: "failed-auth" },
+ ],
+ },
+ ...["signed-out", "loading", "signed-in", "failed-auth"].map((state) => ({
+ id: state,
+ component: "Box",
+ tag: "section",
+ label: state.replace("-", " "),
+ children: [
+ {
+ type: "text" as const,
+ value: `${state.replaceAll("-", " ")} Supabase state`,
+ },
+ ],
+ }))
+ );
+ project.resources.push({
+ id: "account-supabase-session",
+ name: "Supabase account session",
+ method: "get",
+ url: '"/api/auth/session"',
+ headers: [],
+ });
+ return project;
+};
+
+const addDesignPage = (): EvaluationProject => {
+ const project = clone(designInputFixture.project);
+ project.pages.push({
+ id: "summer",
+ name: "Summer",
+ path: "/summer",
+ rootInstanceId: "summer-root",
+ });
+ const definitions = [
+ [
+ "summer-root",
+ "Body",
+ "body",
+ ["summer-header", "summer-main", "summer-footer"],
+ ],
+ ["summer-header", "Box", "header", ["summer-nav"]],
+ ["summer-nav", "Box", "nav", []],
+ ["summer-main", "Box", "main", ["summer-hero", "summer-trips"]],
+ ["summer-hero", "Box", "section", ["summer-heading", "summer-copy"]],
+ ["summer-heading", "Heading", "h1", []],
+ ["summer-copy", "Paragraph", "p", []],
+ ["summer-trips", "Box", "section", ["summer-trip-a", "summer-trip-b"]],
+ ["summer-trip-a", "Box", "article", []],
+ ["summer-trip-b", "Box", "article", []],
+ ["summer-footer", "Box", "footer", []],
+ ] as const;
+ project.instances.push(
+ ...definitions.map(([id, component, tag, children]) => ({
+ id,
+ component,
+ tag,
+ children: children.map((value) => ({ type: "id" as const, value })),
+ }))
+ );
+ project.styleSources.push({ type: "local", id: "summer-layout" });
+ project.styleSourceSelections.push({
+ instanceId: "summer-main",
+ values: ["token-ink", "token-heading", "summer-layout"],
+ });
+ project.styles.push({
+ styleSourceId: "summer-layout",
+ breakpointId: "mobile",
+ property: "grid-template-columns",
+ value: { type: "keyword", value: "1fr" },
+ });
+ return project;
+};
+
+const designCalls: EvaluationToolCall[] = [
+ { name: "meta.guide" },
+ { name: "list-breakpoints" },
+ { name: "list-design-tokens" },
+ { name: "insert-fragment" },
+ { name: "update-styles" },
+ { name: "audit" },
+ { name: "screenshot", arguments: { viewport: { width: 1440, height: 900 } } },
+ { name: "screenshot", arguments: { viewport: { width: 390, height: 844 } } },
+];
+
+describe("high-impact fixture validation", () => {
+ test("keeps both fixtures complete and deterministic", () => {
+ expect(highImpactFixtures.map(validateHighImpactFixture)).toEqual([
+ { valid: true, failures: [] },
+ { valid: true, failures: [] },
+ ]);
+ expect(JSON.stringify(highImpactFixtures)).toBe(
+ JSON.stringify(highImpactFixtures)
+ );
+ });
+});
+
+describe("authenticated-page evaluation", () => {
+ test("accepts four editable states using the existing provider convention", () => {
+ const result = evaluateHighImpactOutcome({
+ fixture: authenticatedPageFixture,
+ project: addAuthPage(),
+ toolCalls: [
+ { name: "meta.guide" },
+ { name: "list-resources" },
+ { name: "list-instances" },
+ { name: "insert-fragment" },
+ { name: "create-resource" },
+ { name: "verify-bindings" },
+ { name: "audit" },
+ {
+ name: "screenshot",
+ arguments: { viewport: { width: 1440, height: 900 } },
+ },
+ ],
+ });
+ expect(result).toMatchObject({ passed: true, failures: [] });
+ });
+
+ test("rejects persisted credentials and a conflicting provider", () => {
+ const project = addAuthPage();
+ project.resources.push({
+ id: "firebase-auth",
+ name: "Firebase",
+ method: "get",
+ url: '"/auth"',
+ headers: [
+ {
+ name: "Authorization",
+ value: '"Bearer sk-abcdefghijklmnopqrstuvwxyz"',
+ },
+ ],
+ });
+ const result = evaluateHighImpactOutcome({
+ fixture: authenticatedPageFixture,
+ project,
+ toolCalls: [{ name: "audit" }],
+ });
+ expect(result.passed).toBe(false);
+ expect(result.checks).toMatchObject({
+ privacy: "failed",
+ providerConvention: "failed",
+ });
+ });
+
+ test("requires guidance, binding verification, audit, and visual evidence", () => {
+ const result = evaluateHighImpactOutcome({
+ fixture: authenticatedPageFixture,
+ project: addAuthPage(),
+ toolCalls: [{ name: "insert-fragment" }],
+ });
+
+ expect(result.checks).toMatchObject({
+ guidance: "failed",
+ bindingVerification: "failed",
+ audit: "failed",
+ visualEvidence: "failed",
+ });
+ });
+});
+
+describe("design-input evaluation", () => {
+ test("accepts semantic token-preserving responsive output with visual evidence", () => {
+ const result = evaluateHighImpactOutcome({
+ fixture: designInputFixture,
+ project: addDesignPage(),
+ toolCalls: designCalls,
+ });
+ expect(result).toMatchObject({ passed: true, failures: [] });
+ });
+
+ test("rejects unsupported components", () => {
+ const project = addDesignPage();
+ project.instances.find(
+ (instance) => instance.id === "summer-hero"
+ )!.component = "HtmlEmbed";
+ const result = evaluateHighImpactOutcome({
+ fixture: designInputFixture,
+ project,
+ toolCalls: designCalls,
+ });
+ expect(result.checks.supportedComponents).toBe("failed");
+ });
+
+ test("rejects invalid expressions", () => {
+ const project = addDesignPage();
+ project.props.push({
+ id: "bad-expression",
+ instanceId: "summer-heading",
+ name: "hidden",
+ type: "expression",
+ value: "user &&",
+ });
+ const result = evaluateHighImpactOutcome({
+ fixture: designInputFixture,
+ project,
+ toolCalls: designCalls,
+ });
+ expect(result.checks.expressions).toBe("failed");
+ });
+
+ test("rejects broad or unnecessarily verbose reads", () => {
+ const result = evaluateHighImpactOutcome({
+ fixture: designInputFixture,
+ project: addDesignPage(),
+ toolCalls: [{ name: "snapshot" }, ...designCalls],
+ });
+ expect(result.checks.boundedReads).toBe("failed");
+ });
+
+ test("requires both desktop and mobile evidence", () => {
+ const result = evaluateHighImpactOutcome({
+ fixture: designInputFixture,
+ project: addDesignPage(),
+ toolCalls: designCalls.filter(
+ (call) =>
+ (call.arguments?.viewport as { width?: number } | undefined)
+ ?.width !== 390
+ ),
+ });
+ expect(result.checks.viewportEvidence).toBe("failed");
+ });
+
+ test("accepts a successful rendered manifest as local audit evidence", () => {
+ const result = evaluateHighImpactOutcome({
+ fixture: designInputFixture,
+ project: addDesignPage(),
+ toolCalls: designCalls.filter((call) => call.name !== "audit"),
+ artifacts: [{ kind: "audit", passed: true }],
+ });
+
+ expect(result.checks.audit).toBe("passed");
+ });
+});
diff --git a/packages/cli/evaluations/high-impact/validate.ts b/packages/cli/evaluations/high-impact/validate.ts
new file mode 100644
index 0000000000..c5cd7f534d
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/validate.ts
@@ -0,0 +1,447 @@
+import { parseExpressionAt } from "acorn";
+import {
+ authenticatedPageFixture,
+ designInputFixture,
+ type EvaluationInstance,
+ type EvaluationProject,
+ type HighImpactFixture,
+} from "./fixtures";
+
+export type EvaluationToolCall = {
+ name: string;
+ arguments?: Record<string, unknown>;
+ isError?: boolean;
+};
+
+export type EvaluationArtifact = {
+ kind: "screenshot" | "audit";
+ path?: string;
+ viewport?: { width: number; height: number };
+ passed: boolean;
+};
+
+export type HighImpactEvaluationInput = {
+ fixture: HighImpactFixture;
+ project: EvaluationProject;
+ toolCalls: EvaluationToolCall[];
+ artifacts?: EvaluationArtifact[];
+};
+
+export type HighImpactEvaluationResult = {
+ passed: boolean;
+ checks: Record<string, "passed" | "failed">;
+ failures: string[];
+ metrics: { toolCallCount: number; focusedReadCount: number };
+};
+
+const secretPatterns = [
+ /(?:service[_-]?role|refresh[_-]?token|client[_-]?secret|password)\s*["'=:\s]+[^\s"']+/i,
+ /authorization\s*:\s*bearer\s+\S+/i,
+ /\b(?:eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}|sk-[A-Za-z0-9_-]{20,})\b/,
+];
+
+const broadReadNames = new Set([
+ "snapshot",
+ "components.list",
+ "components.coverage-plan",
+]);
+
+const allowedComponents = new Set([
+ "body",
+ "box",
+ "element",
+ "text",
+ "heading",
+ "paragraph",
+ "link",
+ "button",
+ "image",
+ "form",
+ "label",
+ "input",
+ "separator",
+]);
+
+const stringifyProject = (project: EvaluationProject) =>
+ JSON.stringify(project);
+
+const descendants = (project: EvaluationProject, rootId: string) => {
+ const byId = new Map(
+ project.instances.map((instance) => [instance.id, instance])
+ );
+ const found: EvaluationInstance[] = [];
+ const pending = [rootId];
+ const seen = new Set<string>();
+ while (pending.length > 0) {
+ const id = pending.pop()!;
+ if (seen.has(id)) {
+ continue;
+ }
+ seen.add(id);
+ const instance = byId.get(id);
+ if (instance === undefined) {
+ continue;
+ }
+ found.push(instance);
+ for (const child of instance.children) {
+ if (child.type === "id") {
+ pending.push(child.value);
+ }
+ }
+ }
+ return found;
+};
+
+const textOf = (instances: EvaluationInstance[]) =>
+ instances
+ .flatMap((instance) => [
+ instance.label ?? "",
+ ...instance.children.map((child) => child.value),
+ ])
+ .join(" ")
+ .toLowerCase();
+
+const getPageEvaluationContext = (project: EvaluationProject, path: string) => {
+ const page = project.pages.find((candidate) => candidate.path === path);
+ return {
+ page,
+ instances:
+ page === undefined ? [] : descendants(project, page.rootInstanceId),
+ };
+};
+
+const isValidExpression = (value: string) => {
+ try {
+ const expression = parseExpressionAt(value, 0, { ecmaVersion: "latest" });
+ return value.slice(expression.end).trim() === "";
+ } catch {
+ return false;
+ }
+};
+
+const validateExpressions = (project: EvaluationProject) => {
+ const expressions = [
+ ...project.instances.flatMap((instance) =>
+ instance.children
+ .filter((child) => child.type === "expression")
+ .map((child) => child.value)
+ ),
+ ...project.props
+ .filter((prop) => prop.type === "expression")
+ .map((prop) => String(prop.value)),
+ ...project.resources.flatMap((resource) => [
+ String(resource.url ?? ""),
+ ...(
+ (resource.headers as Array<{ value?: unknown }> | undefined) ?? []
+ ).map((header) => String(header.value ?? "")),
+ ]),
+ ];
+ return expressions.every(isValidExpression);
+};
+
+const hasSuccessfulCall = (calls: EvaluationToolCall[], name: string) =>
+ calls.some((call) => call.name === name && call.isError !== true);
+
+const hasPassedEvidence = (
+ input: HighImpactEvaluationInput,
+ kind: EvaluationArtifact["kind"]
+) =>
+ hasSuccessfulCall(input.toolCalls, kind) ||
+ (input.artifacts ?? []).some(
+ (artifact) => artifact.kind === kind && artifact.passed
+ );
+
+const getScreenshots = (input: HighImpactEvaluationInput) => [
+ ...input.toolCalls
+ .filter((call) => call.name === "screenshot" && call.isError !== true)
+ .map((call) => ({
+ kind: "screenshot" as const,
+ viewport: call.arguments?.viewport as
+ | { width: number; height: number }
+ | undefined,
+ passed: true,
+ })),
+ ...(input.artifacts ?? []).filter(
+ (artifact) => artifact.kind === "screenshot" && artifact.passed
+ ),
+];
+
+const recordCheck = (
+ checks: Record<string, "passed" | "failed">,
+ failures: string[],
+ name: string,
+ passed: boolean,
+ failure: string
+) => {
+ checks[name] = passed ? "passed" : "failed";
+ if (passed === false) {
+ failures.push(failure);
+ }
+};
+
+const validateCommon = (
+ input: HighImpactEvaluationInput,
+ checks: Record<string, "passed" | "failed">,
+ failures: string[]
+) => {
+ const source = stringifyProject(input.project);
+ recordCheck(
+ checks,
+ failures,
+ "guidance",
+ hasSuccessfulCall(input.toolCalls, "meta.guide"),
+ "The agent did not request focused guidance before authoring."
+ );
+ recordCheck(
+ checks,
+ failures,
+ "privacy",
+ secretPatterns.every((pattern) => pattern.test(source) === false),
+ "Project data contains a credential, token, or private-session-shaped value."
+ );
+ recordCheck(
+ checks,
+ failures,
+ "expressions",
+ validateExpressions(input.project),
+ "Project data contains an invalid expression."
+ );
+ recordCheck(
+ checks,
+ failures,
+ "boundedReads",
+ input.toolCalls.every((call) => broadReadNames.has(call.name) === false) &&
+ input.toolCalls.filter((call) =>
+ /^(?:list-|get-|inspect-)/.test(call.name)
+ ).length <= 8,
+ "Evaluation used a broad project dump or more than eight focused project reads."
+ );
+};
+
+const validateAuth = (
+ input: HighImpactEvaluationInput,
+ checks: Record<string, "passed" | "failed">,
+ failures: string[]
+) => {
+ recordCheck(
+ checks,
+ failures,
+ "bindingVerification",
+ hasSuccessfulCall(input.toolCalls, "verify-bindings"),
+ "The agent did not verify the persisted authentication bindings."
+ );
+ recordCheck(
+ checks,
+ failures,
+ "audit",
+ hasPassedEvidence(input, "audit"),
+ "No successful account-page audit evidence was retained."
+ );
+ recordCheck(
+ checks,
+ failures,
+ "visualEvidence",
+ getScreenshots(input).length > 0,
+ "No successful account-page screenshot evidence was retained."
+ );
+ const { page, instances } = getPageEvaluationContext(
+ input.project,
+ "/account"
+ );
+ const instanceIds = new Set(instances.map((instance) => instance.id));
+ const text = [
+ textOf(instances),
+ ...input.project.props.flatMap((prop) =>
+ instanceIds.has(prop.instanceId) && typeof prop.value === "string"
+ ? [prop.value]
+ : []
+ ),
+ ].join(" ");
+ recordCheck(
+ checks,
+ failures,
+ "accountPage",
+ page !== undefined,
+ "The /account page is missing."
+ );
+ recordCheck(
+ checks,
+ failures,
+ "authStates",
+ [/signed[- ]?out/, /loading/, /signed[- ]?in/, /failed[- ]?auth/].every(
+ (state) => state.test(text)
+ ),
+ "The account page does not explicitly represent all four auth states."
+ );
+ const providerSource = JSON.stringify({
+ resources: input.project.resources,
+ dataSources: input.project.dataSources,
+ instances,
+ }).toLowerCase();
+ recordCheck(
+ checks,
+ failures,
+ "providerConvention",
+ providerSource.includes("supabase") &&
+ providerSource.includes("/api/auth/session") &&
+ /firebase|clerk|auth0/.test(providerSource) === false,
+ "The result did not reuse the fixture's server-mediated Supabase convention."
+ );
+ recordCheck(
+ checks,
+ failures,
+ "editableStructure",
+ instances.length >= 6 &&
+ instances.every((instance) => instance.component !== "HtmlEmbed"),
+ "Auth states must be ordinary editable components, not an embed or flat placeholder."
+ );
+};
+
+const validateDesign = (
+ input: HighImpactEvaluationInput,
+ checks: Record<string, "passed" | "failed">,
+ failures: string[]
+) => {
+ recordCheck(
+ checks,
+ failures,
+ "audit",
+ hasPassedEvidence(input, "audit"),
+ "No successful design audit evidence was retained."
+ );
+ const { page, instances } = getPageEvaluationContext(
+ input.project,
+ "/summer"
+ );
+ const tags = new Set(
+ instances.map(
+ (instance) =>
+ instance.tag ??
+ String(
+ input.project.props.find(
+ (prop) => prop.instanceId === instance.id && prop.name === "tag"
+ )?.value ?? ""
+ )
+ )
+ );
+ recordCheck(
+ checks,
+ failures,
+ "summerPage",
+ page !== undefined,
+ "The /summer page is missing."
+ );
+ recordCheck(
+ checks,
+ failures,
+ "semanticStructure",
+ ["header", "main", "section", "footer"].every((tag) => tags.has(tag)) &&
+ instances.some((instance) => instance.tag === "h1") &&
+ instances.length >= 10,
+ "The design was not authored as a substantive semantic editable tree."
+ );
+ recordCheck(
+ checks,
+ failures,
+ "supportedComponents",
+ instances.every((instance) =>
+ allowedComponents.has(
+ (instance.component.split(":").at(-1) ?? "").toLowerCase()
+ )
+ ),
+ "The design uses an unsupported or opaque component."
+ );
+ const baselineTokens = designInputFixture.project.styleSources.filter(
+ (source) => source.type === "token"
+ );
+ const tokenStylesPreserved = baselineTokens.every((token) => {
+ const sourceStillExists = input.project.styleSources.some(
+ (source) =>
+ source.type === "token" &&
+ source.id === token.id &&
+ source.name === token.name
+ );
+ const baselineStyles = designInputFixture.project.styles.filter(
+ (style) => style.styleSourceId === token.id
+ );
+ return (
+ sourceStillExists &&
+ baselineStyles.every((style) =>
+ input.project.styles.some(
+ (candidate) => JSON.stringify(candidate) === JSON.stringify(style)
+ )
+ )
+ );
+ });
+ const pageIds = new Set(instances.map((instance) => instance.id));
+ const reusedToken = input.project.styleSourceSelections.some(
+ (selection) =>
+ pageIds.has(selection.instanceId) &&
+ selection.values.some((value) =>
+ baselineTokens.some((token) => token.id === value)
+ )
+ );
+ recordCheck(
+ checks,
+ failures,
+ "designSystem",
+ tokenStylesPreserved && reusedToken,
+ "Existing design tokens were changed, duplicated, or not reused on the new page."
+ );
+ const fixtureBreakpointIds = new Set(
+ designInputFixture.project.breakpoints.map((breakpoint) => breakpoint.id)
+ );
+ const responsiveStyles = input.project.styles.filter(
+ (style) =>
+ style.breakpointId !== "base" &&
+ fixtureBreakpointIds.has(style.breakpointId) &&
+ input.project.styleSourceSelections.some(
+ (selection) =>
+ pageIds.has(selection.instanceId) &&
+ selection.values.includes(style.styleSourceId)
+ )
+ );
+ recordCheck(
+ checks,
+ failures,
+ "breakpointBehavior",
+ responsiveStyles.length > 0 &&
+ input.project.breakpoints.every((breakpoint) =>
+ fixtureBreakpointIds.has(breakpoint.id)
+ ),
+ "The page does not use the fixture's actual responsive breakpoints."
+ );
+ const screenshots = getScreenshots(input);
+ recordCheck(
+ checks,
+ failures,
+ "viewportEvidence",
+ screenshots.some((shot) => (shot.viewport?.width ?? 0) >= 1200) &&
+ screenshots.some((shot) => (shot.viewport?.width ?? Infinity) <= 479),
+ "Both desktop and mobile screenshot evidence are required."
+ );
+};
+
+export const evaluateHighImpactOutcome = (
+ input: HighImpactEvaluationInput
+): HighImpactEvaluationResult => {
+ const checks: Record<string, "passed" | "failed"> = {};
+ const failures: string[] = [];
+ validateCommon(input, checks, failures);
+ if (input.fixture.id === authenticatedPageFixture.id) {
+ validateAuth(input, checks, failures);
+ } else {
+ validateDesign(input, checks, failures);
+ }
+ return {
+ passed: failures.length === 0,
+ checks,
+ failures,
+ metrics: {
+ toolCallCount: input.toolCalls.length,
+ focusedReadCount: input.toolCalls.filter((call) =>
+ /^(?:list-|get-|inspect-)/.test(call.name)
+ ).length,
+ },
+ };
+};
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 32e0e5df7a..c7746e864d 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -20,7 +20,9 @@
"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:release-smoke": "pnpm build && tsx --conditions=webstudio scripts/release-smoke.ts"
+ "test:release-smoke": "pnpm build && tsx --conditions=webstudio scripts/release-smoke.ts",
+ "test:release-smoke:model": "WEBSTUDIO_RELEASE_SMOKE_MODEL_EVAL_REQUIRED=1 pnpm test:release-smoke",
+ "test:release-smoke:registry": "tsx --conditions=webstudio scripts/release-smoke.ts"
},
"license": "AGPL-3.0-or-later",
"engines": {
diff --git a/packages/cli/scripts/release-smoke-report.test.ts b/packages/cli/scripts/release-smoke-report.test.ts
new file mode 100644
index 0000000000..bc5eed6c72
--- /dev/null
+++ b/packages/cli/scripts/release-smoke-report.test.ts
@@ -0,0 +1,312 @@
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, test, vi } from "vitest";
+import {
+ assertPrivacySafeArtifact,
+ compactTokenizer,
+ countCompactTokens,
+ createReleaseSmokeReporter,
+ getModelVerificationItemCount,
+ modelEvaluationReportSchema,
+ modelEvaluationSubmissionSchema,
+ publishedCliManifestContractSchema,
+ releaseSmokeReportSchema,
+} from "./release-smoke-report";
+
+const measurement = (
+ bytes: number,
+ tokens = bytes,
+ retries = 0,
+ failures = 0
+) => ({
+ bytes,
+ tokens,
+ attempts: 1 + retries,
+ retries,
+ failures,
+ fallbacks: { verbose: 0, fullResource: 0, source: 0 },
+});
+
+describe("comparative release smoke report", () => {
+ test("separates the same-candidate gate from incomparable history", () => {
+ const times = [100, 125, 180];
+ const reporter = createReleaseSmokeReporter({
+ now: () => times.shift() ?? 180,
+ writeLog: vi.fn(),
+ });
+ reporter.setSubjects({
+ candidate: { source: "local", version: "1.2.3" },
+ baseline: { source: "registry", version: "1.2.2" },
+ });
+ reporter.complete("candidate-install", 110);
+ reporter.recordOperation(
+ "list-pages",
+ measurement(80, 20),
+ measurement(160, 40),
+ measurement(60, 15)
+ );
+ reporter.setContract("candidateCompact", "passed");
+ reporter.setContract("candidateVerbose", "passed");
+ reporter.setContract("historicalBaselineCompact", "failed");
+
+ expect(reporter.createReport("passed")).toMatchObject({
+ schemaVersion: 4,
+ kind: "deterministic-compact-release-smoke",
+ outcome: "passed",
+ totalDurationMs: 80,
+ tokenizer: compactTokenizer,
+ candidateTokenBudget: 6_000,
+ sameCandidate: {
+ totals: {
+ compact: {
+ bytes: 80,
+ tokens: 20,
+ attempts: 1,
+ retries: 0,
+ failures: 0,
+ },
+ verbose: {
+ bytes: 160,
+ tokens: 40,
+ attempts: 1,
+ retries: 0,
+ failures: 0,
+ },
+ tokenDelta: -20,
+ retryDelta: 0,
+ failureDelta: 0,
+ },
+ },
+ historical: {
+ comparable: false,
+ operations: [{ operation: "list-pages", tokenDelta: null }],
+ totals: { tokenDelta: null },
+ },
+ checks: {
+ compactStrictlySmaller: "passed",
+ retryRegression: "passed",
+ failureRegression: "passed",
+ historicalComparable: "skipped",
+ },
+ });
+ expect(reporter.candidatePassesCompactRollout()).toBe(true);
+ });
+
+ test("publishes historical deltas only when both compact contracts pass", () => {
+ const reporter = createReleaseSmokeReporter({ writeLog: vi.fn() });
+ reporter.recordOperation(
+ "list-pages",
+ measurement(100, 25),
+ measurement(200, 50),
+ measurement(120, 30)
+ );
+ reporter.setContract("candidateCompact", "passed");
+ reporter.setContract("candidateVerbose", "passed");
+ reporter.setContract("historicalBaselineCompact", "passed");
+
+ const report = reporter.createReport("passed");
+ expect(report.historical).toMatchObject({
+ comparable: true,
+ operations: [{ tokenDelta: -5 }],
+ totals: { tokenDelta: -5 },
+ });
+ expect(report.checks.historicalComparable).toBe("passed");
+ });
+
+ test("gates token, retry, and failure regressions against candidate verbose", () => {
+ const reporter = createReleaseSmokeReporter({
+ candidateTokenBudget: 10,
+ writeLog: vi.fn(),
+ });
+ reporter.recordOperation(
+ "list-pages",
+ measurement(100, 11, 1, 1),
+ measurement(100, 11, 0, 0),
+ measurement(1, 1)
+ );
+ reporter.setContract("candidateCompact", "passed");
+ reporter.setContract("candidateVerbose", "passed");
+
+ expect(reporter.createReport("failed").checks).toMatchObject({
+ candidateTokenBudget: "failed",
+ compactStrictlySmaller: "failed",
+ retryRegression: "failed",
+ failureRegression: "failed",
+ });
+ expect(reporter.candidatePassesCompactRollout()).toBe(false);
+ });
+
+ test("uses a deterministic versioned tokenizer", () => {
+ expect(countCompactTokens('{"hello":"world"}')).toBe(11);
+ expect(countCompactTokens("cafe")).toBe(1);
+ expect(countCompactTokens("caf\u00e9")).toBe(2);
+ });
+
+ test("counts current and historical list response shapes", () => {
+ expect(
+ getModelVerificationItemCount("list-pages", {
+ ok: true,
+ data: { pages: [{ id: "home" }] },
+ })
+ ).toBe(1);
+ expect(
+ getModelVerificationItemCount("list-assets", {
+ ok: true,
+ items: [{ id: "logo" }, { id: "hero" }],
+ })
+ ).toBe(2);
+ expect(
+ getModelVerificationItemCount("list-assets", {
+ ok: true,
+ data: [{ id: "logo" }],
+ })
+ ).toBe(1);
+ });
+
+ test("records bounded performance evidence without payload fields", () => {
+ const reporter = createReleaseSmokeReporter({
+ now: () => 200,
+ writeLog: vi.fn(),
+ });
+ reporter.complete("rendered-audit", 100, {
+ rssBytes: 1_000,
+ heapUsedBytes: 500,
+ networkTransferBytes: 300,
+ retainedArtifactBytes: 200,
+ generatedBuildBytes: 400,
+ generatedBuildGzipBytes: 100,
+ });
+ expect(reporter.createReport("passed").phases[0]).toMatchObject({
+ phase: "rendered-audit",
+ durationMs: 100,
+ metrics: { rssBytes: 1_000, generatedBuildGzipBytes: 100 },
+ });
+ });
+
+ test("rejects raw payloads and private diagnostic fields", () => {
+ const report = createReleaseSmokeReporter({
+ writeLog: vi.fn(),
+ }).createReport("failed");
+ expect(releaseSmokeReportSchema.parse(report)).toEqual(report);
+ for (const field of ["authToken", "payload", "stdout", "errorMessage"]) {
+ expect(
+ releaseSmokeReportSchema.safeParse({ ...report, [field]: "private" })
+ .success
+ ).toBe(false);
+ }
+ });
+
+ test("validates the exact published manifest projection", () => {
+ const contract = {
+ name: "webstudio",
+ version: "1.2.3",
+ type: "module",
+ bin: { "webstudio-cli": "./bin.js", webstudio: "./bin.js" },
+ files: ["lib/*", "templates/*", "bin.js", "!*.{test,stories}.*"],
+ engines: { node: ">=22" },
+ };
+ expect(publishedCliManifestContractSchema.parse(contract)).toEqual(
+ contract
+ );
+ expect(
+ publishedCliManifestContractSchema.safeParse({
+ ...contract,
+ bin: { webstudio: "./other.js" },
+ }).success
+ ).toBe(false);
+ expect(
+ publishedCliManifestContractSchema.safeParse({
+ ...contract,
+ private: true,
+ }).success
+ ).toBe(false);
+ });
+
+ test("requires independent candidate and baseline model evidence", () => {
+ const submission = {
+ schemaVersion: 2,
+ taskId: "minimal-context-discovery-v2",
+ provider: "openai",
+ model: "gpt-5.1-codex",
+ outcome: "completed",
+ toolCallCount: 2,
+ observations: { pageCount: 2, assetCount: 1 },
+ };
+ expect(modelEvaluationSubmissionSchema.parse(submission)).toEqual(
+ submission
+ );
+ const run = {
+ subject: { source: "local", version: "1.2.3" },
+ evidence: {
+ source: "configured-agent-command",
+ provider: "openai",
+ model: "gpt-5.1-codex",
+ commandSha256: "a".repeat(64),
+ durationMs: 1_000,
+ exitCode: 0,
+ toolCallCount: 2,
+ },
+ observations: { pageCount: 2, assetCount: 1 },
+ checks: { submissionContract: "passed", projectOutcome: "passed" },
+ } as const;
+ const report = {
+ schemaVersion: 2,
+ kind: "model-driven-packaged-cli-evaluation",
+ outcome: "passed",
+ subjects: {
+ candidate: run.subject,
+ baseline: { source: "registry", version: "1.2.2" },
+ },
+ taskId: "minimal-context-discovery-v2",
+ runs: {
+ candidate: run,
+ baseline: {
+ ...run,
+ subject: { source: "registry", version: "1.2.2" },
+ },
+ },
+ checks: { bothOutcomes: "passed", canaryRedaction: "passed" },
+ } as const;
+ expect(modelEvaluationReportSchema.parse(report)).toEqual(report);
+ expect(
+ modelEvaluationReportSchema.safeParse({
+ ...report,
+ transcript: "private",
+ }).success
+ ).toBe(false);
+ expect(
+ modelEvaluationReportSchema.safeParse({
+ ...report,
+ runs: { candidate: run },
+ }).success
+ ).toBe(false);
+ });
+
+ test("scans reports for canaries and token-shaped secrets", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "release-smoke-report-"));
+ const path = join(directory, "report.json");
+ const canary = "release-smoke-secret-canary";
+ try {
+ const reporter = createReleaseSmokeReporter({
+ privacyCanary: canary,
+ writeLog: vi.fn(),
+ });
+ reporter.markCanaryExercised();
+ await reporter.write(path, "passed");
+ const source = await readFile(path, "utf8");
+ expect(source).not.toContain(canary);
+ expect(releaseSmokeReportSchema.parse(JSON.parse(source))).toMatchObject({
+ checks: { canaryRedaction: "passed" },
+ });
+ expect(() =>
+ assertPrivacySafeArtifact({ value: canary }, [canary])
+ ).toThrow("privacy redaction");
+ expect(() =>
+ assertPrivacySafeArtifact({ value: `npm_${"a".repeat(24)}` })
+ ).toThrow("token-shaped");
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/cli/scripts/release-smoke-report.ts b/packages/cli/scripts/release-smoke-report.ts
new file mode 100644
index 0000000000..0824d1e3c2
--- /dev/null
+++ b/packages/cli/scripts/release-smoke-report.ts
@@ -0,0 +1,589 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { dirname } from "node:path";
+import { z } from "zod";
+import { boundedIdentifierPattern } from "../src/type-utils";
+
+export const releaseSmokePhases = [
+ "fixture-api",
+ "package",
+ "candidate-install",
+ "baseline-install",
+ "compact-comparison",
+ "model-evaluation",
+ "audit-help",
+ "preview-start",
+ "agent-workflow",
+ "stdio-workflow",
+ "rendered-audit",
+ "cached-audit",
+ "structured-commands",
+ "cleanup",
+] as const;
+
+export const compactSmokeOperations = [
+ "list-pages",
+ "list-assets",
+ "list-instances",
+ "list-design-tokens",
+ "list-css-variables",
+ "list-variables",
+ "list-resources",
+] as const;
+
+export const compactTokenizer = {
+ implementation: "webstudio-json-lex",
+ version: "1.0.0",
+} as const;
+export const defaultCandidateTokenBudget = 6_000;
+
+export type ReleaseSmokePhase = (typeof releaseSmokePhases)[number];
+export type CompactSmokeOperation = (typeof compactSmokeOperations)[number];
+
+const byteCount = z.number().int().nonnegative();
+const count = z.number().int().nonnegative();
+const checkStatus = z.enum(["passed", "failed", "skipped"]);
+const safeIdentifier = z
+ .string()
+ .min(1)
+ .max(128)
+ .regex(boundedIdentifierPattern);
+
+export const countCompactTokens = (source: string) => {
+ let tokens = 0;
+ let asciiWordBytes = 0;
+ let whitespaceBytes = 0;
+ const flush = () => {
+ tokens += Math.ceil(asciiWordBytes / 4) + Math.ceil(whitespaceBytes / 4);
+ asciiWordBytes = 0;
+ whitespaceBytes = 0;
+ };
+ for (const character of source) {
+ if (/^[A-Za-z0-9_]$/.test(character)) {
+ if (whitespaceBytes > 0) {
+ flush();
+ }
+ asciiWordBytes += 1;
+ continue;
+ }
+ if (/^\s$/u.test(character)) {
+ if (asciiWordBytes > 0) {
+ flush();
+ }
+ whitespaceBytes += Buffer.byteLength(character, "utf8");
+ continue;
+ }
+ flush();
+ tokens += Math.max(1, Math.ceil(Buffer.byteLength(character, "utf8") / 2));
+ }
+ flush();
+ return tokens;
+};
+
+export const getModelVerificationItemCount = (
+ operation: "list-pages" | "list-assets",
+ structuredContent: unknown
+) => {
+ if (
+ typeof structuredContent !== "object" ||
+ structuredContent === null ||
+ Array.isArray(structuredContent)
+ ) {
+ throw new Error(`${operation} model verification response is invalid.`);
+ }
+ const response = structuredContent as Record<string, unknown>;
+ const payload = response.data ?? response;
+ const items = Array.isArray(payload)
+ ? payload
+ : typeof payload === "object" && payload !== null
+ ? (payload as Record<string, unknown>)[
+ operation === "list-pages" ? "pages" : "items"
+ ]
+ : undefined;
+ if (Array.isArray(items) === false) {
+ throw new Error(`${operation} model verification payload is invalid.`);
+ }
+ return items.length;
+};
+
+export const assertPrivacySafeArtifact = (
+ value: unknown,
+ canaries: readonly string[] = []
+) => {
+ const source = typeof value === "string" ? value : JSON.stringify(value);
+ const forbidden = [
+ ...canaries.filter((canary) => canary !== ""),
+ "authToken=",
+ "Authorization: Bearer ",
+ ];
+ if (forbidden.some((secret) => source.includes(secret))) {
+ throw new Error(
+ "Release smoke artifact failed privacy redaction scanning."
+ );
+ }
+ if (
+ /(?:^|[\"'\s])(npm_[A-Za-z0-9]{20,}|gh[opsu]_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9_-]{20,})/.test(
+ source
+ )
+ ) {
+ throw new Error("Release smoke artifact contains a token-shaped secret.");
+ }
+};
+
+export const publishedCliManifestContractSchema = z
+ .object({
+ name: z.literal("webstudio"),
+ version: z.string().min(1).max(128),
+ type: z.literal("module"),
+ bin: z
+ .object({
+ "webstudio-cli": z.literal("./bin.js"),
+ webstudio: z.literal("./bin.js"),
+ })
+ .strict(),
+ files: z.tuple([
+ z.literal("lib/*"),
+ z.literal("templates/*"),
+ z.literal("bin.js"),
+ z.literal("!*.{test,stories}.*"),
+ ]),
+ engines: z.object({ node: z.literal(">=22") }).strict(),
+ })
+ .strict();
+
+export const releaseSmokeMetricsSchema = z
+ .object({
+ rssBytes: byteCount.optional(),
+ heapUsedBytes: byteCount.optional(),
+ networkTransferBytes: byteCount.optional(),
+ retainedArtifactBytes: byteCount.optional(),
+ generatedBuildBytes: byteCount.optional(),
+ generatedBuildGzipBytes: byteCount.optional(),
+ })
+ .strict();
+
+const operationMeasurementFields = {
+ bytes: byteCount,
+ tokens: count,
+ attempts: count,
+ retries: count,
+ failures: count,
+};
+
+export const compactOperationMeasurementSchema = z
+ .object({
+ ...operationMeasurementFields,
+ fallbacks: z
+ .object({
+ verbose: count,
+ fullResource: count,
+ source: count,
+ })
+ .strict(),
+ })
+ .strict();
+
+const aggregateMeasurementSchema = z
+ .object(operationMeasurementFields)
+ .strict();
+
+const releaseSubjectSchema = z
+ .object({
+ source: z.enum(["local", "registry"]),
+ version: z.string().min(1).max(128),
+ })
+ .strict();
+
+export type ReleaseSmokeMetrics = z.infer<typeof releaseSmokeMetricsSchema>;
+export type CompactOperationMeasurement = z.infer<
+ typeof compactOperationMeasurementSchema
+>;
+export type ReleaseSubject = z.infer<typeof releaseSubjectSchema>;
+
+const comparisonOperationSchema = z
+ .object({
+ operation: z.enum(compactSmokeOperations),
+ compact: compactOperationMeasurementSchema,
+ verbose: compactOperationMeasurementSchema,
+ tokenDelta: z.number().int(),
+ retryDelta: z.number().int(),
+ failureDelta: z.number().int(),
+ })
+ .strict();
+
+const historicalOperationSchema = z
+ .object({
+ operation: z.enum(compactSmokeOperations),
+ candidate: compactOperationMeasurementSchema,
+ baseline: compactOperationMeasurementSchema,
+ tokenDelta: z.number().int().nullable(),
+ })
+ .strict();
+
+export const releaseSmokeReportSchema = z
+ .object({
+ schemaVersion: z.literal(4),
+ kind: z.literal("deterministic-compact-release-smoke"),
+ outcome: z.enum(["passed", "failed"]),
+ totalDurationMs: count,
+ subjects: z
+ .object({
+ candidate: releaseSubjectSchema,
+ baseline: releaseSubjectSchema,
+ })
+ .strict(),
+ tokenizer: z
+ .object({
+ implementation: z.literal(compactTokenizer.implementation),
+ version: z.literal(compactTokenizer.version),
+ })
+ .strict(),
+ candidateTokenBudget: count.positive(),
+ sameCandidate: z
+ .object({
+ operations: z.array(comparisonOperationSchema),
+ totals: z
+ .object({
+ compact: aggregateMeasurementSchema,
+ verbose: aggregateMeasurementSchema,
+ tokenDelta: z.number().int(),
+ retryDelta: z.number().int(),
+ failureDelta: z.number().int(),
+ })
+ .strict(),
+ })
+ .strict(),
+ historical: z
+ .object({
+ comparable: z.boolean(),
+ operations: z.array(historicalOperationSchema),
+ totals: z
+ .object({
+ candidate: aggregateMeasurementSchema,
+ baseline: aggregateMeasurementSchema,
+ tokenDelta: z.number().int().nullable(),
+ })
+ .strict(),
+ })
+ .strict(),
+ phases: z.array(
+ z
+ .object({
+ phase: z.enum(releaseSmokePhases),
+ durationMs: count,
+ metrics: releaseSmokeMetricsSchema.optional(),
+ })
+ .strict()
+ ),
+ checks: z
+ .object({
+ contracts: z
+ .object({
+ candidateCompact: checkStatus,
+ candidateVerbose: checkStatus,
+ historicalBaselineCompact: checkStatus,
+ })
+ .strict(),
+ candidateTokenBudget: checkStatus,
+ compactStrictlySmaller: checkStatus,
+ retryRegression: checkStatus,
+ failureRegression: checkStatus,
+ historicalComparable: checkStatus,
+ canaryRedaction: checkStatus,
+ registryArtifact: checkStatus,
+ })
+ .strict(),
+ })
+ .strict();
+
+export type ReleaseSmokeReport = z.infer<typeof releaseSmokeReportSchema>;
+
+export const modelEvaluationTaskId = "minimal-context-discovery-v2" as const;
+export const modelEvaluationSubmissionSchema = z
+ .object({
+ schemaVersion: z.literal(2),
+ taskId: z.literal(modelEvaluationTaskId),
+ provider: safeIdentifier,
+ model: safeIdentifier,
+ outcome: z.enum(["completed", "failed"]),
+ toolCallCount: count,
+ observations: z.object({ pageCount: count, assetCount: count }).strict(),
+ })
+ .strict();
+
+const modelRunSchema = z
+ .object({
+ subject: releaseSubjectSchema,
+ evidence: z
+ .object({
+ source: z.literal("configured-agent-command"),
+ provider: safeIdentifier,
+ model: safeIdentifier,
+ commandSha256: z.string().regex(/^[a-f0-9]{64}$/),
+ durationMs: count,
+ exitCode: z.number().int(),
+ toolCallCount: count,
+ })
+ .strict(),
+ observations: z.object({ pageCount: count, assetCount: count }).strict(),
+ checks: z
+ .object({ submissionContract: checkStatus, projectOutcome: checkStatus })
+ .strict(),
+ })
+ .strict();
+
+export const modelEvaluationReportSchema = z
+ .object({
+ schemaVersion: z.literal(2),
+ kind: z.literal("model-driven-packaged-cli-evaluation"),
+ outcome: z.enum(["passed", "failed"]),
+ subjects: z
+ .object({
+ candidate: releaseSubjectSchema,
+ baseline: releaseSubjectSchema,
+ })
+ .strict(),
+ taskId: z.literal(modelEvaluationTaskId),
+ runs: z
+ .object({ candidate: modelRunSchema, baseline: modelRunSchema })
+ .strict(),
+ checks: z
+ .object({ bothOutcomes: checkStatus, canaryRedaction: checkStatus })
+ .strict(),
+ })
+ .strict();
+
+export type ModelEvaluationReport = z.infer<typeof modelEvaluationReportSchema>;
+
+const unknownSubject: ReleaseSubject = {
+ source: "local",
+ version: "unresolved",
+};
+
+export const writeModelEvaluationReport = async (
+ path: string,
+ report: ModelEvaluationReport,
+ canaries: readonly string[] = []
+) => {
+ const parsed = modelEvaluationReportSchema.parse(report);
+ assertPrivacySafeArtifact(parsed, canaries);
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(path, `${JSON.stringify(parsed, undefined, 2)}\n`, "utf8");
+};
+
+const aggregateMeasurements = (
+ values: readonly CompactOperationMeasurement[]
+) =>
+ values.reduce(
+ (total, value) => ({
+ bytes: total.bytes + value.bytes,
+ tokens: total.tokens + value.tokens,
+ attempts: total.attempts + value.attempts,
+ retries: total.retries + value.retries,
+ failures: total.failures + value.failures,
+ }),
+ { bytes: 0, tokens: 0, attempts: 0, retries: 0, failures: 0 }
+ );
+
+export const createReleaseSmokeReporter = ({
+ now = Date.now,
+ writeLog = (message: string) => process.stderr.write(message),
+ privacyCanary = "",
+ candidateTokenBudget = defaultCandidateTokenBudget,
+}: {
+ now?: () => number;
+ writeLog?: (message: string) => void;
+ privacyCanary?: string;
+ candidateTokenBudget?: number;
+} = {}) => {
+ const parsedCandidateTokenBudget = count
+ .positive()
+ .parse(candidateTokenBudget);
+ const startedAt = now();
+ const phases: ReleaseSmokeReport["phases"] = [];
+ const sameCandidateOperations: ReleaseSmokeReport["sameCandidate"]["operations"] =
+ [];
+ const historicalMeasurements: Array<{
+ operation: CompactSmokeOperation;
+ candidate: CompactOperationMeasurement;
+ baseline: CompactOperationMeasurement;
+ }> = [];
+ let subjects: ReleaseSmokeReport["subjects"] = {
+ candidate: unknownSubject,
+ baseline: unknownSubject,
+ };
+ let contracts: ReleaseSmokeReport["checks"]["contracts"] = {
+ candidateCompact: "failed",
+ candidateVerbose: "failed",
+ historicalBaselineCompact: "failed",
+ };
+ let registryArtifact: ReleaseSmokeReport["checks"]["registryArtifact"] =
+ "skipped";
+ let canaryExercised = false;
+
+ const getComparisons = () => {
+ const compact = aggregateMeasurements(
+ sameCandidateOperations.map((operation) => operation.compact)
+ );
+ const verbose = aggregateMeasurements(
+ sameCandidateOperations.map((operation) => operation.verbose)
+ );
+ const comparable =
+ contracts.candidateCompact === "passed" &&
+ contracts.historicalBaselineCompact === "passed";
+ const historicalCandidate = aggregateMeasurements(
+ historicalMeasurements.map((operation) => operation.candidate)
+ );
+ const historicalBaseline = aggregateMeasurements(
+ historicalMeasurements.map((operation) => operation.baseline)
+ );
+ return {
+ sameCandidate: {
+ operations: sameCandidateOperations,
+ totals: {
+ compact,
+ verbose,
+ tokenDelta: compact.tokens - verbose.tokens,
+ retryDelta: compact.retries - verbose.retries,
+ failureDelta: compact.failures - verbose.failures,
+ },
+ },
+ historical: {
+ comparable,
+ operations: historicalMeasurements.map((operation) => ({
+ ...operation,
+ tokenDelta: comparable
+ ? operation.candidate.tokens - operation.baseline.tokens
+ : null,
+ })),
+ totals: {
+ candidate: historicalCandidate,
+ baseline: historicalBaseline,
+ tokenDelta: comparable
+ ? historicalCandidate.tokens - historicalBaseline.tokens
+ : null,
+ },
+ },
+ };
+ };
+
+ const createReport = (
+ outcome: ReleaseSmokeReport["outcome"],
+ canaryRedaction: ReleaseSmokeReport["checks"]["canaryRedaction"] = "skipped"
+ ): ReleaseSmokeReport => {
+ const comparisons = getComparisons();
+ const totals = comparisons.sameCandidate.totals;
+ const retryRegression = sameCandidateOperations.some(
+ (operation) => operation.retryDelta > 0
+ );
+ const failureRegression = sameCandidateOperations.some(
+ (operation) => operation.failureDelta > 0
+ );
+ return releaseSmokeReportSchema.parse({
+ schemaVersion: 4,
+ kind: "deterministic-compact-release-smoke",
+ outcome,
+ totalDurationMs: Math.max(0, now() - startedAt),
+ subjects,
+ tokenizer: compactTokenizer,
+ candidateTokenBudget: parsedCandidateTokenBudget,
+ ...comparisons,
+ phases,
+ checks: {
+ contracts,
+ candidateTokenBudget:
+ totals.compact.tokens <= parsedCandidateTokenBudget
+ ? "passed"
+ : "failed",
+ compactStrictlySmaller:
+ totals.compact.tokens < totals.verbose.tokens ? "passed" : "failed",
+ retryRegression: retryRegression ? "failed" : "passed",
+ failureRegression: failureRegression ? "failed" : "passed",
+ historicalComparable: comparisons.historical.comparable
+ ? "passed"
+ : "skipped",
+ canaryRedaction,
+ registryArtifact,
+ },
+ });
+ };
+
+ return {
+ complete(
+ phase: ReleaseSmokePhase,
+ phaseStartedAt = now(),
+ metrics?: ReleaseSmokeMetrics
+ ) {
+ const durationMs = Math.max(0, now() - phaseStartedAt);
+ phases.push({
+ phase,
+ durationMs,
+ ...(metrics === undefined ? {} : { metrics }),
+ });
+ writeLog(`[release-smoke] ${phase} (${durationMs}ms)\n`);
+ },
+ setSubjects(value: ReleaseSmokeReport["subjects"]) {
+ subjects = releaseSmokeReportSchema.shape.subjects.parse(value);
+ },
+ setContract(
+ target: keyof ReleaseSmokeReport["checks"]["contracts"],
+ status: ReleaseSmokeReport["checks"]["contracts"][typeof target]
+ ) {
+ contracts = { ...contracts, [target]: status };
+ },
+ setRegistryArtifact(
+ status: ReleaseSmokeReport["checks"]["registryArtifact"]
+ ) {
+ registryArtifact = status;
+ },
+ markCanaryExercised() {
+ canaryExercised = true;
+ },
+ recordOperation(
+ operation: CompactSmokeOperation,
+ compact: CompactOperationMeasurement,
+ verbose: CompactOperationMeasurement,
+ historicalBaseline: CompactOperationMeasurement
+ ) {
+ const parsedCompact = compactOperationMeasurementSchema.parse(compact);
+ const parsedVerbose = compactOperationMeasurementSchema.parse(verbose);
+ const parsedHistoricalBaseline =
+ compactOperationMeasurementSchema.parse(historicalBaseline);
+ sameCandidateOperations.push({
+ operation,
+ compact: parsedCompact,
+ verbose: parsedVerbose,
+ tokenDelta: parsedCompact.tokens - parsedVerbose.tokens,
+ retryDelta: parsedCompact.retries - parsedVerbose.retries,
+ failureDelta: parsedCompact.failures - parsedVerbose.failures,
+ });
+ historicalMeasurements.push({
+ operation,
+ candidate: parsedCompact,
+ baseline: parsedHistoricalBaseline,
+ });
+ },
+ candidatePassesCompactRollout() {
+ const report = createReport("failed");
+ return (
+ report.checks.contracts.candidateCompact === "passed" &&
+ report.checks.contracts.candidateVerbose === "passed" &&
+ report.checks.candidateTokenBudget === "passed" &&
+ report.checks.compactStrictlySmaller === "passed" &&
+ report.checks.retryRegression === "passed" &&
+ report.checks.failureRegression === "passed"
+ );
+ },
+ createReport,
+ async write(path: string, outcome: ReleaseSmokeReport["outcome"]) {
+ const report = createReport(
+ outcome,
+ canaryExercised ? "passed" : "skipped"
+ );
+ assertPrivacySafeArtifact(report, [privacyCanary]);
+ const source = `${JSON.stringify(report, undefined, 2)}\n`;
+ releaseSmokeReportSchema.parse(JSON.parse(source));
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(path, source, "utf8");
+ },
+ };
+};
diff --git a/packages/cli/scripts/release-smoke.ts b/packages/cli/scripts/release-smoke.ts
index 1448c850d3..eb770ae47c 100644
--- a/packages/cli/scripts/release-smoke.ts
+++ b/packages/cli/scripts/release-smoke.ts
@@ -1,6 +1,5 @@
import { execFile, spawn, type ChildProcess } from "node:child_process";
-import { randomUUID } from "node:crypto";
-import { createServer, type Server } from "node:http";
+import { createHash, randomUUID } from "node:crypto";
import {
cp,
mkdir,
@@ -8,17 +7,13 @@ import {
readFile,
readdir,
rm,
+ stat,
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 { bundleVersion } from "@webstudio-is/protocol";
import type { Instance } from "@webstudio-is/sdk";
import type { BuilderState } from "@webstudio-is/project-build/state";
import type { BuilderPatchTransaction } from "@webstudio-is/project-build/contracts";
@@ -26,6 +21,28 @@ import type { BuilderRuntimeMutation } from "@webstudio-is/project-build/runtime
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import React from "react";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
+import {
+ compactSmokeOperations,
+ countCompactTokens,
+ createReleaseSmokeReporter,
+ defaultCandidateTokenBudget,
+ getModelVerificationItemCount,
+ modelEvaluationReportSchema,
+ modelEvaluationSubmissionSchema,
+ modelEvaluationTaskId,
+ publishedCliManifestContractSchema,
+ writeModelEvaluationReport,
+ type CompactOperationMeasurement,
+ type CompactSmokeOperation,
+} from "./release-smoke-report";
+import {
+ createRuntimeFixtureBuildSnapshot,
+ createRuntimeFixtureSerializedBuild,
+ runtimeFixturePermissions,
+ startRuntimeFixtureApi,
+} from "./runtime-fixture-api";
+import { runAgentCommand } from "./run-agent-command";
+import { isPlainRecord } from "../src/type-utils";
const execFileAsync = promisify(execFile);
const projectId = "release-smoke-project";
@@ -33,16 +50,185 @@ const buildId = "release-smoke-build";
const projectVersion = 1;
const sessionVersion = "cli-project-session-v1";
const releaseVersionPlaceholder = "0.0.0-webstudio-version";
+const privacyCanary = "releaseSmokePrivateCanaryAuthTokenDoNotReport";
+const duplicatedPage = { name: "About", path: "/about" } as const;
+const createdPageInputs = [
+ { name: "Services", path: "/services" },
+ { name: "Work", path: "/work" },
+ { name: "Blog", path: "/blog" },
+ { name: "Contact", path: "/contact" },
+] as const;
+const additionalPageCount = 1 + createdPageInputs.length;
const agentSmokeClients = [
{ connect: "claude", name: "claude-code" },
{ connect: "codex", name: "codex" },
{ connect: "cursor", name: "cursor" },
+ { connect: "vscode", name: "vscode" },
] as const;
-const reportPhase = (phase: string, startedAt = Date.now()) => {
- process.stderr.write(
- `[release-smoke] ${phase} (${Date.now() - startedAt}ms)\n`
+const configuredTokenBudget = Number(
+ process.env.WEBSTUDIO_RELEASE_SMOKE_TOKEN_BUDGET ??
+ defaultCandidateTokenBudget
+);
+const reporter = createReleaseSmokeReporter({
+ privacyCanary,
+ candidateTokenBudget: configuredTokenBudget,
+});
+const reportPhase = reporter.complete;
+
+type ReleaseTarget = {
+ source: "local" | "registry";
+ version: string;
+ installSpec: string;
+ integrity?: string;
+};
+
+const readNpmJson = async (args: string[]) =>
+ JSON.parse((await execFileAsync("npm", args)).stdout) as unknown;
+
+const resolveRegistryTarget = async (spec: string): Promise<ReleaseTarget> => {
+ const version = await readNpmJson(["view", spec, "version", "--json"]);
+ const integrity = await readNpmJson([
+ "view",
+ spec,
+ "dist.integrity",
+ "--json",
+ ]);
+ if (typeof version !== "string" || version.length === 0) {
+ throw new Error(`Could not resolve registry package ${spec}.`);
+ }
+ if (typeof integrity !== "string" || integrity.length === 0) {
+ throw new Error(`Registry package webstudio@${version} has no integrity.`);
+ }
+ return {
+ source: "registry",
+ version,
+ installSpec: `webstudio@${version}`,
+ integrity,
+ };
+};
+
+const installReleaseTarget = async ({
+ directory,
+ target,
+ enforceArtifactContract = false,
+}: {
+ directory: string;
+ target: ReleaseTarget;
+ enforceArtifactContract?: boolean;
+}) => {
+ await writeFile(
+ join(directory, "package.json"),
+ JSON.stringify({ private: true }),
+ "utf8"
+ );
+ const install = await execFileAsync(
+ "npm",
+ [
+ "install",
+ target.installSpec,
+ "--no-audit",
+ "--no-fund",
+ "--loglevel=warn",
+ ],
+ { cwd: directory, maxBuffer: 10 * 1024 * 1024 }
);
+ if (/ERESOLVE|overriding peer dependency/i.test(install.stderr)) {
+ throw new Error(
+ `npm install emitted peer dependency warnings for ${target.source} ${target.version}.`
+ );
+ }
+ const installedManifest = JSON.parse(
+ await readFile(
+ join(directory, "node_modules", "webstudio", "package.json"),
+ "utf8"
+ )
+ ) as Record<string, unknown>;
+ if (installedManifest.version !== target.version) {
+ throw new Error(
+ `Clean install resolved webstudio ${String(installedManifest.version)} instead of ${target.version}.`
+ );
+ }
+ if (enforceArtifactContract) {
+ publishedCliManifestContractSchema.parse({
+ name: installedManifest.name,
+ version: installedManifest.version,
+ type: installedManifest.type,
+ bin: installedManifest.bin,
+ files: installedManifest.files,
+ engines: installedManifest.engines,
+ });
+ const packageDirectory = join(directory, "node_modules", "webstudio");
+ const packageEntries = new Set(await readdir(packageDirectory));
+ for (const requiredEntry of [
+ "bin.js",
+ "lib",
+ "package.json",
+ "templates",
+ ]) {
+ if (packageEntries.has(requiredEntry) === false) {
+ throw new Error(
+ `Installed webstudio artifact is missing required entry ${requiredEntry}.`
+ );
+ }
+ }
+ const allowedTopLevelEntries = new Set([
+ "LICENSE",
+ "README.md",
+ "bin.js",
+ "lib",
+ "package.json",
+ "templates",
+ ]);
+ const unexpectedEntry = Array.from(packageEntries).find(
+ (entry) => allowedTopLevelEntries.has(entry) === false
+ );
+ if (unexpectedEntry !== undefined) {
+ throw new Error(
+ `Installed webstudio artifact contains unexpected top-level entry ${unexpectedEntry}.`
+ );
+ }
+ const scanTree = async (path: string, relativePath = "") => {
+ for (const entry of await readdir(path, { withFileTypes: true })) {
+ const entryPath = join(path, entry.name);
+ const relativeEntryPath = join(relativePath, entry.name);
+ if (entry.isSymbolicLink()) {
+ throw new Error(
+ `Installed webstudio artifact contains symlink ${relativeEntryPath}.`
+ );
+ }
+ if (
+ /(?:^|\/)(?:\.env(?:\.|$)|\.npmrc$)|\.(?:map|test\.[^.]+|stories\.[^.]+)$/i.test(
+ relativeEntryPath
+ )
+ ) {
+ throw new Error(
+ `Installed webstudio artifact contains forbidden file ${relativeEntryPath}.`
+ );
+ }
+ if (entry.isDirectory()) {
+ await scanTree(entryPath, relativeEntryPath);
+ }
+ }
+ };
+ await scanTree(packageDirectory);
+ const executable = await stat(join(packageDirectory, "bin.js"));
+ if (executable.isFile() === false || (executable.mode & 0o111) === 0) {
+ throw new Error("Installed webstudio bin.js is not executable.");
+ }
+ }
+ if (target.integrity !== undefined) {
+ const lock = JSON.parse(
+ await readFile(join(directory, "package-lock.json"), "utf8")
+ ) as { packages?: Record<string, { integrity?: unknown }> };
+ const installedIntegrity =
+ lock.packages?.["node_modules/webstudio"]?.integrity;
+ if (installedIntegrity !== target.integrity) {
+ throw new Error(
+ `Installed webstudio integrity ${String(installedIntegrity)} does not match registry metadata.`
+ );
+ }
+ }
};
const runAgentWorkflowStep = async <Result>({
@@ -133,9 +319,11 @@ const replaceReleaseVersion = async (
const packReleaseShapedCli = async ({
stagingDirectory,
packDirectory,
+ releaseVersion,
}: {
stagingDirectory: string;
packDirectory: string;
+ releaseVersion: string;
}) => {
const cliDirectory = join(import.meta.dirname, "..");
await Promise.all(
@@ -145,12 +333,6 @@ const packReleaseShapedCli = async ({
})
)
);
- 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.");
}
@@ -216,7 +398,7 @@ const createFixture = () => {
{
id: "home",
name: "Home",
- title: "Home",
+ title: privacyCanary,
path: "",
rootInstanceId: "home-root",
meta: {},
@@ -231,7 +413,7 @@ const createFixture = () => {
},
];
const extraPageCount =
- process.env.WEBSTUDIO_RELEASE_SMOKE_LARGE_AUDIT === "1" ? 120 : 0;
+ process.env.WEBSTUDIO_RELEASE_SMOKE_LARGE_AUDIT === "1" ? 114 : 0;
const pages = [
...basePages,
...Array.from({ length: extraPageCount }, (_, index) => {
@@ -396,35 +578,12 @@ const stopProcessTree = async (child: ChildProcess | undefined) => {
}
};
-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: {
@@ -441,24 +600,28 @@ const startFixtureApi = async (
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"
- )
- ) {
+ const getCurrentBuildSnapshot = () =>
+ createRuntimeFixtureBuildSnapshot({
+ state,
+ projectId,
+ buildId,
+ version,
+ });
+ const getCurrentSerializedBuild = () =>
+ createRuntimeFixtureSerializedBuild({
+ state,
+ baseBuild: fixture.build,
+ buildId,
+ version,
+ });
+ return startRuntimeFixtureApi(
+ async ({ pathname, response, operationPath, readInput }) => {
+ if (pathname.endsWith("/release-hero.png")) {
response.writeHead(200, { "content-type": "image/png" });
response.end(
Buffer.from(
@@ -466,15 +629,11 @@ const startFixtureApi = async (
"base64"
)
);
- return;
+ return undefined;
}
- const operationPath = new URL(
- requestUrl,
- "http://127.0.0.1"
- ).pathname.replace(/^\/trpc\/(?:api\.)?/, "");
let data: unknown;
if (operationPath === "build.loadProjectBundleByProjectId") {
- data = fixture.data;
+ data = { ...fixture.data, build: getCurrentSerializedBuild() };
} else if (operationPath === "projects.get") {
data = {
id: projectId,
@@ -489,45 +648,19 @@ const startFixtureApi = async (
} else if (operationPath === "publish.create") {
data = { jobId: "release-smoke-staging-job" };
} else if (operationPath === "build.patch") {
- const input = (await readTrpcInput(request)) as {
+ const input = (await readInput()) 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,
- };
+ data = getCurrentBuildSnapshot();
} else if (
operationPath !== "projects.permissions" &&
operationPath !== ""
) {
- const input = await readTrpcInput(request);
+ const input = await readInput();
const result = await executeRuntime({
id: operationPath,
state,
@@ -557,58 +690,11 @@ const startFixtureApi = async (
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]
- : []
- ),
- },
- };
+ data = runtimeFixturePermissions;
}
- 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 },
- },
- },
- ])
- );
+ return data;
}
- });
- 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) => {
@@ -626,6 +712,429 @@ const getRecord = (value: unknown, label: string) => {
return value as Record<string, unknown>;
};
+const createMcpSmokeClient = ({
+ bin,
+ cwd,
+ env,
+ name,
+}: {
+ bin: string;
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+ name: string;
+}) => {
+ const transport = new StdioClientTransport({
+ command: bin,
+ args: ["mcp"],
+ cwd,
+ env: Object.fromEntries(
+ Object.entries(env).filter(
+ (entry): entry is [string, string] => typeof entry[1] === "string"
+ )
+ ),
+ stderr: "pipe",
+ });
+ const client = new Client({ name, version: "1.0.0" });
+ return { client, transport };
+};
+
+const emptyFallbackCounts = () => ({
+ verbose: 0,
+ fullResource: 0,
+ source: 0,
+});
+
+const runCompactMeasurementSuite = async ({
+ bin,
+ cwd,
+ env,
+ expectedDetail,
+}: {
+ bin: string;
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+ expectedDetail: "compact" | "verbose";
+}) => {
+ const { client, transport } = createMcpSmokeClient({
+ bin,
+ cwd,
+ env,
+ name: "webstudio-release-smoke-compact-measurement",
+ });
+ const measurements = new Map<
+ CompactSmokeOperation,
+ CompactOperationMeasurement
+ >();
+ const contractFailures: CompactSmokeOperation[] = [];
+ let canarySeen = false;
+ await client.connect(transport);
+ try {
+ for (const operation of compactSmokeOperations) {
+ let attempts = 0;
+ let failures = 0;
+ let bytes = 0;
+ let tokens = 0;
+ const fallbacks = emptyFallbackCounts();
+ let passed = false;
+ for (let attempt = 0; attempt < 2 && passed === false; attempt += 1) {
+ attempts += 1;
+ try {
+ const result = await client.callTool({
+ name: operation,
+ arguments: {
+ limit: 25,
+ ...(expectedDetail === "verbose" ? { verbose: true } : {}),
+ },
+ });
+ const source = JSON.stringify(result.structuredContent);
+ canarySeen ||= source.includes(privacyCanary);
+ const structured = getRecord(
+ result.structuredContent,
+ `${operation} compact structured content`
+ );
+ const data = getRecord(
+ structured.data,
+ `${operation} compact response data`
+ );
+ if (result.isError === true || structured.ok !== true) {
+ throw new Error(`${expectedDetail} operation failed`);
+ }
+ bytes = Buffer.byteLength(source, "utf8");
+ tokens = countCompactTokens(source);
+ if (data.detail !== expectedDetail) {
+ contractFailures.push(operation);
+ if (data.detail === "verbose") {
+ fallbacks.verbose += 1;
+ }
+ }
+ passed = true;
+ } catch {
+ failures += 1;
+ }
+ }
+ measurements.set(operation, {
+ bytes,
+ tokens,
+ attempts,
+ retries: Math.max(0, attempts - 1),
+ failures,
+ fallbacks,
+ });
+ if (passed === false) {
+ contractFailures.push(operation);
+ }
+ }
+ } finally {
+ await client.close();
+ }
+ return { measurements, contractFailures, canarySeen };
+};
+
+const verifyModelEvaluationOutcome = async ({
+ bin,
+ cwd,
+ env,
+}: {
+ bin: string;
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+}) => {
+ const { client, transport } = createMcpSmokeClient({
+ bin,
+ cwd,
+ env,
+ name: "webstudio-release-smoke-model-verifier",
+ });
+ await client.connect(transport);
+ try {
+ const countItems = async (operation: "list-pages" | "list-assets") => {
+ let result = await client.callTool({
+ name: operation,
+ arguments: { limit: 25 },
+ });
+ if (result.isError === true) {
+ result = await client.callTool({ name: operation, arguments: {} });
+ }
+ const structured = getRecord(
+ result.structuredContent,
+ `${operation} model evaluation verification response`
+ );
+ if (result.isError === true || structured.ok === false) {
+ throw new Error(`${operation} model evaluation verification failed.`);
+ }
+ return getModelVerificationItemCount(operation, structured);
+ };
+ return {
+ pageCount: await countItems("list-pages"),
+ assetCount: await countItems("list-assets"),
+ };
+ } finally {
+ await client.close();
+ }
+};
+
+const runSingleModelEvaluation = async ({
+ targetName,
+ command,
+ subject,
+ bin,
+ projectDirectory,
+ configDirectory,
+ temp,
+}: {
+ targetName: "candidate" | "baseline";
+ command: string;
+ subject: ReleaseTarget;
+ bin: string;
+ projectDirectory: string;
+ configDirectory: string;
+ temp: string;
+}) => {
+ const evaluationDirectory = join(
+ temp,
+ `model-evaluation-${targetName}-project`
+ );
+ const evaluationConfigDirectory = join(
+ temp,
+ `model-evaluation-${targetName}-config`
+ );
+ const taskPath = join(temp, `model-evaluation-${targetName}-task.json`);
+ const submissionPath = join(
+ temp,
+ `model-evaluation-${targetName}-submission.json`
+ );
+ await Promise.all([
+ cp(projectDirectory, evaluationDirectory, { recursive: true }),
+ cp(configDirectory, evaluationConfigDirectory, { recursive: true }),
+ ]);
+ const task = {
+ schemaVersion: 2,
+ taskId: modelEvaluationTaskId,
+ objective:
+ "Using only the packaged Webstudio MCP server, determine the exact number of pages and assets in the linked project. Choose the minimal tool sequence yourself.",
+ mcp: { command: bin, args: ["mcp"], cwd: evaluationDirectory },
+ resultPath: submissionPath,
+ resultContract: {
+ schemaVersion: 2,
+ taskId: modelEvaluationTaskId,
+ provider: "agent provider identifier",
+ model: "agent model identifier",
+ outcome: "completed or failed",
+ toolCallCount: "non-negative integer",
+ observations: {
+ pageCount: "non-negative integer",
+ assetCount: "non-negative integer",
+ },
+ },
+ };
+ await writeFile(taskPath, JSON.stringify(task, undefined, 2), "utf8");
+ const evaluationEnv = {
+ ...process.env,
+ WEBSTUDIO_CONFIG_DIR: evaluationConfigDirectory,
+ WEBSTUDIO_RELEASE_SMOKE_AGENT_TASK: taskPath,
+ WEBSTUDIO_RELEASE_SMOKE_AGENT_RESULT: submissionPath,
+ WEBSTUDIO_RELEASE_SMOKE_MCP_COMMAND: bin,
+ WEBSTUDIO_RELEASE_SMOKE_MCP_CWD: evaluationDirectory,
+ WEBSTUDIO_RELEASE_SMOKE_MODEL_TARGET: targetName,
+ };
+ const execution = await runAgentCommand({
+ command,
+ cwd: evaluationDirectory,
+ env: evaluationEnv,
+ timeoutMs: 10 * 60_000,
+ });
+ const submission = modelEvaluationSubmissionSchema.parse(
+ JSON.parse(await readFile(submissionPath, "utf8"))
+ );
+ const verifiedObservations = await verifyModelEvaluationOutcome({
+ bin,
+ cwd: evaluationDirectory,
+ env: evaluationEnv,
+ });
+ const projectOutcome =
+ submission.observations.pageCount === verifiedObservations.pageCount &&
+ submission.observations.assetCount === verifiedObservations.assetCount;
+ const passed =
+ execution.exitCode === 0 &&
+ submission.outcome === "completed" &&
+ projectOutcome;
+ return {
+ passed,
+ run: {
+ subject: { source: subject.source, version: subject.version },
+ evidence: {
+ source: "configured-agent-command" as const,
+ provider: submission.provider,
+ model: submission.model,
+ commandSha256: createHash("sha256").update(command).digest("hex"),
+ durationMs: execution.durationMs,
+ exitCode: execution.exitCode,
+ toolCallCount: submission.toolCallCount,
+ },
+ observations: submission.observations,
+ checks: {
+ submissionContract: "passed" as const,
+ projectOutcome: projectOutcome
+ ? ("passed" as const)
+ : ("failed" as const),
+ },
+ },
+ };
+};
+
+const runModelEvaluation = async ({
+ command,
+ reportPath,
+ candidate,
+ baseline,
+ candidateBin,
+ baselineBin,
+ candidateProjectDirectory,
+ baselineProjectDirectory,
+ candidateConfigDirectory,
+ baselineConfigDirectory,
+ temp,
+}: {
+ command: string;
+ reportPath: string;
+ candidate: ReleaseTarget;
+ baseline: ReleaseTarget;
+ candidateBin: string;
+ baselineBin: string;
+ candidateProjectDirectory: string;
+ baselineProjectDirectory: string;
+ candidateConfigDirectory: string;
+ baselineConfigDirectory: string;
+ temp: string;
+}) => {
+ const results = await Promise.allSettled([
+ runSingleModelEvaluation({
+ targetName: "candidate",
+ command,
+ subject: candidate,
+ bin: candidateBin,
+ projectDirectory: candidateProjectDirectory,
+ configDirectory: candidateConfigDirectory,
+ temp,
+ }),
+ runSingleModelEvaluation({
+ targetName: "baseline",
+ command,
+ subject: baseline,
+ bin: baselineBin,
+ projectDirectory: baselineProjectDirectory,
+ configDirectory: baselineConfigDirectory,
+ temp,
+ }),
+ ]);
+ const rejected = results.find(
+ (result): result is PromiseRejectedResult => result.status === "rejected"
+ );
+ if (rejected !== undefined) {
+ throw rejected.reason;
+ }
+ const [candidateResult, baselineResult] = results.map(
+ (result) =>
+ (
+ result as PromiseFulfilledResult<
+ Awaited<ReturnType<typeof runSingleModelEvaluation>>
+ >
+ ).value
+ );
+ if (candidateResult === undefined || baselineResult === undefined) {
+ throw new Error(
+ "Both packaged CLI model evaluations must produce evidence."
+ );
+ }
+ const passed = candidateResult.passed && baselineResult.passed;
+ const report = modelEvaluationReportSchema.parse({
+ schemaVersion: 2,
+ kind: "model-driven-packaged-cli-evaluation",
+ outcome: passed ? "passed" : "failed",
+ subjects: {
+ candidate: { source: candidate.source, version: candidate.version },
+ baseline: { source: baseline.source, version: baseline.version },
+ },
+ taskId: modelEvaluationTaskId,
+ runs: {
+ candidate: candidateResult.run,
+ baseline: baselineResult.run,
+ },
+ checks: {
+ bothOutcomes: passed ? "passed" : "failed",
+ canaryRedaction: "passed",
+ },
+ });
+ await writeModelEvaluationReport(reportPath, report, [privacyCanary]);
+ if (passed === false) {
+ throw new Error(
+ "Configured model-driven evaluation did not pass against both packaged CLIs."
+ );
+ }
+};
+
+const getRenderedNetworkTransferBytes = (manifest: Record<string, unknown>) =>
+ (Array.isArray(manifest.checks) ? manifest.checks : []).reduce(
+ (total, check) => {
+ if (
+ isPlainRecord(check) === false ||
+ isPlainRecord(check.layout) === false
+ ) {
+ return total;
+ }
+ return (
+ total +
+ (Array.isArray(check.layout.resources)
+ ? check.layout.resources
+ : []
+ ).reduce(
+ (resourceTotal, resource) =>
+ resourceTotal +
+ (isPlainRecord(resource) &&
+ typeof resource.transferSize === "number"
+ ? resource.transferSize
+ : 0),
+ 0
+ )
+ );
+ },
+ 0
+ );
+
+const getRetainedArtifactBytes = async ({
+ manifest,
+ manifestPath,
+ projectDirectory,
+}: {
+ manifest: Record<string, unknown>;
+ manifestPath: string;
+ projectDirectory: string;
+}) => {
+ const artifactPaths = new Set([manifestPath]);
+ for (const collection of [manifest.checks, manifest.failures]) {
+ if (Array.isArray(collection) === false) {
+ continue;
+ }
+ for (const item of collection) {
+ if (isPlainRecord(item) && typeof item.screenshotPath === "string") {
+ artifactPaths.add(
+ item.screenshotPath.startsWith("/")
+ ? item.screenshotPath
+ : join(projectDirectory, item.screenshotPath)
+ );
+ }
+ }
+ }
+ const sizes = await Promise.all(
+ Array.from(artifactPaths, async (path) =>
+ stat(path)
+ .then((file) => file.size)
+ .catch(() => 0)
+ )
+ );
+ return sizes.reduce((total, size) => total + size, 0);
+};
+
const assertScreenshotEvidence = async ({
payload,
label,
@@ -686,28 +1195,21 @@ 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"),
- import("@webstudio-is/project-build/contracts"),
- import("@webstudio-is/project-build/project-session"),
- import("@webstudio-is/project-build/runtime"),
- import("@webstudio-is/project-build/state"),
- ]);
+ const [pagesModule, state, namespaces, projectSession, runtimeRegistry] =
+ await Promise.all([
+ import("@webstudio-is/project-migrations/pages"),
+ import("@webstudio-is/project-build/state"),
+ import("@webstudio-is/project-build/contracts"),
+ import("@webstudio-is/project-build/project-session"),
+ import("@webstudio-is/project-build/runtime"),
+ ]);
const temp = await mkdtemp(join(tmpdir(), "webstudio-release-smoke-"));
let preview: ChildProcess | undefined;
- let apiServer: Server | undefined;
+ let closeApiServer: (() => Promise<void>) | undefined;
try {
const startedAt = Date.now();
const fixture = createFixture();
- const initialState = adapters.createBuilderStateFromBuildData({
+ const initialState = state.createBuilderStateFromBuildData({
...fixture.build,
pages: pagesModule.migratePages(fixture.persistedPages),
assets: fixture.assets,
@@ -717,66 +1219,120 @@ const run = async () => {
const fixtureApi = await startFixtureApi(fixture, {
initialState,
executeRuntime: runtimeRegistry.executeBuilderRuntimeOperation,
- applyTransactions: statePatch.applyBuilderPatchTransactions,
- serializeFixturePages: pagesModule.serializePages,
+ applyTransactions: state.applyBuilderPatchTransactions,
});
fixture.data.origin = fixtureApi.origin;
- reportPhase("fixture API ready", startedAt);
- apiServer = fixtureApi.server;
+ reportPhase("fixture-api", startedAt);
+ closeApiServer = fixtureApi.close;
const packDirectory = join(temp, "pack");
const stagingDirectory = join(temp, "staging");
- const projectDirectory = join(temp, "project");
- const configDirectory = join(temp, "config");
+ const projectDirectory = join(temp, "candidate-project");
+ const baselineProjectDirectory = join(temp, "baseline-project");
+ const configDirectory = join(temp, "candidate-config");
+ const baselineConfigDirectory = join(temp, "baseline-config");
await Promise.all([
mkdir(packDirectory, { recursive: true }),
mkdir(stagingDirectory, { recursive: true }),
mkdir(join(projectDirectory, ".webstudio"), { recursive: true }),
+ mkdir(join(baselineProjectDirectory, ".webstudio"), { recursive: true }),
mkdir(join(configDirectory, "webstudio-nodejs"), { recursive: true }),
+ mkdir(join(baselineConfigDirectory, "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.");
+ const requestedCandidate =
+ process.env.WEBSTUDIO_RELEASE_SMOKE_CANDIDATE ?? "local";
+ let candidate: ReleaseTarget;
+ if (requestedCandidate === "local") {
+ const releaseVersion =
+ process.env.WEBSTUDIO_RELEASE_SMOKE_VERSION ??
+ (await resolveRegistryTarget("webstudio@latest")).version;
+ const packStartedAt = Date.now();
+ await packReleaseShapedCli({
+ stagingDirectory,
+ packDirectory,
+ releaseVersion,
+ });
+ reportPhase("package", packStartedAt);
+ const tarballName = (await readdir(packDirectory)).find((name) =>
+ name.endsWith(".tgz")
+ );
+ if (tarballName === undefined) {
+ throw new Error("npm pack did not produce a tarball.");
+ }
+ candidate = {
+ source: "local",
+ version: releaseVersion,
+ installSpec: join(packDirectory, tarballName),
+ };
+ } else {
+ candidate = await resolveRegistryTarget(requestedCandidate);
}
- await writeFile(
- join(projectDirectory, "package.json"),
- JSON.stringify({ private: true }),
- "utf8"
+ const baseline = await resolveRegistryTarget(
+ process.env.WEBSTUDIO_RELEASE_SMOKE_BASELINE ?? "webstudio@latest"
);
- 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}`
- );
+ reporter.setSubjects({
+ candidate: { source: candidate.source, version: candidate.version },
+ baseline: { source: baseline.source, version: baseline.version },
+ });
+ const expectedRegistryVersion =
+ process.env.WEBSTUDIO_RELEASE_SMOKE_EXPECT_REGISTRY_VERSION;
+ if (expectedRegistryVersion !== undefined) {
+ if (
+ candidate.source !== "registry" ||
+ candidate.version !== expectedRegistryVersion ||
+ candidate.integrity === undefined
+ ) {
+ reporter.setRegistryArtifact("failed");
+ throw new Error(
+ `Expected exact registry artifact webstudio@${expectedRegistryVersion}, resolved ${candidate.source} ${candidate.version}.`
+ );
+ }
}
- reportPhase("installed packed CLI", installStartedAt);
+
+ const candidateInstallStartedAt = Date.now();
+ await installReleaseTarget({
+ directory: projectDirectory,
+ target: candidate,
+ enforceArtifactContract: true,
+ });
+ if (expectedRegistryVersion !== undefined) {
+ reporter.setRegistryArtifact("passed");
+ }
+ reportPhase("candidate-install", candidateInstallStartedAt);
+ const baselineInstallStartedAt = Date.now();
+ await installReleaseTarget({
+ directory: baselineProjectDirectory,
+ target: baseline,
+ });
+ reportPhase("baseline-install", baselineInstallStartedAt);
const bin = join(projectDirectory, "node_modules", ".bin", "webstudio");
+ const baselineBin = join(
+ baselineProjectDirectory,
+ "node_modules",
+ ".bin",
+ "webstudio"
+ );
const env = {
...process.env,
WEBSTUDIO_CONFIG_DIR: configDirectory,
};
+ const baselineEnv = {
+ ...process.env,
+ WEBSTUDIO_CONFIG_DIR: baselineConfigDirectory,
+ };
const globalConfigPath = join(configDirectory, "webstudio-config.json");
- await mkdir(dirname(globalConfigPath), { recursive: true });
- await writeFile(globalConfigPath, "{}", "utf8");
+ const baselineGlobalConfigPath = join(
+ baselineConfigDirectory,
+ "webstudio-config.json"
+ );
+ await Promise.all([
+ mkdir(dirname(globalConfigPath), { recursive: true }),
+ mkdir(dirname(baselineGlobalConfigPath), { recursive: true }),
+ writeFile(globalConfigPath, "{}", "utf8"),
+ writeFile(baselineGlobalConfigPath, "{}", "utf8"),
+ ]);
const workflowStartedAt = Date.now();
const runCliStep = (step: string, recovery: string, args: string[]) =>
runAgentWorkflowStep({
@@ -810,7 +1366,7 @@ const run = async () => {
);
}
- const state = adapters.createBuilderStateFromBuildData({
+ const builderState = state.createBuilderStateFromBuildData({
...fixture.build,
pages: pagesModule.migratePages(fixture.persistedPages),
assets: fixture.assets,
@@ -829,25 +1385,157 @@ const run = async () => {
},
])
);
+ const candidateSessionSnapshot = {
+ projectId,
+ buildId,
+ version: projectVersion,
+ state: state.createSerializedBuilderStateSnapshotFromState(builderState),
+ freshness,
+ compatibilityVersion: sessionVersion,
+ compatibility: {
+ ...projectSession.createDefaultProjectSessionCompatibility(
+ sessionVersion
+ ),
+ apiCompatibilityVersion: candidate.version,
+ },
+ revision: randomUUID(),
+ };
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(),
- }),
+ JSON.stringify(candidateSessionSnapshot),
"utf8"
);
+ await cp(
+ join(projectDirectory, ".webstudio"),
+ join(baselineProjectDirectory, ".webstudio"),
+ { recursive: true, force: true }
+ );
+ await Promise.all([
+ writeFile(
+ join(baselineProjectDirectory, ".webstudio", "project-session.json"),
+ JSON.stringify({
+ ...candidateSessionSnapshot,
+ compatibility: {
+ ...candidateSessionSnapshot.compatibility,
+ apiCompatibilityVersion: baseline.version,
+ },
+ revision: randomUUID(),
+ }),
+ "utf8"
+ ),
+ cp(globalConfigPath, baselineGlobalConfigPath, { force: true }),
+ ]);
+ const agentCommand = process.env.WEBSTUDIO_RELEASE_SMOKE_AGENT_COMMAND;
+ if (
+ process.env.WEBSTUDIO_RELEASE_SMOKE_MODEL_EVAL_REQUIRED === "1" &&
+ (agentCommand === undefined || agentCommand === "")
+ ) {
+ throw new Error(
+ "WEBSTUDIO_RELEASE_SMOKE_AGENT_COMMAND is required for model evaluation; no model evidence was created."
+ );
+ }
+ if (agentCommand !== undefined && agentCommand !== "") {
+ const agentReportPath = process.env.WEBSTUDIO_RELEASE_SMOKE_AGENT_REPORT;
+ if (agentReportPath === undefined || agentReportPath === "") {
+ throw new Error(
+ "WEBSTUDIO_RELEASE_SMOKE_AGENT_REPORT is required when a model evaluation command is configured."
+ );
+ }
+ const modelEvaluationStartedAt = Date.now();
+ await runModelEvaluation({
+ command: agentCommand,
+ reportPath: agentReportPath,
+ candidate,
+ baseline,
+ candidateBin: bin,
+ baselineBin,
+ candidateProjectDirectory: projectDirectory,
+ baselineProjectDirectory,
+ candidateConfigDirectory: configDirectory,
+ baselineConfigDirectory,
+ temp,
+ });
+ reportPhase("model-evaluation", modelEvaluationStartedAt);
+ }
+ const compactComparisonStartedAt = Date.now();
+ const candidateCompact = await runCompactMeasurementSuite({
+ bin,
+ cwd: projectDirectory,
+ env,
+ expectedDetail: "compact",
+ });
+ const candidateVerbose = await runCompactMeasurementSuite({
+ bin,
+ cwd: projectDirectory,
+ env,
+ expectedDetail: "verbose",
+ });
+ const baselineCompact = await runCompactMeasurementSuite({
+ bin: baselineBin,
+ cwd: baselineProjectDirectory,
+ env: baselineEnv,
+ expectedDetail: "compact",
+ });
+ for (const operation of compactSmokeOperations) {
+ const candidateMeasurement = candidateCompact.measurements.get(operation);
+ const verboseMeasurement = candidateVerbose.measurements.get(operation);
+ const baselineMeasurement = baselineCompact.measurements.get(operation);
+ if (
+ candidateMeasurement === undefined ||
+ verboseMeasurement === undefined ||
+ baselineMeasurement === undefined
+ ) {
+ throw new Error(`Missing comparison measurement for ${operation}.`);
+ }
+ reporter.recordOperation(
+ operation,
+ candidateMeasurement,
+ verboseMeasurement,
+ baselineMeasurement
+ );
+ }
+ const candidateContractPassed =
+ candidateCompact.contractFailures.length === 0;
+ const candidateVerboseContractPassed =
+ candidateVerbose.contractFailures.length === 0;
+ const baselineContractPassed =
+ baselineCompact.contractFailures.length === 0;
+ reporter.setContract(
+ "candidateCompact",
+ candidateContractPassed ? "passed" : "failed"
+ );
+ reporter.setContract(
+ "candidateVerbose",
+ candidateVerboseContractPassed ? "passed" : "failed"
+ );
+ reporter.setContract(
+ "historicalBaselineCompact",
+ baselineContractPassed ? "passed" : "failed"
+ );
+ reportPhase("compact-comparison", compactComparisonStartedAt);
+ if (candidateContractPassed === false) {
+ throw new Error(
+ `Compact output contract failed for candidate [${candidateCompact.contractFailures.join(", ")}].`
+ );
+ }
+ if (candidateVerboseContractPassed === false) {
+ throw new Error(
+ `Verbose semantic baseline failed for candidate [${candidateVerbose.contractFailures.join(", ")}].`
+ );
+ }
+ if (reporter.candidatePassesCompactRollout() === false) {
+ const report = reporter.createReport("failed");
+ const totals = report.sameCandidate.totals;
+ throw new Error(
+ `Candidate compact rollout gate failed: compact=${totals.compact.tokens} tokens, verbose=${totals.verbose.tokens} tokens, budget=${report.candidateTokenBudget}, retryDelta=${totals.retryDelta}, failureDelta=${totals.failureDelta}. Compact must be strictly smaller with no retry or failure regression.`
+ );
+ }
+ if (candidateCompact.canarySeen === false) {
+ throw new Error(
+ "Privacy canary was not exercised by the candidate compact list-pages response."
+ );
+ }
+ reporter.markCanaryExercised();
const invoke = async (label: string, args: string[]) => {
const result = await execFileAsync(bin, args, {
cwd: projectDirectory,
@@ -904,7 +1592,7 @@ const run = async () => {
);
}
}
- reportPhase("validated packed audit help examples", helpStartedAt);
+ reportPhase("audit-help", helpStartedAt);
const previewStartedAt = Date.now();
preview = spawn(bin, ["preview", "--port", "5190"], {
@@ -928,7 +1616,7 @@ const run = async () => {
"Generic React Router preview unexpectedly includes Docker-only image proxy dependencies."
);
}
- reportPhase("started packed preview", previewStartedAt);
+ reportPhase("preview-start", previewStartedAt);
const commandsStartedAt = Date.now();
const assertLocalDryRun = async (
label: string,
@@ -987,20 +1675,13 @@ const run = async () => {
step: `${clientName} connection smoke`,
recovery: `Reload ${clientName}, then verify its Webstudio MCP command starts in the linked project folder.`,
run: async () => {
- const transport = new StdioClientTransport({
- command: bin,
- args: ["mcp"],
+ const { client, transport } = createMcpSmokeClient({
+ bin,
cwd: projectDirectory,
- env: Object.fromEntries(
- Object.entries(env).filter(
- (entry): entry is [string, string] =>
- typeof entry[1] === "string"
- )
- ),
- stderr: "pipe",
+ env,
+ name: clientName,
});
transport.stderr?.on("data", () => {});
- const client = new Client({ name: clientName, version: "1.0.0" });
await client.connect(transport);
try {
const tools = await client.listTools();
@@ -1015,25 +1696,17 @@ const run = async () => {
},
});
}
- 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",
- });
+ const { client: stdioClient, transport: stdioTransport } =
+ createMcpSmokeClient({
+ bin,
+ cwd: projectDirectory,
+ env,
+ name: "webstudio-release-smoke",
+ });
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> = {}
@@ -1050,6 +1723,22 @@ const run = async () => {
}
return getRecord(structured.data, `${name} data`);
};
+ const listAllPages = async () => {
+ const pages: unknown[] = [];
+ let cursor: string | undefined;
+ do {
+ const result = await callTool("list-pages", { cursor, limit: 200 });
+ if (Array.isArray(result.pages) === false) {
+ throw new Error(
+ `list-pages returned invalid data: ${JSON.stringify(result)}`
+ );
+ }
+ pages.push(...result.pages);
+ cursor =
+ typeof result.nextCursor === "string" ? result.nextCursor : undefined;
+ } while (cursor !== undefined);
+ return pages;
+ };
await stdioClient.connect(stdioTransport);
try {
const inspection = await callTool("inspect");
@@ -1058,13 +1747,8 @@ const run = async () => {
`Inspect returned the wrong project: ${JSON.stringify(inspection)}`
);
}
- const initialPages = await callTool("list-pages", {
- includeFolders: true,
- });
- if (
- Array.isArray(initialPages.pages) === false ||
- initialPages.pages.length !== 2
- ) {
+ const initialPages = await listAllPages();
+ if (initialPages.length !== fixture.data.pages.length) {
throw new Error(
`Cold stdio discovery returned unexpected pages: ${JSON.stringify(initialPages)}`
);
@@ -1086,20 +1770,13 @@ const run = async () => {
}> = [];
const duplicate = await callTool("duplicate-page", {
pageId: "home",
- name: "About",
- path: "/about",
+ ...duplicatedPage,
});
createdPages.push({
pageId: String(duplicate.pageId),
- name: "About",
- path: "/about",
+ ...duplicatedPage,
});
- for (const page of [
- { name: "Services", path: "/services" },
- { name: "Work", path: "/work" },
- { name: "Blog", path: "/blog" },
- { name: "Contact", path: "/contact" },
- ]) {
+ for (const page of createdPageInputs) {
const created = await callTool("create-page", page);
createdPages.push({ pageId: String(created.pageId), ...page });
}
@@ -1147,6 +1824,18 @@ const run = async () => {
values: { title: `Pricing session check ${index}` },
});
}
+ const committedPricing = await callTool("get-page", {
+ pageId: "pricing",
+ });
+ await callTool("refresh", { namespaces: ["pages"] });
+ const refreshedPricing = await callTool("get-page", {
+ pageId: "pricing",
+ });
+ if (refreshedPricing.title !== committedPricing.title) {
+ throw new Error(
+ `Committed page title did not survive refresh: before=${JSON.stringify(committedPricing)} after=${JSON.stringify(refreshedPricing)}`
+ );
+ }
const usage = await callTool("find-asset-usage", {
assetId: "asset-hero",
@@ -1185,17 +1874,15 @@ const run = async () => {
`Agent connection workflow exceeded ten minutes (${workflowDuration}ms). Recovery: Inspect the reported release-smoke phase timings and optimize the slowest blocked step.`
);
}
- reportPhase(
- "completed ten-minute agent connection workflow",
- workflowStartedAt
- );
+ reportPhase("agent-workflow", workflowStartedAt);
- const finalPages = await callTool("list-pages");
- const finalPageNames = Array.isArray(finalPages.pages)
- ? finalPages.pages.map((page) => getRecord(page, "final page").name)
- : [];
+ const finalPages = await listAllPages();
+ const finalPageNames = finalPages.map(
+ (page) => getRecord(page, "final page").name
+ );
if (
- finalPageNames.length !== 7 ||
+ finalPageNames.length !==
+ fixture.data.pages.length + createdPages.length ||
createdPages.some(
(page) => finalPageNames.includes(page.name) === false
)
@@ -1215,10 +1902,7 @@ const run = async () => {
) {
throw new Error(`Unexpected packed stdio lifecycle logs:\n${stdioLogs}`);
}
- reportPhase(
- "completed packed seven-page stdio MCP workflow",
- stdioStartedAt
- );
+ reportPhase("stdio-workflow", stdioStartedAt);
preview = spawn(bin, ["preview", "--port", "5190"], {
cwd: projectDirectory,
@@ -1326,6 +2010,8 @@ const run = async () => {
);
}
if (process.env.WEBSTUDIO_RELEASE_SMOKE_LARGE_AUDIT === "1") {
+ const expectedCaptureCount =
+ fixture.data.pages.length + additionalPageCount;
const planPayload = await invoke("large rendered audit plan", [
"audit",
"--rendered",
@@ -1336,11 +2022,11 @@ const run = async () => {
const planData = getRecord(planPayload.data, "large audit plan data");
const plan = getRecord(planData.renderedPlan, "large rendered plan");
if (
- plan.captureCount !== 122 ||
+ plan.captureCount !== expectedCaptureCount ||
typeof plan.confirmationToken !== "string"
) {
throw new Error(
- `Large rendered audit did not return the expected 122-capture confirmation plan: ${JSON.stringify(plan)}`
+ `Large rendered audit did not return the expected ${expectedCaptureCount}-capture confirmation plan: ${JSON.stringify(plan)}`
);
}
const confirmedAuditStartedAt = Date.now();
@@ -1367,18 +2053,16 @@ const run = async () => {
"confirmed large audit artifact manifest"
);
const manifestPath = String(manifestSummary.path);
+ const absoluteManifestPath = manifestPath.startsWith("/")
+ ? manifestPath
+ : join(projectDirectory, manifestPath);
const manifest = JSON.parse(
- await readFile(
- manifestPath.startsWith("/")
- ? manifestPath
- : join(projectDirectory, manifestPath),
- "utf8"
- )
- ) as { failures?: unknown[]; performance?: unknown };
+ await readFile(absoluteManifestPath, "utf8")
+ ) as Record<string, unknown>;
if (
confirmedPayload.ok !== true ||
- confirmedData.renderedCheckCount !== 122 ||
- summary.planned !== 122 ||
+ confirmedData.renderedCheckCount !== expectedCaptureCount ||
+ summary.planned !== expectedCaptureCount ||
summary.failed !== 0 ||
summary.skipped !== 0
) {
@@ -1386,14 +2070,30 @@ const run = async () => {
`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 memory = process.memoryUsage();
+ const buildMetrics = isPlainRecord(manifest.generatedBuildMetrics)
+ ? manifest.generatedBuildMetrics
+ : undefined;
+ reportPhase("rendered-audit", confirmedAuditStartedAt, {
+ rssBytes: memory.rss,
+ heapUsedBytes: memory.heapUsed,
+ networkTransferBytes: getRenderedNetworkTransferBytes(manifest),
+ retainedArtifactBytes: await getRetainedArtifactBytes({
+ manifest,
+ manifestPath: absoluteManifestPath,
+ projectDirectory,
+ }),
+ ...(typeof buildMetrics?.bytes === "number"
+ ? { generatedBuildBytes: buildMetrics.bytes }
+ : {}),
+ ...(typeof buildMetrics?.gzipBytes === "number"
+ ? { generatedBuildGzipBytes: buildMetrics.gzipBytes }
+ : {}),
+ });
const confirmedAuditDuration = Date.now() - confirmedAuditStartedAt;
- if (confirmedAuditDuration > 90_000) {
+ if (confirmedAuditDuration > 120_000) {
throw new Error(
- `Confirmed 122-capture packaged audit took ${confirmedAuditDuration}ms; expected at most 90000ms.`
+ `Confirmed ${expectedCaptureCount}-capture packaged audit took ${confirmedAuditDuration}ms; expected at most 120000ms.`
);
}
const cachedAuditStartedAt = Date.now();
@@ -1406,7 +2106,7 @@ const run = async () => {
"performance",
"--json",
]);
- reportPhase("validated cached rendered audit", cachedAuditStartedAt);
+ reportPhase("cached-audit", cachedAuditStartedAt);
const cachedAuditDuration = Date.now() - cachedAuditStartedAt;
if (cachedAuditDuration > 20_000) {
throw new Error(
@@ -1414,13 +2114,22 @@ const run = async () => {
);
}
}
- reportPhase("validated structured commands", commandsStartedAt);
+ reportPhase("structured-commands", commandsStartedAt);
} finally {
await stopProcessTree(preview);
- await closeServer(apiServer);
+ await closeApiServer?.();
await rm(temp, { recursive: true, force: true });
- reportPhase("cleaned temporary release smoke files");
+ reportPhase("cleanup");
}
};
-await run();
+let outcome: "passed" | "failed" = "failed";
+try {
+ await run();
+ outcome = "passed";
+} finally {
+ const reportPath = process.env.WEBSTUDIO_RELEASE_SMOKE_REPORT;
+ if (reportPath !== undefined && reportPath !== "") {
+ await reporter.write(reportPath, outcome);
+ }
+}
diff --git a/packages/cli/scripts/run-agent-command.test.ts b/packages/cli/scripts/run-agent-command.test.ts
new file mode 100644
index 0000000000..495ec47e43
--- /dev/null
+++ b/packages/cli/scripts/run-agent-command.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, test } from "vitest";
+import { runAgentCommand } from "./run-agent-command";
+
+describe("runAgentCommand", () => {
+ test("returns the process exit code without capturing private output", async () => {
+ await expect(
+ runAgentCommand({
+ command: `${JSON.stringify(process.execPath)} -e 'process.exit(7)'`,
+ cwd: process.cwd(),
+ env: process.env,
+ timeoutMs: 5_000,
+ })
+ ).resolves.toMatchObject({ exitCode: 7, durationMs: expect.any(Number) });
+ });
+
+ test("terminates a timed-out process group", async () => {
+ await expect(
+ runAgentCommand({
+ command: `${JSON.stringify(process.execPath)} -e 'setInterval(() => {}, 1000)'`,
+ cwd: process.cwd(),
+ env: process.env,
+ timeoutMs: 50,
+ })
+ ).rejects.toThrow("Agent command timed out after 50ms.");
+ });
+});
diff --git a/packages/cli/scripts/run-agent-command.ts b/packages/cli/scripts/run-agent-command.ts
new file mode 100644
index 0000000000..21c9d2cc16
--- /dev/null
+++ b/packages/cli/scripts/run-agent-command.ts
@@ -0,0 +1,42 @@
+import { spawn } from "node:child_process";
+
+export const runAgentCommand = ({
+ command,
+ cwd,
+ env,
+ timeoutMs,
+}: {
+ command: string;
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+ timeoutMs: number;
+}) =>
+ new Promise<{ exitCode: number; durationMs: number }>((resolve, reject) => {
+ const startedAt = Date.now();
+ const child = spawn(process.env.SHELL ?? "/bin/sh", ["-c", command], {
+ cwd,
+ env,
+ stdio: "ignore",
+ detached: process.platform !== "win32",
+ });
+ const timeout = setTimeout(() => {
+ if (child.pid !== undefined) {
+ try {
+ process.kill(process.platform === "win32" ? child.pid : -child.pid);
+ } catch {}
+ }
+ reject(new Error(`Agent command timed out after ${timeoutMs}ms.`));
+ }, timeoutMs);
+ child.once("error", (error) => {
+ clearTimeout(timeout);
+ reject(error);
+ });
+ child.once("exit", (code, signal) => {
+ clearTimeout(timeout);
+ if (signal !== null) {
+ reject(new Error(`Agent command exited from signal ${signal}.`));
+ return;
+ }
+ resolve({ exitCode: code ?? -1, durationMs: Date.now() - startedAt });
+ });
+ });
diff --git a/packages/cli/scripts/runtime-fixture-api.test.ts b/packages/cli/scripts/runtime-fixture-api.test.ts
new file mode 100644
index 0000000000..e49e73d4cf
--- /dev/null
+++ b/packages/cli/scripts/runtime-fixture-api.test.ts
@@ -0,0 +1,170 @@
+import { afterEach, describe, expect, test } from "vitest";
+import { migratePages } from "@webstudio-is/project-migrations/pages";
+import { serializedBuild } from "@webstudio-is/project-build/contracts";
+import { createBuilderStateFromBuildData } from "@webstudio-is/project-build/state";
+import {
+ createRuntimeFixtureBuildSnapshot,
+ createRuntimeFixtureSerializedBuild,
+ publicApiCommandByOperationId,
+ runtimeFixturePermissions,
+ startRuntimeFixtureApi,
+} from "./runtime-fixture-api";
+
+const closeCallbacks: Array<() => Promise<void>> = [];
+
+afterEach(async () => {
+ await Promise.all(closeCallbacks.splice(0).map((close) => close()));
+});
+
+describe("runtime fixture API", () => {
+ test("serializes build snapshots for their distinct API contracts", () => {
+ const state = createBuilderStateFromBuildData({
+ pages: migratePages({
+ meta: {},
+ compiler: {},
+ redirects: [],
+ homePageId: "home",
+ rootFolderId: "root",
+ pages: [
+ {
+ id: "home",
+ name: "Home",
+ path: "",
+ title: "Home",
+ rootInstanceId: "root-instance",
+ meta: {},
+ },
+ ],
+ folders: [
+ {
+ id: "root",
+ name: "Root",
+ slug: "",
+ children: ["home"],
+ },
+ ],
+ }),
+ instances: [
+ {
+ type: "instance",
+ id: "root-instance",
+ component: "Box",
+ children: [],
+ },
+ ],
+ props: [],
+ dataSources: [],
+ resources: [],
+ breakpoints: [],
+ styles: [],
+ styleSources: [],
+ styleSourceSelections: [],
+ assets: [],
+ projectSettings: { meta: {}, compiler: {} },
+ });
+ const baseBuild = {
+ id: "old-build",
+ projectId: "project",
+ version: 1,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ };
+
+ const snapshot = createRuntimeFixtureBuildSnapshot({
+ state,
+ projectId: "project",
+ buildId: "build",
+ version: 2,
+ });
+ expect(snapshot.pages).toEqual([expect.objectContaining({ id: "home" })]);
+ expect(snapshot.instances).toEqual([
+ expect.objectContaining({ id: "root-instance" }),
+ ]);
+ expect(snapshot.variables).toEqual([]);
+ expect(snapshot).not.toHaveProperty("dataSources");
+
+ const build = createRuntimeFixtureSerializedBuild({
+ state,
+ baseBuild,
+ buildId: "build",
+ version: 2,
+ });
+ expect(serializedBuild.parse(build)).toEqual(build);
+ expect(build.pages).toEqual(
+ expect.objectContaining({
+ pages: [expect.objectContaining({ id: "home" })],
+ })
+ );
+ expect(build.instances).toEqual([
+ ["root-instance", expect.objectContaining({ id: "root-instance" })],
+ ]);
+ });
+
+ test.each([
+ {
+ method: "GET",
+ request: (origin: string) =>
+ fetch(
+ `${origin}/trpc/api.pages.list?input=${encodeURIComponent(
+ JSON.stringify({ 0: { json: { limit: 3 } } })
+ )}`
+ ),
+ },
+ {
+ method: "POST",
+ request: (origin: string) =>
+ fetch(`${origin}/trpc/api.pages.list`, {
+ method: "POST",
+ body: JSON.stringify({ 0: { json: { limit: 3 } } }),
+ }),
+ },
+ ])("decodes $method tRPC input", async ({ request }) => {
+ const api = await startRuntimeFixtureApi(
+ async ({ operationPath, readInput }) => ({
+ operationPath,
+ input: await readInput(),
+ })
+ );
+ closeCallbacks.push(api.close);
+
+ const response = await request(api.origin);
+
+ expect(await response.json()).toEqual([
+ {
+ result: {
+ data: {
+ operationPath: "pages.list",
+ input: { limit: 3 },
+ },
+ },
+ },
+ ]);
+ });
+
+ test("returns a stable tRPC error envelope", async () => {
+ const api = await startRuntimeFixtureApi(async () => {
+ throw new Error("fixture failed");
+ });
+ closeCallbacks.push(api.close);
+
+ const response = await fetch(`${api.origin}/trpc/api.pages.list`);
+
+ expect(response.status).toBe(500);
+ expect(await response.json()).toEqual([
+ {
+ error: {
+ message: "fixture failed",
+ code: -32603,
+ data: { code: "INTERNAL_SERVER_ERROR", httpStatus: 500 },
+ },
+ },
+ ]);
+ });
+
+ test("derives permissions and command names from the public API contract", () => {
+ expect(runtimeFixturePermissions.apiContract.operationIds).toContain(
+ "publish.list"
+ );
+ expect(publicApiCommandByOperationId.get("pages.list")).toBe("list-pages");
+ });
+});
diff --git a/packages/cli/scripts/runtime-fixture-api.ts b/packages/cli/scripts/runtime-fixture-api.ts
new file mode 100644
index 0000000000..7e5b6a4ba9
--- /dev/null
+++ b/packages/cli/scripts/runtime-fixture-api.ts
@@ -0,0 +1,178 @@
+import {
+ createServer,
+ type IncomingMessage,
+ type ServerResponse,
+} from "node:http";
+import {
+ publicApiContractVersion,
+ publicApiOperationRequiresServerSupport,
+ publicApiOperations,
+} from "@webstudio-is/protocol";
+import { serializePages } from "@webstudio-is/project-migrations/pages";
+import {
+ createBuilderBuildDataSnapshotFromState,
+ createSerializedBuilderBuildDataFromState,
+ type BuilderState,
+} from "@webstudio-is/project-build/state";
+
+export type RuntimeFixtureRequest = {
+ request: IncomingMessage;
+ response: ServerResponse;
+ pathname: string;
+ operationPath: string;
+ readInput: () => Promise<unknown>;
+};
+
+export const runtimeFixturePermissions = {
+ canView: true,
+ canEdit: true,
+ canBuild: true,
+ canAdmin: true,
+ canUseApi: true,
+ apiContract: {
+ version: publicApiContractVersion,
+ operationIds: publicApiOperations.flatMap((operation) =>
+ publicApiOperationRequiresServerSupport(operation) ? [operation.id] : []
+ ),
+ },
+} as const;
+
+export const publicApiCommandByOperationId = new Map(
+ publicApiOperations.map((operation) => [operation.id, operation.command])
+);
+
+export const createRuntimeFixtureBuildSnapshot = ({
+ state,
+ projectId,
+ buildId,
+ version,
+}: {
+ state: BuilderState;
+ projectId: string;
+ buildId: string;
+ version: number;
+}) => {
+ const {
+ pages: hydratedPages,
+ dataSources,
+ ...buildData
+ } = createBuilderBuildDataSnapshotFromState(state);
+ if (hydratedPages === undefined) {
+ throw new Error("Runtime fixture pages are missing.");
+ }
+ const pages = serializePages(hydratedPages);
+ return {
+ ...buildData,
+ projectId,
+ buildId,
+ version,
+ pages: pages.pages,
+ pageTemplates: pages.pageTemplates,
+ folders: pages.folders,
+ homePageId: pages.homePageId,
+ rootFolderId: pages.rootFolderId,
+ redirects: pages.redirects,
+ variables: dataSources,
+ };
+};
+
+export const createRuntimeFixtureSerializedBuild = ({
+ state,
+ baseBuild,
+ buildId,
+ version,
+}: {
+ state: BuilderState;
+ baseBuild: Record<string, unknown>;
+ buildId: string;
+ version: number;
+}) => {
+ return {
+ ...baseBuild,
+ ...createSerializedBuilderBuildDataFromState(state),
+ id: buildId,
+ version,
+ };
+};
+
+const readTrpcInput = async (request: 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 closeServer = async (
+ server: ReturnType<typeof createServer>
+): Promise<void> => {
+ server.closeAllConnections();
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) => (error === undefined ? resolve() : reject(error)))
+ );
+};
+
+export const startRuntimeFixtureApi = async (
+ handle: (request: RuntimeFixtureRequest) => Promise<unknown>
+) => {
+ const server = createServer(async (request, response) => {
+ try {
+ const pathname = new URL(request.url ?? "", "http://127.0.0.1").pathname;
+ const data = await handle({
+ request,
+ response,
+ pathname,
+ operationPath: pathname.replace(/^\/trpc\/(?:api\.)?/, ""),
+ readInput: () => readTrpcInput(request),
+ });
+ if (response.writableEnded) {
+ return;
+ }
+ response.writeHead(200, { "content-type": "application/json" });
+ response.end(JSON.stringify([{ result: { data } }]));
+ } catch (error) {
+ if (response.writableEnded) {
+ return;
+ }
+ 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}`,
+ close: () => closeServer(server),
+ };
+};
diff --git a/packages/cli/src/api-connection.test.ts b/packages/cli/src/api-connection.test.ts
index a34ad17aa0..0b448e09bb 100644
--- a/packages/cli/src/api-connection.test.ts
+++ b/packages/cli/src/api-connection.test.ts
@@ -10,7 +10,7 @@ const createDependencies = ({
files?: Record<string, string>;
} = {}) => ({
isFileExists: vi.fn(async (path: string) =>
- path === LOCAL_CONFIG_FILE ? exists : path in files
+ path.endsWith(LOCAL_CONFIG_FILE) ? exists : path in files
),
readFile: vi.fn(async (path: string) => {
const key = path.endsWith(LOCAL_CONFIG_FILE) ? LOCAL_CONFIG_FILE : path;
@@ -43,6 +43,27 @@ describe("resolveApiConnection", () => {
});
});
+ test("resolves local config from an explicit project root", async () => {
+ const dependencies = createDependencies({
+ files: {
+ [LOCAL_CONFIG_FILE]: JSON.stringify({ projectId: "project-1" }),
+ [GLOBAL_CONFIG_FILE]: JSON.stringify({
+ "project-1": { origin: "https://example.com", token: "token-1" },
+ }),
+ },
+ });
+
+ await resolveApiConnection(dependencies, "/workspace/site-a");
+
+ expect(dependencies.isFileExists).toHaveBeenCalledWith(
+ "/workspace/site-a/.webstudio/config.json"
+ );
+ expect(dependencies.readFile).toHaveBeenCalledWith(
+ "/workspace/site-a/.webstudio/config.json",
+ "utf-8"
+ );
+ });
+
test("requires a local project config", async () => {
await expect(
resolveApiConnection(createDependencies({ exists: false }))
diff --git a/packages/cli/src/api-connection.ts b/packages/cli/src/api-connection.ts
index 2b40e1fd56..ceb8f71fe5 100644
--- a/packages/cli/src/api-connection.ts
+++ b/packages/cli/src/api-connection.ts
@@ -27,18 +27,18 @@ export const defaultApiConnectionDependencies: ApiConnectionDependencies = {
};
export const resolveApiConnection = async (
- dependencies = defaultApiConnectionDependencies
+ dependencies = defaultApiConnectionDependencies,
+ projectRoot = cwd()
): Promise<ApiConnection> => {
- if ((await dependencies.isFileExists(LOCAL_CONFIG_FILE)) === false) {
+ const localConfigFile = join(projectRoot, LOCAL_CONFIG_FILE);
+ if ((await dependencies.isFileExists(localConfigFile)) === false) {
throw new Error(
"Local config file is not found. Run webstudio init --link <api-share-link> from a Webstudio project."
);
}
const localConfig = jsonToLocalConfig(
- JSON.parse(
- await dependencies.readFile(join(cwd(), LOCAL_CONFIG_FILE), "utf-8")
- )
+ JSON.parse(await dependencies.readFile(localConfigFile, "utf-8"))
);
const globalConfig = jsonToGlobalConfig(
JSON.parse(await dependencies.readFile(GLOBAL_CONFIG_FILE, "utf-8"))
diff --git a/packages/cli/src/commands/api-command-metadata.test.ts b/packages/cli/src/commands/api-command-metadata.test.ts
index ab0ba9a08d..b5a3bea42a 100644
--- a/packages/cli/src/commands/api-command-metadata.test.ts
+++ b/packages/cli/src/commands/api-command-metadata.test.ts
@@ -142,7 +142,7 @@ test("parses redirect status as a string option", () => {
);
});
-test("describes list-folders include-pages response shape", () => {
+test("describes list-folders pagination and detail options", () => {
const yargs = { option: vi.fn().mockReturnThis() };
const metadata = apiCommandMetadata.find(
(item) => item.command === "list-folders"
@@ -152,10 +152,12 @@ test("describes list-folders include-pages response shape", () => {
getApiCommandOptions(metadata!)(yargs as never);
expect(yargs.option).toHaveBeenCalledWith(
- "include-pages",
- expect.objectContaining({
- describe: "Include a top-level pages array with page summaries",
- })
+ "limit",
+ expect.objectContaining({ type: "number" })
+ );
+ expect(yargs.option).toHaveBeenCalledWith(
+ "verbose",
+ expect.objectContaining({ type: "boolean" })
);
});
diff --git a/packages/cli/src/commands/api-command-metadata.ts b/packages/cli/src/commands/api-command-metadata.ts
index b12a5b61bb..70932ea63b 100644
--- a/packages/cli/src/commands/api-command-metadata.ts
+++ b/packages/cli/src/commands/api-command-metadata.ts
@@ -1,8 +1,6 @@
import {
publicApiOperations,
- type InputJsonSchema,
- type PublicApiOperationMethod,
- type PublicApiOperationPermit,
+ type PublicApiOperation,
} from "@webstudio-is/protocol";
import type { CommonYargsArgv } from "./yargs-types";
import * as apiCommand from "./api-command";
@@ -10,19 +8,20 @@ import type { ApiCommandName } from "./api-command";
type ApiCommandOptions = (yargs: CommonYargsArgv) => CommonYargsArgv;
-type ApiCommandMetadata = {
- command: ApiCommandName;
- description: string;
- method: PublicApiOperationMethod;
- permit: PublicApiOperationPermit;
- inputFields: readonly string[];
- requiredInputFields: readonly string[];
- inputFieldTypes: Partial<Record<string, "array">>;
- inputSchema: InputJsonSchema;
- outputSchema?: InputJsonSchema;
- requiredOptions?: readonly string[];
- examples: readonly string[];
-};
+type ApiCommandMetadata = Pick<
+ PublicApiOperation<ApiCommandName>,
+ | "command"
+ | "description"
+ | "method"
+ | "permit"
+ | "inputFields"
+ | "requiredInputFields"
+ | "inputFieldTypes"
+ | "inputSchema"
+ | "outputSchema"
+ | "requiredOptions"
+ | "examples"
+>;
export type CliCommandMetadata = ApiCommandMetadata & {
cliCommand: string;
@@ -145,7 +144,7 @@ const apiCommandOptionsByCommand: Partial<
"get-marketplace-product": apiCommand.projectSettingsCommandOptions,
"update-marketplace-product":
apiCommand.updateMarketplaceProductCommandOptions,
- "list-redirects": apiCommand.projectSettingsCommandOptions,
+ "list-redirects": apiCommand.paginatedListCommandOptions,
"create-redirect": apiCommand.createRedirectCommandOptions,
"update-redirect": apiCommand.updateRedirectCommandOptions,
"delete-redirect": apiCommand.deleteRedirectCommandOptions,
@@ -200,9 +199,11 @@ const apiCommandOptionsByCommand: Partial<
"update-variable": apiCommand.updateVariableCommandOptions,
"delete-variable": apiCommand.deleteVariableCommandOptions,
"list-resources": apiCommand.scopedCommandOptions,
+ "list-publishes": apiCommand.paginatedListCommandOptions,
"create-resource": apiCommand.createResourceCommandOptions,
"update-resource": apiCommand.updateResourceCommandOptions,
"delete-resource": apiCommand.deleteResourceCommandOptions,
+ "list-domains": apiCommand.paginatedListCommandOptions,
publish: apiCommand.publishCommandOptions,
"get-publish-job": apiCommand.publishJobCommandOptions,
unpublish: apiCommand.unpublishCommandOptions,
@@ -214,7 +215,7 @@ const apiCommandOptionsByCommand: Partial<
"list-fonts": apiCommand.fontsCommandOptions,
"upload-asset": apiCommand.uploadAssetCommandOptions,
"upload-assets": apiCommand.uploadAssetsCommandOptions,
- "find-asset-usage": apiCommand.assetCommandOptions,
+ "find-asset-usage": apiCommand.assetUsageCommandOptions,
"replace-asset": apiCommand.replaceAssetCommandOptions,
"delete-asset": apiCommand.deleteAssetCommandOptions,
};
diff --git a/packages/cli/src/commands/api-command.test.ts b/packages/cli/src/commands/api-command.test.ts
index 9a11c1dd9a..abeec388ec 100644
--- a/packages/cli/src/commands/api-command.test.ts
+++ b/packages/cli/src/commands/api-command.test.ts
@@ -103,10 +103,10 @@ const dependencies = new Proxy(
}
) as unknown as Parameters<typeof apiCommand>[1];
-const expectJsonOutput = (command: string) => {
+const expectJsonOutput = (command: string, data: unknown = { ok: true }) => {
expect(getLastJsonOutput()).toEqual({
ok: true,
- data: { ok: true },
+ data,
meta: {
command,
projectId: "project-1",
@@ -202,11 +202,13 @@ const expectCommandCall = async ({
call,
connection = {},
inputJson,
+ expectedData,
}: {
options: Parameters<typeof apiCommand>[0];
call: ReturnType<typeof vi.fn>;
connection?: Record<string, unknown>;
inputJson?: unknown;
+ expectedData?: unknown;
}) => {
mockConfig();
if (inputJson !== undefined) {
@@ -217,7 +219,7 @@ const expectCommandCall = async ({
expect(call).toHaveBeenCalledWith(expectConnection(connection));
expectCallUsesDocumentedInputFields(call, options.command);
- expectJsonOutput(options.command);
+ expectJsonOutput(options.command, expectedData);
};
const patchTransactions = [
@@ -347,15 +349,25 @@ const simpleCommandCases = [
],
[
"page list",
- { command: "list-pages", includeFolders: true },
+ {
+ command: "list-pages",
+ cursor: "10",
+ limit: 5,
+ verbose: true,
+ },
"listPages",
- { includeFolders: true },
+ { cursor: "10", limit: 5, verbose: true },
],
[
"folder list",
- { command: "list-folders", includePages: true },
+ {
+ command: "list-folders",
+ cursor: "10",
+ limit: 5,
+ verbose: true,
+ },
"listFolders",
- { includePages: true },
+ { cursor: "10", limit: 5, verbose: true },
],
[
"folder delete",
@@ -398,17 +410,13 @@ test.each(simpleCommandCases)(
test("routes local-capable commands through project session runtime", async () => {
mockConfig();
- await apiCommand(
- { command: "list-pages", includeFolders: true, json: true },
- dependencies
- );
+ await apiCommand({ command: "list-pages", json: true }, dependencies);
const session = createCliProjectSession.mock.results[0]?.value;
expect(session.read).toHaveBeenCalledWith(
"pages.list",
{
projectId: "project-1",
- includeFolders: true,
},
{
permit: "view",
@@ -444,7 +452,7 @@ test("passes refresh to local-capable command session", async () => {
expect(session.refresh).toHaveBeenCalledWith(["pages"]);
expect(session.read).toHaveBeenCalledWith(
"pages.list",
- { projectId: "project-1", includeFolders: undefined },
+ { projectId: "project-1" },
{ permit: "view" }
);
});
@@ -530,6 +538,14 @@ test("parses the documented repeated audit scope options", async () => {
});
});
+test("accepts the opt-in Craft audit scope", async () => {
+ const parsed = await auditCommandOptions(
+ makeCLI([]).exitProcess(false) as unknown as CommonYargsArgv
+ ).parseAsync(["--scopes", "craft"]);
+
+ expect(parsed).toMatchObject({ scopes: ["craft"] });
+});
+
test("prints a compact project audit without --json", async () => {
mockConfig();
apiCalls.audit.mockResolvedValueOnce({
@@ -899,6 +915,19 @@ test("updates marketplace product from input file", async () => {
});
});
+test("lists redirects with shared output detail options", async () => {
+ await expectCommandCall({
+ options: {
+ command: "list-redirects",
+ cursor: "10",
+ limit: 5,
+ verbose: true,
+ },
+ call: apiCalls.listRedirects,
+ connection: { cursor: "10", limit: 5, verbose: true },
+ });
+});
+
test("creates redirect", async () => {
await expectCommandCall({
options: {
@@ -972,6 +1001,19 @@ test("sets redirects from input file", async () => {
});
});
+test("lists breakpoints with shared output detail options", async () => {
+ await expectCommandCall({
+ options: {
+ command: "list-breakpoints",
+ cursor: "10",
+ limit: 5,
+ verbose: true,
+ },
+ call: apiCalls.listBreakpoints,
+ connection: { cursor: "10", limit: 5, verbose: true },
+ });
+});
+
test("creates breakpoint", async () => {
await expectCommandCall({
options: {
@@ -1096,8 +1138,14 @@ test("duplicates page", async () => {
test("lists page templates", async () => {
await expectCommandCall({
- options: { command: "list-page-templates" },
+ options: {
+ command: "list-page-templates",
+ cursor: "10",
+ limit: 5,
+ verbose: true,
+ },
call: apiCalls.listPageTemplates,
+ connection: { cursor: "10", limit: 5, verbose: true },
});
});
@@ -1414,7 +1462,9 @@ test("lists text children with filters", async () => {
instance: "instance-1",
mode: "expression",
contains: "headline",
- maxValueLength: 80,
+ cursor: "10",
+ limit: 5,
+ verbose: true,
},
call: apiCalls.listTexts,
connection: {
@@ -1423,7 +1473,9 @@ test("lists text children with filters", async () => {
instanceId: "instance-1",
mode: "expression",
contains: "headline",
- maxValueLength: 80,
+ cursor: "10",
+ limit: 5,
+ verbose: true,
},
});
});
@@ -1466,9 +1518,20 @@ test("creates variable with parsed value", async () => {
test("lists variables with scope filter", async () => {
await expectCommandCall({
- options: { command: "list-variables", scopeInstance: "body-id" },
+ options: {
+ command: "list-variables",
+ scopeInstance: "body-id",
+ cursor: "10",
+ limit: 5,
+ verbose: true,
+ },
call: apiCalls.listVariables,
- connection: { scopeInstanceId: "body-id" },
+ connection: {
+ scopeInstanceId: "body-id",
+ cursor: "10",
+ limit: 5,
+ verbose: true,
+ },
});
});
@@ -1528,9 +1591,20 @@ test("creates resource from options and exposes data source", async () => {
test("lists resources with scope filter", async () => {
await expectCommandCall({
- options: { command: "list-resources", scopeInstance: "body-id" },
+ options: {
+ command: "list-resources",
+ scopeInstance: "body-id",
+ cursor: "10",
+ limit: 5,
+ verbose: true,
+ },
call: apiCalls.listResources,
- connection: { scopeInstanceId: "body-id" },
+ connection: {
+ scopeInstanceId: "body-id",
+ cursor: "10",
+ limit: 5,
+ verbose: true,
+ },
});
});
@@ -1692,9 +1766,20 @@ test("calls asset list with pagination", async () => {
test("lists fonts with optional system stacks", async () => {
await expectCommandCall({
- options: { command: "list-fonts", includeSystem: false },
+ options: {
+ command: "list-fonts",
+ includeSystem: false,
+ cursor: "10",
+ limit: 5,
+ verbose: true,
+ },
call: apiCalls.listFonts,
- connection: { includeSystem: false },
+ connection: {
+ includeSystem: false,
+ cursor: "10",
+ limit: 5,
+ verbose: true,
+ },
});
});
@@ -1991,9 +2076,21 @@ test("extracts design token from input file", async () => {
test("lists css variables", async () => {
await expectCommandCall({
- options: { command: "list-css-variables", withUsage: true },
+ options: {
+ command: "list-css-variables",
+ withUsage: true,
+ cursor: "10",
+ limit: 5,
+ verbose: true,
+ },
call: apiCalls.listCssVariables,
- connection: { filter: undefined, withUsage: true },
+ connection: {
+ filter: undefined,
+ withUsage: true,
+ cursor: "10",
+ limit: 5,
+ verbose: true,
+ },
});
});
diff --git a/packages/cli/src/commands/api-command.ts b/packages/cli/src/commands/api-command.ts
index 4a455d2a5b..ca20a06478 100644
--- a/packages/cli/src/commands/api-command.ts
+++ b/packages/cli/src/commands/api-command.ts
@@ -152,10 +152,7 @@ export const pathCommandOptions = (yargs: CommonYargsArgv) =>
});
export const pagesCommandOptions = (yargs: CommonYargsArgv) =>
- apiCommandOptions(yargs).option("include-folders", {
- type: "boolean",
- describe: "Include folder records alongside page summaries",
- });
+ outputDetailCommandOptions(apiCommandOptions(yargs));
export const createPageCommandOptions = (yargs: CommonYargsArgv) =>
apiCommandOptions(yargs)
@@ -247,7 +244,10 @@ export const updatePageCommandOptions = (yargs: CommonYargsArgv) =>
});
export const projectSettingsCommandOptions = (yargs: CommonYargsArgv) =>
- apiCommandOptions(yargs);
+ outputDetailCommandOptions(apiCommandOptions(yargs));
+
+export const paginatedListCommandOptions = (yargs: CommonYargsArgv) =>
+ outputDetailCommandOptions(apiCommandOptions(yargs));
export const updateProjectSettingsCommandOptions = (yargs: CommonYargsArgv) =>
requiredInputOption(
@@ -320,7 +320,7 @@ export const setRedirectsCommandOptions = (yargs: CommonYargsArgv) =>
);
export const breakpointCommandOptions = (yargs: CommonYargsArgv) =>
- apiCommandOptions(yargs);
+ outputDetailCommandOptions(apiCommandOptions(yargs));
const breakpointFieldsCommandOptions = (
yargs: CommonYargsArgv,
@@ -412,7 +412,7 @@ export const duplicatePageCommandOptions = (yargs: CommonYargsArgv) =>
});
export const listPageTemplatesCommandOptions = (yargs: CommonYargsArgv) =>
- apiCommandOptions(yargs);
+ outputDetailCommandOptions(apiCommandOptions(yargs));
const pageTemplateFieldsCommandOptions = (
yargs: CommonYargsArgv,
@@ -521,10 +521,7 @@ export const createPageFromTemplateCommandOptions = (yargs: CommonYargsArgv) =>
});
export const foldersCommandOptions = (yargs: CommonYargsArgv) =>
- apiCommandOptions(yargs).option("include-pages", {
- type: "boolean",
- describe: "Include a top-level pages array with page summaries",
- });
+ outputDetailCommandOptions(apiCommandOptions(yargs));
export const createFolderCommandOptions = (yargs: CommonYargsArgv) =>
apiCommandOptions(yargs)
@@ -698,7 +695,7 @@ export const bindPropsCommandOptions = (yargs: CommonYargsArgv) =>
);
export const textListCommandOptions = (yargs: CommonYargsArgv) =>
- apiCommandOptions(yargs)
+ outputDetailCommandOptions(apiCommandOptions(yargs))
.option("page", {
type: "string",
describe: "Limit text nodes to a page id",
@@ -718,10 +715,6 @@ export const textListCommandOptions = (yargs: CommonYargsArgv) =>
.option("contains", {
type: "string",
describe: "Only return text nodes whose value contains this substring",
- })
- .option("max-value-length", {
- type: "number",
- describe: "Truncate returned text values to this character count",
});
export const textUpdateCommandOptions = (yargs: CommonYargsArgv) =>
@@ -878,7 +871,7 @@ export const extractDesignTokenCommandOptions = (yargs: CommonYargsArgv) =>
);
export const cssVariablesCommandOptions = (yargs: CommonYargsArgv) =>
- apiCommandOptions(yargs)
+ outputDetailCommandOptions(apiCommandOptions(yargs))
.option("filter", {
type: "string",
describe: "Only return CSS variables whose name contains this text",
@@ -920,10 +913,13 @@ export const rewriteCssVariableRefsCommandOptions = (yargs: CommonYargsArgv) =>
);
export const scopedCommandOptions = (yargs: CommonYargsArgv) =>
- apiCommandOptions(yargs).option("scope-instance", {
- type: "string",
- describe: "Only return items scoped to this instance id",
- });
+ outputDetailCommandOptions(apiCommandOptions(yargs)).option(
+ "scope-instance",
+ {
+ type: "string",
+ describe: "Only return items scoped to this instance id",
+ }
+ );
export const createVariableCommandOptions = (yargs: CommonYargsArgv) =>
apiCommandOptions(yargs)
@@ -1171,6 +1167,7 @@ export const auditCommandOptions = (yargs: CommonYargsArgv) =>
"assets",
"styles",
"performance",
+ "craft",
] as const,
describe: "Audit only the selected project-quality scopes",
})
@@ -1208,11 +1205,14 @@ export const auditCommandOptions = (yargs: CommonYargsArgv) =>
);
export const fontsCommandOptions = (yargs: CommonYargsArgv) =>
- apiCommandOptions(yargs).option("include-system", {
- type: "boolean",
- default: true,
- describe: "Include built-in system font stacks",
- });
+ outputDetailCommandOptions(apiCommandOptions(yargs)).option(
+ "include-system",
+ {
+ type: "boolean",
+ default: true,
+ describe: "Include built-in system font stacks",
+ }
+ );
export const uploadAssetCommandOptions = (yargs: CommonYargsArgv) =>
requiredInputOption(
@@ -1239,6 +1239,9 @@ export const assetCommandOptions = (yargs: CommonYargsArgv) =>
demandOption: true,
});
+export const assetUsageCommandOptions = (yargs: CommonYargsArgv) =>
+ outputDetailCommandOptions(assetCommandOptions(yargs));
+
export const replaceAssetCommandOptions = (yargs: CommonYargsArgv) =>
confirmOption(
apiCommandOptions(yargs)
@@ -1322,8 +1325,6 @@ export type ApiCommandOptions = {
authPassword?: string;
message?: string;
parentFolder?: string;
- includeFolders?: boolean;
- includePages?: boolean;
sourceTemplate?: string;
targetTemplate?: string;
root?: string;
@@ -1350,7 +1351,6 @@ export type ApiCommandOptions = {
overwrite?: boolean;
scopeRegex?: string;
contains?: string;
- maxValueLength?: number;
breakpoint?: string;
state?: string;
property?: string;
@@ -1366,7 +1366,13 @@ export type ApiCommandOptions = {
cursor?: string;
limit?: number;
scopes?: Array<
- "accessibility" | "security" | "seo" | "assets" | "styles" | "performance"
+ | "accessibility"
+ | "security"
+ | "seo"
+ | "assets"
+ | "styles"
+ | "performance"
+ | "craft"
>;
severities?: Array<"error" | "warning" | "info">;
pageId?: string;
@@ -1953,7 +1959,11 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
);
},
"list-pages": async (options, connection, dependencies) => {
- const input = { includeFolders: options.includeFolders };
+ const input = {
+ cursor: options.cursor,
+ limit: options.limit,
+ verbose: options.verbose,
+ };
return runProjectSessionCommand(
"list-pages",
input,
@@ -2012,10 +2022,10 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
dependencies
);
},
- "get-project-settings": async (_options, connection, dependencies) =>
+ "get-project-settings": async (options, connection, dependencies) =>
runProjectSessionCommand(
"get-project-settings",
- {},
+ { verbose: options.verbose },
connection,
dependencies
),
@@ -2050,8 +2060,17 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
dependencies
);
},
- "list-redirects": async (_options, connection, dependencies) =>
- runProjectSessionCommand("list-redirects", {}, connection, dependencies),
+ "list-redirects": async (options, connection, dependencies) =>
+ runProjectSessionCommand(
+ "list-redirects",
+ {
+ cursor: options.cursor,
+ limit: options.limit,
+ verbose: options.verbose,
+ },
+ connection,
+ dependencies
+ ),
"create-redirect": async (options, connection, dependencies) => {
const input = {
old: requireOption(options.old, "--old"),
@@ -2111,8 +2130,17 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
dependencies
);
},
- "list-breakpoints": async (_options, connection, dependencies) =>
- runProjectSessionCommand("list-breakpoints", {}, connection, dependencies),
+ "list-breakpoints": async (options, connection, dependencies) =>
+ runProjectSessionCommand(
+ "list-breakpoints",
+ {
+ cursor: options.cursor,
+ limit: options.limit,
+ verbose: options.verbose,
+ },
+ connection,
+ dependencies
+ ),
"create-breakpoint": async (options, connection, dependencies) => {
const input: Omit<BreakpointInput, "id"> = {
label: requireOption(options.label, "--label"),
@@ -2198,10 +2226,14 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
dependencies
);
},
- "list-page-templates": async (_options, connection, dependencies) =>
+ "list-page-templates": async (options, connection, dependencies) =>
runProjectSessionCommand(
"list-page-templates",
- {},
+ {
+ cursor: options.cursor,
+ limit: options.limit,
+ verbose: options.verbose,
+ },
connection,
dependencies
),
@@ -2298,7 +2330,11 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
);
},
"list-folders": async (options, connection, dependencies) => {
- const input = { includePages: options.includePages };
+ const input = {
+ cursor: options.cursor,
+ limit: options.limit,
+ verbose: options.verbose,
+ };
return runProjectSessionCommand(
"list-folders",
input,
@@ -2471,7 +2507,9 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
typeof options.instance === "string" ? options.instance : undefined,
mode: textListModeOption(options.mode),
contains: options.contains,
- maxValueLength: options.maxValueLength,
+ cursor: options.cursor,
+ limit: options.limit,
+ verbose: options.verbose,
};
return runProjectSessionCommand(
"list-texts",
@@ -2557,10 +2595,10 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
const input = {
filter: options.filter,
withUsage: options.withUsage,
- sort: designTokenSortOption(options.sort),
cursor: options.cursor,
limit: options.limit,
verbose: options.verbose,
+ sort: designTokenSortOption(options.sort),
};
return runProjectSessionCommand(
"list-design-tokens",
@@ -2654,6 +2692,9 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
const input = {
filter: options.filter,
withUsage: options.withUsage,
+ cursor: options.cursor,
+ limit: options.limit,
+ verbose: options.verbose,
};
return runProjectSessionCommand(
"list-css-variables",
@@ -2709,7 +2750,12 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
);
},
"list-variables": async (options, connection, dependencies) => {
- const input = { scopeInstanceId: options.scopeInstance };
+ const input = {
+ scopeInstanceId: options.scopeInstance,
+ cursor: options.cursor,
+ limit: options.limit,
+ verbose: options.verbose,
+ };
return runProjectSessionCommand(
"list-variables",
input,
@@ -2758,7 +2804,12 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
);
},
"list-resources": async (options, connection, dependencies) => {
- const input = { scopeInstanceId: options.scopeInstance };
+ const input = {
+ scopeInstanceId: options.scopeInstance,
+ cursor: options.cursor,
+ limit: options.limit,
+ verbose: options.verbose,
+ };
return runProjectSessionCommand(
"list-resources",
input,
@@ -2822,8 +2873,17 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
};
return runProjectSessionCommand("publish", input, connection, dependencies);
},
- "list-publishes": async (_options, connection, dependencies) =>
- runProjectSessionCommand("list-publishes", {}, connection, dependencies),
+ "list-publishes": async (options, connection, dependencies) =>
+ runProjectSessionCommand(
+ "list-publishes",
+ {
+ cursor: options.cursor,
+ limit: options.limit,
+ verbose: options.verbose,
+ },
+ connection,
+ dependencies
+ ),
"get-publish-job": async (options, connection, dependencies) => {
const input = { jobId: requireOption(options.job, "--job") };
return runProjectSessionCommand(
@@ -2848,8 +2908,17 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
dependencies
);
},
- "list-domains": async (_options, connection, dependencies) =>
- runProjectSessionCommand("list-domains", {}, connection, dependencies),
+ "list-domains": async (options, connection, dependencies) =>
+ runProjectSessionCommand(
+ "list-domains",
+ {
+ cursor: options.cursor,
+ limit: options.limit,
+ verbose: options.verbose,
+ },
+ connection,
+ dependencies
+ ),
"create-domain": async (options, connection, dependencies) => {
const input = { domain: requireSingleOption(options.domain, "--domain") };
return runProjectSessionCommand(
@@ -2912,7 +2981,12 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
"list-fonts": async (options, connection, dependencies) =>
runProjectSessionCommand(
"list-fonts",
- { includeSystem: options.includeSystem },
+ {
+ includeSystem: options.includeSystem,
+ cursor: options.cursor,
+ limit: options.limit,
+ verbose: options.verbose,
+ },
connection,
dependencies
),
@@ -2943,7 +3017,12 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
);
},
"find-asset-usage": async (options, connection, dependencies) => {
- const input = { assetId: requireSingleOption(options.asset, "--asset") };
+ const input = {
+ assetId: requireSingleOption(options.asset, "--asset"),
+ cursor: options.cursor,
+ limit: options.limit,
+ verbose: options.verbose,
+ };
return runProjectSessionCommand(
"find-asset-usage",
input,
diff --git a/packages/cli/src/commands/connect.test.ts b/packages/cli/src/commands/connect.test.ts
index 5c8416b38e..57d4fba6d8 100644
--- a/packages/cli/src/commands/connect.test.ts
+++ b/packages/cli/src/commands/connect.test.ts
@@ -3,8 +3,6 @@ import { cwd } from "node:process";
import { expect, test, vi } from "vitest";
import {
connect,
- createCodexSnippet,
- defaultServerCommand,
mergeServerConfig,
type ConnectDependencies,
} from "./connect";
@@ -145,6 +143,22 @@ test("writes the cursor config into .cursor/mcp.json", async () => {
);
});
+test.each(["claude", "cursor", "vscode"] as const)(
+ "prints the same generated %s configuration that it writes",
+ async (client) => {
+ const writeDependencies = createDependencies(linkedProject);
+ const printDependencies = createDependencies(linkedProject);
+
+ await connect({ client, print: false }, writeDependencies);
+ await connect({ client, print: true }, printDependencies);
+
+ const [, written] = vi.mocked(writeDependencies.writeFileAtomic).mock
+ .calls[0];
+ expect(written).toContain("webstudio@latest");
+ expect(printDependencies.writeFileAtomic).not.toHaveBeenCalled();
+ }
+);
+
test("prints codex snippet without writing files", async () => {
const dependencies = createDependencies(linkedProject);
@@ -197,16 +211,6 @@ test("rejects an empty server command", async () => {
).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",
diff --git a/packages/cli/src/commands/connect.ts b/packages/cli/src/commands/connect.ts
index c6b031ba49..d67f29fb60 100644
--- a/packages/cli/src/commands/connect.ts
+++ b/packages/cli/src/commands/connect.ts
@@ -4,11 +4,11 @@ import { cwd } from "node:process";
import { log } from "@clack/prompts";
import {
agentClients,
- agentClientTargets,
agentServerName,
+ createAgentQuickstart,
createAgentServerEntry,
- createCodexAgentSnippet,
defaultAgentServerCommand,
+ getAgentClientDefinition,
type AgentClient,
} from "@webstudio-is/protocol";
import {
@@ -18,15 +18,13 @@ import {
} from "../fs-utils";
import { LOCAL_CONFIG_FILE } from "../config";
import { HandledCliError } from "../errors";
+import { isPlainRecord } from "../type-utils";
import type {
CommonYargsArgv,
StrictYargsOptionsToInterface,
} from "./yargs-types";
-export const connectClients = agentClients;
export type ConnectClient = AgentClient;
-export const defaultServerCommand = defaultAgentServerCommand;
-export const mcpServerName = agentServerName;
export type ConnectFileResult =
| "created"
@@ -34,13 +32,6 @@ export type ConnectFileResult =
| "unchanged"
| "blocked-by-invalid-json";
-const jsonClientTargets = agentClientTargets;
-export const createServerEntry = createAgentServerEntry;
-export const createCodexSnippet = createCodexAgentSnippet;
-
-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
@@ -63,17 +54,19 @@ export const mergeServerConfig = ({
} catch {
return { result: "blocked-by-invalid-json" };
}
- if (isJsonObject(parsed) === false) {
+ if (isPlainRecord(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)) {
+ const servers = isPlainRecord(config[rootKey]) ? config[rootKey] : {};
+ if (
+ JSON.stringify(servers[agentServerName]) === JSON.stringify(serverEntry)
+ ) {
return { result: "unchanged" };
}
const content = `${JSON.stringify(
- { ...config, [rootKey]: { ...servers, [mcpServerName]: serverEntry } },
+ { ...config, [rootKey]: { ...servers, [agentServerName]: serverEntry } },
null,
2
)}\n`;
@@ -98,12 +91,12 @@ export const connectOptions = (yargs: CommonYargsArgv) =>
yargs
.positional("client", {
type: "string",
- choices: connectClients,
+ choices: agentClients,
describe: "Agent client to generate the MCP configuration for",
})
.option("command", {
type: "string",
- default: defaultServerCommand,
+ default: defaultAgentServerCommand,
describe:
"Command used by the client to start the Webstudio MCP server over stdio",
})
@@ -140,14 +133,14 @@ export const connect = async (
options: ConnectOptions,
dependencies: ConnectDependencies = defaultDependencies
) => {
- const serverCommand = options.command ?? defaultServerCommand;
+ const serverCommand = options.command ?? defaultAgentServerCommand;
const client = options.client;
if (client === undefined) {
log.message(
[
"Specify the agent client to connect:",
- ...connectClients.map((name) => ` webstudio connect ${name}`),
+ ...agentClients.map((name) => ` webstudio connect ${name}`),
].join("\n")
);
return;
@@ -159,35 +152,35 @@ export const connect = async (
);
}
+ const quickstart = createAgentQuickstart({ client, serverCommand });
+ const configuration = quickstart.configuration;
+ const completionHint = `${quickstart.completion.connection} ${quickstart.completion.firstRead}`;
+
if (client === "codex") {
- const snippet = createCodexSnippet(serverCommand);
log.message(
[
- "Codex reads MCP servers from ~/.codex/config.toml. Add the server with:",
+ `${quickstart.label} reads MCP servers from ${configuration.path}. Add the server with:`,
+ "",
+ ` codex mcp add ${agentServerName} -- ${serverCommand}`,
"",
- ` codex mcp add ${mcpServerName} -- ${serverCommand}`,
+ `or append this snippet to ${configuration.path}:`,
"",
- "or append this snippet to ~/.codex/config.toml:",
+ configuration.content,
"",
- snippet,
+ quickstart.completion.firstRead,
].join("\n")
);
return;
}
- const target = jsonClientTargets[client];
- const serverEntry = createServerEntry(
+ const target = getAgentClientDefinition(client);
+ const serverEntry = createAgentServerEntry(
serverCommand,
"extraServerFields" in target ? target.extraServerFields : undefined
);
if (options.print === true) {
- const { content } = mergeServerConfig({
- current: undefined,
- rootKey: target.rootKey,
- serverEntry,
- });
- log.message(`${target.path}\n\n${content}`);
+ log.message(`${configuration.path}\n\n${configuration.content}`);
return;
}
@@ -209,13 +202,13 @@ export const connect = async (
}
if (result === "unchanged") {
- log.success(`${target.path} is already configured. ${target.hint}`);
+ log.success(`${target.path} is already configured. ${completionHint}`);
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}`
+ `${result === "created" ? "Created" : "Updated"} ${target.path} with the ${agentServerName} MCP server. ${completionHint}`
);
};
diff --git a/packages/cli/src/commands/fixtures/mcp-projects-workflow.json b/packages/cli/src/commands/fixtures/mcp-projects-workflow.json
new file mode 100644
index 0000000000..2313fd8c6d
--- /dev/null
+++ b/packages/cli/src/commands/fixtures/mcp-projects-workflow.json
@@ -0,0 +1,16 @@
+{
+ "concurrency": 2,
+ "calls": [
+ { "tool": "status", "input": {} },
+ { "tool": "audit", "input": {} },
+ {
+ "tool": "update-project-settings",
+ "input": { "meta": { "siteName": "Reviewed" } },
+ "dryRun": true
+ }
+ ],
+ "projects": [
+ { "id": "site-a", "root": "../../../../../../examples/site-a" },
+ { "id": "site-b", "root": "../../../../../../examples/site-b" }
+ ]
+}
diff --git a/packages/cli/src/commands/man.test.ts b/packages/cli/src/commands/man.test.ts
index 849e19933f..abefc9cff3 100644
--- a/packages/cli/src/commands/man.test.ts
+++ b/packages/cli/src/commands/man.test.ts
@@ -8,6 +8,7 @@ import {
apiCommandMetadata,
cliCommandMetadata,
mcpOnlyApiCommandMetadata,
+ topLevelCliCommandMetadata,
} from "./api-command-metadata";
import {
generatedAppDependencyNotes,
@@ -27,10 +28,66 @@ const visibleMcpOnlyApiCommandMetadata = mcpOnlyApiCommandMetadata.filter(
(command) => mcpVisibleToolNames.has(command.command)
);
-test("prints complete manual by default", () => {
+const readLastJsonOutput = () =>
+ JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0]);
+
+test("prints a bounded compact manual by default", () => {
+ vi.spyOn(console, "info").mockImplementation(() => undefined);
+
+ man({ json: true });
+
+ const rawOutput = vi.mocked(console.info).mock.calls.at(-1)?.[0];
+ const output = JSON.parse(rawOutput);
+ expect(output).toMatchObject({
+ topic: "all",
+ detail: "compact",
+ returnedCount: 20,
+ nextCursor: "20",
+ });
+ expect(output.items).toHaveLength(20);
+ expect(rawOutput.length).toBeLessThan(16_000);
+ expect(rawOutput).not.toContain("inputSchema");
+ expect(rawOutput).not.toContain("mcpArgumentExamples");
+});
+
+test("caps compact manual pages and preserves complete catalog parity", () => {
+ vi.spyOn(console, "info").mockImplementation(() => undefined);
+ const ids: string[] = [];
+ let cursor: string | undefined;
+
+ do {
+ man({ json: true, cursor, limit: 500 });
+ const output = readLastJsonOutput();
+ expect(output.returnedCount).toBeLessThanOrEqual(50);
+ ids.push(...output.items.map((item: { id: string }) => item.id));
+ cursor = output.nextCursor;
+ } while (cursor !== undefined);
+
+ expect(ids).toEqual([
+ ...topLevelCliCommandMetadata.map(({ command }) => `cli:${command}`),
+ ...cliCommandMetadata.map(({ cliCommand }) => `api:${cliCommand}`),
+ ...listProjectSessionMcpTools(publicApiOperations).map(
+ ({ name }) => `mcp:${name}`
+ ),
+ ]);
+ expect(new Set(ids).size).toBe(ids.length);
+});
+
+test("rejects invalid compact manual pagination", () => {
+ vi.spyOn(console, "info").mockImplementation(() => undefined);
+
+ expect(() => man({ json: true, cursor: "not-a-cursor" })).toThrow(
+ 'Invalid manual cursor "not-a-cursor".'
+ );
+ expect(() => man({ json: true, limit: 0 })).toThrow(
+ "Manual limit must be at least 1."
+ );
+});
+
+test("prints the complete manual in verbose mode", () => {
vi.spyOn(console, "info").mockImplementation(() => undefined);
- man({ json: false });
+ man({ json: false, verbose: true });
const output = vi.mocked(console.info).mock.calls.at(-1)?.[0];
expect(output).toContain("# Webstudio Complete CLI Manual");
@@ -43,10 +100,10 @@ test("prints complete manual by default", () => {
expect(output).not.toContain("### insert-component");
});
-test("prints complete manual as json by default", () => {
+test("prints the complete manual as verbose json", () => {
vi.spyOn(console, "info").mockImplementation(() => undefined);
- man({ json: true });
+ man({ json: true, verbose: true });
const output = JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0]);
expect(output.topic).toBe("all");
@@ -66,7 +123,7 @@ test("prints complete manual as json by default", () => {
test("prints api manual with patch workflow and examples", () => {
vi.spyOn(console, "info").mockImplementation(() => undefined);
- man({ topic: "api", json: false });
+ man({ topic: "api", json: false, verbose: true });
const output = vi.mocked(console.info).mock.calls.at(-1)?.[0];
expect(output).toContain("webstudio permissions --json");
@@ -110,7 +167,7 @@ test("prints api manual with patch workflow and examples", () => {
test("prints api manual as json", () => {
vi.spyOn(console, "info").mockImplementation(() => undefined);
- man({ topic: "api", json: true });
+ man({ topic: "api", json: true, verbose: true });
const output = JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0]);
expect(output.topic).toBe("api");
@@ -194,9 +251,7 @@ test("prints api manual as json", () => {
for (const command of output.mcpOnlyCommands) {
expect(command).not.toHaveProperty("required");
}
- expect(output.taskRecipes.pages).toContain(
- 'MCP tool: list-pages {"includeFolders":true}'
- );
+ expect(output.taskRecipes.pages).toContain("MCP tool: list-pages {}");
expect(output.useCaseScenarios).toEqual(
expect.arrayContaining([
expect.objectContaining({
@@ -289,7 +344,7 @@ test("prints api manual as json", () => {
test("prints llm manual with discovery rules", () => {
vi.spyOn(console, "info").mockImplementation(() => undefined);
- man({ topic: "llm", json: false });
+ man({ topic: "llm", json: false, verbose: true });
const output = vi.mocked(console.info).mock.calls.at(-1)?.[0];
expect(output).toContain("webstudio schema api");
@@ -351,7 +406,7 @@ test("prints llm manual with discovery rules", () => {
test("prints project-editing manual as llm alias", () => {
vi.spyOn(console, "info").mockImplementation(() => undefined);
- man({ topic: "project-editing", json: false });
+ man({ topic: "project-editing", json: false, verbose: true });
const output = vi.mocked(console.info).mock.calls.at(-1)?.[0];
expect(output).toContain("## LLM Implementation Process");
@@ -362,7 +417,7 @@ test("prints project-editing manual as llm alias", () => {
test("prints project-editing manual as json alias", () => {
vi.spyOn(console, "info").mockImplementation(() => undefined);
- man({ topic: "project-editing", json: true });
+ man({ topic: "project-editing", json: true, verbose: true });
const output = JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0]);
expect(output.topic).toBe("project-editing");
@@ -378,7 +433,7 @@ test("prints project-editing manual as json alias", () => {
test("prints llm manual as json with implementation process", () => {
vi.spyOn(console, "info").mockImplementation(() => undefined);
- man({ topic: "llm", json: true });
+ man({ topic: "llm", json: true, verbose: true });
const output = JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0]);
expect(output.topic).toBe("llm");
@@ -446,7 +501,7 @@ test("prints llm manual as json with implementation process", () => {
test("prints mcp manual with startup and JSON argument examples", () => {
vi.spyOn(console, "info").mockImplementation(() => undefined);
- man({ topic: "mcp", json: false });
+ man({ topic: "mcp", json: false, verbose: true });
const output = vi.mocked(console.info).mock.calls.at(-1)?.[0];
expect(output).toContain("# Webstudio MCP Manual");
@@ -479,7 +534,7 @@ test("prints mcp manual with startup and JSON argument examples", () => {
test("prints mcp manual as json", () => {
vi.spyOn(console, "info").mockImplementation(() => undefined);
- man({ topic: "mcp", json: true });
+ man({ topic: "mcp", json: true, verbose: true });
const output = JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0]);
expect(output.topic).toBe("mcp");
diff --git a/packages/cli/src/commands/man.ts b/packages/cli/src/commands/man.ts
index 13ebe5222d..df1f5d9cee 100644
--- a/packages/cli/src/commands/man.ts
+++ b/packages/cli/src/commands/man.ts
@@ -40,15 +40,41 @@ export const manOptions = (yargs: CommonYargsArgv) =>
type: "boolean",
describe: "Print the manual topic as structured JSON",
default: false,
+ })
+ .option("cursor", {
+ type: "string",
+ describe: "Continue a compact manual listing from this cursor",
+ })
+ .option("limit", {
+ type: "number",
+ describe: "Maximum compact manual entries to return (1-50)",
+ default: 20,
+ })
+ .option("verbose", {
+ type: "boolean",
+ describe: "Print the complete manual instead of a compact listing",
+ default: false,
});
type ManOptions = Omit<
StrictYargsOptionsToInterface<typeof manOptions>,
- "topic"
+ "topic" | "cursor" | "limit" | "verbose"
> & {
topic?: string;
+ cursor?: string;
+ limit?: number;
+ verbose?: boolean;
};
+const maxManualPageSize = 50;
+const defaultManualPageSize = 20;
+const compactDescriptionLength = 240;
+
+const compactDescription = (value: string) =>
+ value.length <= compactDescriptionLength
+ ? value
+ : `${value.slice(0, compactDescriptionLength - 1)}…`;
+
const commandIndex = cliCommandMetadata
.map((command) => {
const required = command.requiredOptions?.join(", ") ?? "json";
@@ -752,6 +778,102 @@ const topics = {
},
};
+type ManualCatalogItem = {
+ id: string;
+ command: string;
+ surface: "cli" | "api" | "mcp";
+ use: string;
+};
+
+const topLevelManualItems: ManualCatalogItem[] = topLevelCommandCatalog.map(
+ ({ command, use }) => ({
+ id: `cli:${command}`,
+ command,
+ surface: "cli",
+ use: compactDescription(use),
+ })
+);
+
+const apiManualItems: ManualCatalogItem[] = commandCatalog.map(
+ ({ command, use }) => ({
+ id: `api:${command}`,
+ command,
+ surface: "api",
+ use: compactDescription(use),
+ })
+);
+
+const mcpManualItems: ManualCatalogItem[] = listProjectSessionMcpTools(
+ publicApiOperations
+).map(({ name, description }) => ({
+ id: `mcp:${name}`,
+ command: name,
+ surface: "mcp",
+ use: compactDescription(description),
+}));
+
+const manualItemsByTopic: Record<keyof typeof topics, ManualCatalogItem[]> = {
+ all: [...topLevelManualItems, ...apiManualItems, ...mcpManualItems],
+ api: [...apiManualItems, ...mcpManualItems],
+ llm: [...topLevelManualItems, ...apiManualItems, ...mcpManualItems],
+ "project-editing": [...apiManualItems, ...mcpManualItems],
+ mcp: mcpManualItems,
+};
+
+const parseManualCursor = (cursor: string | undefined) => {
+ if (cursor === undefined) {
+ return 0;
+ }
+ if (/^(0|[1-9]\d*)$/.test(cursor) === false) {
+ throw new Error(`Invalid manual cursor "${cursor}".`);
+ }
+ return Number(cursor);
+};
+
+const getCompactManual = (
+ topic: keyof typeof topics,
+ options: Pick<ManOptions, "cursor" | "limit">
+) => {
+ const items = manualItemsByTopic[topic];
+ const offset = parseManualCursor(options.cursor);
+ const requestedLimit = Math.floor(options.limit ?? defaultManualPageSize);
+ if (requestedLimit < 1) {
+ throw new Error("Manual limit must be at least 1.");
+ }
+ const limit = Math.min(requestedLimit, maxManualPageSize);
+ const page = items.slice(offset, offset + limit);
+ return {
+ topic,
+ title: topics[topic].json.title,
+ detail: "compact" as const,
+ usage:
+ "Use cursor to continue this listing. Pass --verbose for the complete manual and full examples.",
+ total: items.length,
+ returnedCount: page.length,
+ nextCursor:
+ offset + page.length < items.length
+ ? String(offset + page.length)
+ : undefined,
+ items: page,
+ };
+};
+
+const renderCompactManual = (manual: ReturnType<typeof getCompactManual>) =>
+ [
+ `# ${manual.title}`,
+ "",
+ manual.usage,
+ "",
+ ...manual.items.map(
+ ({ command, surface, use }) => `- ${command} (${surface}): ${use}`
+ ),
+ "",
+ `Showing ${manual.returnedCount} of ${manual.total}.`,
+ ...(manual.nextCursor === undefined
+ ? []
+ : [`Continue with --cursor ${manual.nextCursor}.`]),
+ ].join("\n");
+
export const man = (options: ManOptions) => {
const topic = options.topic ?? "all";
const entry = topics[topic as keyof typeof topics];
@@ -765,6 +887,18 @@ ${Object.keys(topics)
.join("\n")}`);
return;
}
+ if (options.verbose !== true) {
+ const compactManual = getCompactManual(
+ topic as keyof typeof topics,
+ options
+ );
+ if (options.json === true) {
+ printJson(compactManual);
+ return;
+ }
+ console.info(renderCompactManual(compactManual));
+ return;
+ }
if (options.json === true) {
printJson(entry.json);
return;
diff --git a/packages/cli/src/commands/mcp-batch.test.ts b/packages/cli/src/commands/mcp-batch.test.ts
new file mode 100644
index 0000000000..c6bc05ba64
--- /dev/null
+++ b/packages/cli/src/commands/mcp-batch.test.ts
@@ -0,0 +1,310 @@
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { afterEach, expect, test, vi } from "vitest";
+import {
+ assertMcpBatchMutationApproved,
+ parseMcpProjectsManifest,
+ runMcpProjectBatch,
+ type McpBatchCall,
+} from "./mcp-batch";
+
+const tempDirs: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ tempDirs
+ .splice(0)
+ .map((directory) => rm(directory, { recursive: true, force: true }))
+ );
+});
+
+const parseCalls = (value: unknown): McpBatchCall[] =>
+ (value as Array<{ tool: string; dryRun?: boolean }>).map((call) => ({
+ tool: call.tool,
+ input: {},
+ dryRun: call.dryRun === true,
+ }));
+
+test("requires explicit approval only for committed mutations", () => {
+ const mutation = { tool: "update-page", input: {}, dryRun: false };
+
+ expect(() =>
+ assertMcpBatchMutationApproved({
+ projectId: "site-a",
+ call: mutation,
+ method: "mutation",
+ approved: false,
+ })
+ ).toThrow(/--approve-mutations/);
+ expect(() =>
+ assertMcpBatchMutationApproved({
+ projectId: "site-a",
+ call: { ...mutation, dryRun: true },
+ method: "mutation",
+ approved: false,
+ })
+ ).not.toThrow();
+ expect(() =>
+ assertMcpBatchMutationApproved({
+ projectId: "site-a",
+ call: mutation,
+ method: "mutation",
+ approved: true,
+ })
+ ).not.toThrow();
+});
+
+test("parses shared calls and project roots relative to the manifest", () => {
+ const manifest = parseMcpProjectsManifest({
+ value: {
+ calls: [{ tool: "status" }],
+ projects: [
+ { id: "one", root: "../one" },
+ { id: "two", root: "../two", calls: [{ tool: "audit" }] },
+ ],
+ concurrency: 3,
+ },
+ baseDirectory: "/workspace/manifests",
+ defaultProgressDirectory: "/workspace",
+ parseCalls,
+ });
+
+ expect(manifest.projects).toMatchObject([
+ { id: "one", root: "/workspace/one", calls: [{ tool: "status" }] },
+ { id: "two", root: "/workspace/two", calls: [{ tool: "audit" }] },
+ ]);
+ expect(manifest.concurrency).toBe(3);
+ expect(manifest.progressFile).toMatch(
+ /^\/workspace\/\.webstudio\/mcp-batch-[a-f0-9]{16}\.json$/
+ );
+});
+
+test("rejects unbounded concurrency", () => {
+ expect(() =>
+ parseMcpProjectsManifest({
+ value: {
+ calls: [{ tool: "status" }],
+ projects: ["one"],
+ concurrency: 17,
+ },
+ baseDirectory: "/workspace",
+ defaultProgressDirectory: "/workspace",
+ parseCalls,
+ })
+ ).toThrow(/integer from 1 to 16/);
+});
+
+test("keeps the minimally prompted projects workflow fixture valid", async () => {
+ const fixtureUrl = new URL(
+ "./fixtures/mcp-projects-workflow.json",
+ import.meta.url
+ );
+ const manifest = parseMcpProjectsManifest({
+ value: JSON.parse(await readFile(fixtureUrl, "utf8")),
+ baseDirectory: path.dirname(fixtureUrl.pathname),
+ defaultProgressDirectory: "/workspace",
+ parseCalls,
+ });
+
+ expect(manifest.projects).toHaveLength(2);
+ expect(manifest.projects[0]?.calls.map((call) => call.tool)).toEqual([
+ "status",
+ "audit",
+ "update-project-settings",
+ ]);
+ expect(manifest.projects[0]?.calls[2]?.dryRun).toBe(true);
+});
+
+test("runs projects with bounded concurrency and isolates failures", async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), "mcp-batch-"));
+ tempDirs.push(directory);
+ const manifest = parseMcpProjectsManifest({
+ value: {
+ calls: [{ tool: "status" }],
+ projects: ["one", "two", "three"],
+ progressFile: "progress.json",
+ concurrency: 2,
+ },
+ baseDirectory: directory,
+ defaultProgressDirectory: directory,
+ parseCalls,
+ });
+ let active = 0;
+ let maximumActive = 0;
+ const reports = await runMcpProjectBatch({
+ manifest,
+ resume: true,
+ runProject: async ({ project, callSucceeded }) => {
+ active++;
+ maximumActive = Math.max(maximumActive, active);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ active--;
+ if (project.id === "two") {
+ throw Object.assign(new Error("not linked"), { code: "UNAUTHORIZED" });
+ }
+ await callSucceeded(1);
+ },
+ });
+
+ expect(maximumActive).toBe(2);
+ expect(reports.map((report) => report.status)).toEqual([
+ "succeeded",
+ "failed",
+ "succeeded",
+ ]);
+ expect(reports[1]?.error).toEqual({
+ code: "UNAUTHORIZED",
+ message: "not linked",
+ });
+});
+
+test("resume never retries successful calls or completed projects", async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), "mcp-batch-resume-"));
+ tempDirs.push(directory);
+ const manifest = parseMcpProjectsManifest({
+ value: {
+ calls: [{ tool: "status" }, { tool: "audit" }],
+ projects: ["one", "two"],
+ progressFile: "progress.json",
+ },
+ baseDirectory: directory,
+ defaultProgressDirectory: directory,
+ parseCalls,
+ });
+ const firstStarts: Record<string, number> = {};
+ await runMcpProjectBatch({
+ manifest,
+ resume: true,
+ runProject: async ({ project, startCall, callSucceeded }) => {
+ firstStarts[project.id] = startCall;
+ await callSucceeded(1);
+ if (project.id === "one") {
+ throw new Error("temporary failure");
+ }
+ await callSucceeded(2);
+ },
+ });
+ const secondRun = vi.fn(
+ async ({
+ project,
+ startCall,
+ callSucceeded,
+ }: Parameters<
+ Parameters<typeof runMcpProjectBatch>[0]["runProject"]
+ >[0]) => {
+ expect(project.id).toBe("one");
+ expect(startCall).toBe(1);
+ await callSucceeded(2);
+ }
+ );
+ const reports = await runMcpProjectBatch({
+ manifest,
+ resume: true,
+ runProject: secondRun,
+ });
+
+ expect(firstStarts).toEqual({ one: 0, two: 0 });
+ expect(secondRun).toHaveBeenCalledTimes(1);
+ expect(reports.map((report) => report.status)).toEqual([
+ "succeeded",
+ "skipped",
+ ]);
+ expect(
+ JSON.parse(await readFile(manifest.progressFile, "utf8"))
+ ).toMatchObject({
+ projects: {
+ one: { nextCall: 2, completed: true },
+ two: { nextCall: 2, completed: true },
+ },
+ });
+});
+
+test("never replays a mutation with an ambiguous interrupted result", async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), "mcp-batch-ambiguous-"));
+ tempDirs.push(directory);
+ const manifest = parseMcpProjectsManifest({
+ value: {
+ calls: [{ tool: "update-page" }],
+ projects: ["one"],
+ progressFile: "progress.json",
+ },
+ baseDirectory: directory,
+ defaultProgressDirectory: directory,
+ parseCalls,
+ });
+
+ await runMcpProjectBatch({
+ manifest,
+ resume: true,
+ runProject: async ({ callStarted }) => {
+ await callStarted(0, false);
+ throw new Error("connection closed after dispatch");
+ },
+ });
+ const resumedRun = vi.fn();
+ const reports = await runMcpProjectBatch({
+ manifest,
+ resume: true,
+ runProject: resumedRun,
+ });
+
+ expect(resumedRun).not.toHaveBeenCalled();
+ expect(reports).toEqual([
+ expect.objectContaining({
+ status: "failed",
+ completedCalls: 0,
+ error: expect.objectContaining({ code: "AMBIGUOUS_MUTATION_RESULT" }),
+ }),
+ ]);
+});
+
+test("resumes projects whose ids are object prototype names", async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), "mcp-batch-prototype-"));
+ tempDirs.push(directory);
+ const manifest = parseMcpProjectsManifest({
+ value: {
+ calls: [{ tool: "status" }],
+ projects: [{ id: "__proto__", root: "site" }],
+ progressFile: "progress.json",
+ },
+ baseDirectory: directory,
+ defaultProgressDirectory: directory,
+ parseCalls,
+ });
+ const firstRun = vi.fn(
+ async ({
+ callSucceeded,
+ }: Parameters<
+ Parameters<typeof runMcpProjectBatch>[0]["runProject"]
+ >[0]) => {
+ await callSucceeded(1);
+ }
+ );
+
+ await runMcpProjectBatch({ manifest, resume: true, runProject: firstRun });
+
+ const secondRun = vi.fn();
+ const reports = await runMcpProjectBatch({
+ manifest,
+ resume: true,
+ runProject: secondRun,
+ });
+
+ expect(firstRun).toHaveBeenCalledOnce();
+ expect(secondRun).not.toHaveBeenCalled();
+ expect(reports).toEqual([
+ {
+ id: "__proto__",
+ root: path.join(directory, "site"),
+ status: "skipped",
+ completedCalls: 1,
+ totalCalls: 1,
+ },
+ ]);
+ expect(
+ JSON.parse(await readFile(manifest.progressFile, "utf8")).projects[
+ "__proto__"
+ ]
+ ).toEqual({ nextCall: 1, completed: true });
+});
diff --git a/packages/cli/src/commands/mcp-batch.ts b/packages/cli/src/commands/mcp-batch.ts
new file mode 100644
index 0000000000..4c951d236d
--- /dev/null
+++ b/packages/cli/src/commands/mcp-batch.ts
@@ -0,0 +1,331 @@
+import { createHash } from "node:crypto";
+import { mkdir, readFile } from "node:fs/promises";
+import path from "node:path";
+import { writeFileAtomic } from "../fs-utils";
+import { isPlainRecord } from "../type-utils";
+
+export type McpBatchCall = {
+ tool: string;
+ input: unknown;
+ dryRun: boolean;
+};
+
+export type McpBatchProject = {
+ id: string;
+ root: string;
+ calls: McpBatchCall[];
+};
+
+export type McpProjectsManifest = {
+ projects: McpBatchProject[];
+ concurrency: number;
+ progressFile: string;
+ fingerprint: string;
+};
+
+type PersistedProjectProgress = {
+ nextCall: number;
+ completed: boolean;
+ ambiguousMutationCall?: number;
+};
+
+type PersistedBatchProgress = {
+ version: 1;
+ fingerprint: string;
+ projects: Record<string, PersistedProjectProgress>;
+};
+
+const createProgressProjects = () =>
+ Object.create(null) as Record<string, PersistedProjectProgress>;
+
+const maximumConcurrency = 16;
+
+export type McpBatchProjectReport = {
+ id: string;
+ root: string;
+ status: "succeeded" | "failed" | "skipped";
+ completedCalls: number;
+ totalCalls: number;
+ error?: { code: string; message: string };
+};
+
+const parsePositiveInteger = (value: unknown, fallback: number) => {
+ if (value === undefined) {
+ return fallback;
+ }
+ if (
+ typeof value !== "number" ||
+ Number.isInteger(value) === false ||
+ value < 1 ||
+ value > maximumConcurrency
+ ) {
+ throw new Error(
+ `MCP batch concurrency must be an integer from 1 to ${maximumConcurrency}.`
+ );
+ }
+ return value;
+};
+
+export const isMcpProjectsManifest = (
+ value: unknown
+): value is Record<string, unknown> & { projects: unknown[] } =>
+ isPlainRecord(value) && Array.isArray(value.projects);
+
+export const assertMcpBatchMutationApproved = ({
+ projectId,
+ call,
+ method,
+ approved,
+}: {
+ projectId: string;
+ call: McpBatchCall;
+ method: string | undefined;
+ approved: boolean;
+}) => {
+ if (call.dryRun || method !== "mutation" || approved) {
+ return;
+ }
+ throw Object.assign(
+ new Error(
+ `Project "${projectId}" includes committed mutation "${call.tool}". Re-run with --approve-mutations after reviewing the manifest, or use --dry-run.`
+ ),
+ { code: "MUTATION_APPROVAL_REQUIRED" }
+ );
+};
+
+export const parseMcpProjectsManifest = ({
+ value,
+ baseDirectory,
+ defaultProgressDirectory,
+ parseCalls,
+ concurrency,
+}: {
+ value: unknown;
+ baseDirectory: string;
+ defaultProgressDirectory: string;
+ parseCalls: (value: unknown) => McpBatchCall[];
+ concurrency?: number;
+}): McpProjectsManifest => {
+ if (isMcpProjectsManifest(value) === false) {
+ throw new Error('MCP batch input must include a "projects" array.');
+ }
+ if (value.projects.length === 0) {
+ throw new Error("MCP batch input must include at least one project.");
+ }
+ const sharedCalls =
+ value.calls === undefined ? undefined : parseCalls(value.calls);
+ const seenRoots = new Set<string>();
+ const seenIds = new Set<string>();
+ const projects = value.projects.map((entry, index): McpBatchProject => {
+ const project = typeof entry === "string" ? { root: entry } : entry;
+ if (
+ isPlainRecord(project) === false ||
+ typeof project.root !== "string" ||
+ project.root.trim() === ""
+ ) {
+ throw new Error(
+ `MCP batch projects[${index}].root must be a non-empty string.`
+ );
+ }
+ const root = path.resolve(baseDirectory, project.root);
+ const id =
+ typeof project.id === "string" && project.id.trim() !== ""
+ ? project.id
+ : path.basename(root);
+ if (seenRoots.has(root)) {
+ throw new Error(`MCP batch project root is duplicated: ${root}`);
+ }
+ if (seenIds.has(id)) {
+ throw new Error(`MCP batch project id is duplicated: ${id}`);
+ }
+ seenRoots.add(root);
+ seenIds.add(id);
+ const calls =
+ project.calls === undefined ? sharedCalls : parseCalls(project.calls);
+ if (calls === undefined) {
+ throw new Error(
+ `MCP batch project "${id}" needs calls or a top-level calls array.`
+ );
+ }
+ return { id, root, calls };
+ });
+ const fingerprint = createHash("sha256")
+ .update(JSON.stringify(projects))
+ .digest("hex")
+ .slice(0, 16);
+ const progressFile =
+ typeof value.progressFile === "string" && value.progressFile.trim() !== ""
+ ? path.resolve(baseDirectory, value.progressFile)
+ : path.join(
+ defaultProgressDirectory,
+ ".webstudio",
+ `mcp-batch-${fingerprint}.json`
+ );
+ return {
+ projects,
+ concurrency: parsePositiveInteger(concurrency ?? value.concurrency, 2),
+ progressFile,
+ fingerprint,
+ };
+};
+
+const readProgress = async (
+ manifest: McpProjectsManifest,
+ resume: boolean
+): Promise<PersistedBatchProgress> => {
+ if (resume) {
+ try {
+ const progress = JSON.parse(
+ await readFile(manifest.progressFile, "utf8")
+ ) as PersistedBatchProgress;
+ if (
+ progress.version === 1 &&
+ progress.fingerprint === manifest.fingerprint &&
+ isPlainRecord(progress.projects)
+ ) {
+ return {
+ ...progress,
+ // Project ids come from user-controlled manifests. A null-prototype
+ // map keeps ids such as "__proto__" ordinary progress keys.
+ projects: Object.assign(createProgressProjects(), progress.projects),
+ };
+ }
+ } catch (error) {
+ if (isPlainRecord(error) === false || error.code !== "ENOENT") {
+ throw error;
+ }
+ }
+ }
+ return {
+ version: 1,
+ fingerprint: manifest.fingerprint,
+ projects: createProgressProjects(),
+ };
+};
+
+const toError = (error: unknown) => {
+ if (isPlainRecord(error) && typeof error.message === "string") {
+ return {
+ code: typeof error.code === "string" ? error.code : "MCP_PROJECT_FAILED",
+ message: error.message,
+ };
+ }
+ return {
+ code: "MCP_PROJECT_FAILED",
+ message: error instanceof Error ? error.message : String(error),
+ };
+};
+
+export const runMcpProjectBatch = async ({
+ manifest,
+ resume,
+ runProject,
+}: {
+ manifest: McpProjectsManifest;
+ resume: boolean;
+ runProject: (options: {
+ project: McpBatchProject;
+ startCall: number;
+ callStarted: (call: number, replaySafe: boolean) => Promise<void>;
+ callSucceeded: (nextCall: number) => Promise<void>;
+ }) => Promise<void>;
+}) => {
+ const progress = await readProgress(manifest, resume);
+ let pendingWrite = Promise.resolve();
+ const persist = () => {
+ pendingWrite = pendingWrite.then(async () => {
+ await mkdir(path.dirname(manifest.progressFile), { recursive: true });
+ await writeFileAtomic(
+ manifest.progressFile,
+ `${JSON.stringify(progress, undefined, 2)}\n`
+ );
+ });
+ return pendingWrite;
+ };
+ const reports: McpBatchProjectReport[] = new Array(manifest.projects.length);
+ let cursor = 0;
+ const worker = async () => {
+ while (cursor < manifest.projects.length) {
+ const index = cursor++;
+ const project = manifest.projects[index]!;
+ const saved = progress.projects[project.id];
+ if (saved?.completed === true) {
+ reports[index] = {
+ id: project.id,
+ root: project.root,
+ status: "skipped",
+ completedCalls: project.calls.length,
+ totalCalls: project.calls.length,
+ };
+ continue;
+ }
+ if (resume && saved?.ambiguousMutationCall !== undefined) {
+ reports[index] = {
+ id: project.id,
+ root: project.root,
+ status: "failed",
+ completedCalls: saved.nextCall,
+ totalCalls: project.calls.length,
+ error: {
+ code: "AMBIGUOUS_MUTATION_RESULT",
+ message: `Mutation call ${saved.ambiguousMutationCall + 1} may have committed before the previous run stopped. Inspect the project before deciding whether to continue; it will not be replayed automatically.`,
+ },
+ };
+ continue;
+ }
+ const startCall = resume
+ ? Math.min(saved?.nextCall ?? 0, project.calls.length)
+ : 0;
+ try {
+ await runProject({
+ project,
+ startCall,
+ callStarted: async (call, replaySafe) => {
+ if (replaySafe) {
+ return;
+ }
+ progress.projects[project.id] = {
+ nextCall: call,
+ completed: false,
+ ambiguousMutationCall: call,
+ };
+ await persist();
+ },
+ callSucceeded: async (nextCall) => {
+ progress.projects[project.id] = { nextCall, completed: false };
+ await persist();
+ },
+ });
+ progress.projects[project.id] = {
+ nextCall: project.calls.length,
+ completed: true,
+ };
+ await persist();
+ reports[index] = {
+ id: project.id,
+ root: project.root,
+ status: "succeeded",
+ completedCalls: project.calls.length,
+ totalCalls: project.calls.length,
+ };
+ } catch (error) {
+ reports[index] = {
+ id: project.id,
+ root: project.root,
+ status: "failed",
+ completedCalls: progress.projects[project.id]?.nextCall ?? startCall,
+ totalCalls: project.calls.length,
+ error: toError(error),
+ };
+ }
+ }
+ };
+ await Promise.all(
+ Array.from(
+ { length: Math.min(manifest.concurrency, manifest.projects.length) },
+ worker
+ )
+ );
+ await pendingWrite;
+ return reports;
+};
diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.ts
index d1bdce7b9e..db110874e7 100644
--- a/packages/cli/src/commands/mcp.test.ts
+++ b/packages/cli/src/commands/mcp.test.ts
@@ -114,9 +114,21 @@ test("documents MCP stdio startup and discovery tools", () => {
describe: "Run local-capable mutation tools without committing",
})
);
+ expect(runYargs.option).toHaveBeenCalledWith(
+ "approve-mutations",
+ expect.objectContaining({ default: false })
+ );
+ expect(runYargs.option).toHaveBeenCalledWith(
+ "concurrency",
+ expect.objectContaining({ type: "number" })
+ );
+ expect(runYargs.option).toHaveBeenCalledWith(
+ "resume",
+ expect.objectContaining({ default: true })
+ );
expect(yargs.command).toHaveBeenCalledWith(
["run <input>"],
- "Run multiple MCP tool calls in one shared CLI session from JSON or a file",
+ "Run an MCP workflow manifest for one or more linked projects",
expect.any(Function),
expect.any(Function)
);
diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.ts
index 46af49dc1e..0ca893aad7 100644
--- a/packages/cli/src/commands/mcp.ts
+++ b/packages/cli/src/commands/mcp.ts
@@ -5,6 +5,7 @@ import {
connectProjectSessionMcpServer,
createProjectSessionMcpCore,
createMcpStdioTransport,
+ getProjectSessionMcpCheckpoint,
} from "@webstudio-is/project-build/mcp";
import type { BuilderNamespace } from "@webstudio-is/project-build/contracts";
import { diffPngFiles } from "@webstudio-is/project-build/visual";
@@ -35,7 +36,7 @@ import {
writeCliProjectSessionDataFile,
} from "../project-session";
import { executeProjectSessionApiOperation } from "../project-session-api";
-import { createPreviewController } from "../preview-server";
+import { createPreviewController, findAvailablePort } from "../preview-server";
import {
captureScreenshotWithBrowserInstall,
createScreenshotCaptureSession,
@@ -52,6 +53,16 @@ import {
} from "../mcp-guidance";
import { readCliDoc } from "../docs";
import { printJson } from "../json-output";
+import { isPlainRecord } from "../type-utils";
+import { inspectGeneratedBuildMetrics } from "../generated-build-metrics";
+import { LOCAL_DATA_FILE } from "../config";
+import {
+ assertMcpBatchMutationApproved,
+ isMcpProjectsManifest,
+ parseMcpProjectsManifest,
+ runMcpProjectBatch,
+ type McpBatchCall,
+} from "./mcp-batch";
import { apiCompatibilityHeaders } from "./api";
import { importProject as importProjectCommand } from "./import";
import {
@@ -100,6 +111,7 @@ type McpScreenshotInput = {
fullPage?: boolean;
includeImageMetrics?: boolean;
includeResourceMetrics?: boolean;
+ includeContrastMetrics?: boolean;
browser?: CaptureScreenshotInput["browser"];
browserPath?: string;
waitUntil?: CaptureScreenshotInput["waitUntil"];
@@ -121,11 +133,7 @@ type CliMcpHost = Parameters<
typeof createProjectSessionMcpCore<PublicApiCommand>
>[0];
-type McpRunCall = {
- tool: string;
- input: unknown;
- dryRun: boolean;
-};
+type McpRunCall = McpBatchCall;
export const prepareMcpProjectSession = async (
session: StartableProjectSession
@@ -188,17 +196,14 @@ export const createMcpStatusReporter = (
},
});
-const isRecord = (value: unknown): value is Record<string, unknown> =>
- typeof value === "object" && value !== null && Array.isArray(value) === false;
-
const createMcpInputError = (message: string, code: string) =>
Object.assign(new Error(message), { code });
const hasAssetName = (value: unknown): value is { name: string } =>
- isRecord(value) && typeof value.name === "string";
+ isPlainRecord(value) && typeof value.name === "string";
const getMcpUploadAssetInput = (input: unknown) => {
- if (isRecord(input) === false || hasAssetName(input.asset) === false) {
+ if (isPlainRecord(input) === false || hasAssetName(input.asset) === false) {
throw new Error("upload-asset requires an asset object.");
}
return createLocalUploadAssetInput({
@@ -211,7 +216,7 @@ const getMcpUploadAssetInput = (input: unknown) => {
const getMcpUploadAssetsInput = (input: unknown) => {
if (
- isRecord(input) === false ||
+ isPlainRecord(input) === false ||
Array.isArray(input.assets) === false ||
input.assets.every(hasAssetName) === false
) {
@@ -278,28 +283,11 @@ const assertPersistedMcpCheckpointAcknowledged = async (
};
const getResultCheckpoint = (tool: string, structuredContent: unknown) => {
- if (isRecord(structuredContent) === false) {
+ if (isPlainRecord(structuredContent) === false) {
return;
}
const data = structuredContent.data;
- if (isRecord(data) === false) {
- return;
- }
- const checkpoint = data.checkpoint;
- if (
- isRecord(checkpoint) &&
- checkpoint.required === true &&
- typeof checkpoint.instruction === "string"
- ) {
- return {
- tool,
- message: checkpoint.instruction,
- nextCommand:
- typeof checkpoint.nextCommand === "string"
- ? checkpoint.nextCommand
- : undefined,
- };
- }
+ return getProjectSessionMcpCheckpoint(tool, data);
};
const updatePersistedMcpCheckpoint = async ({
@@ -468,6 +456,7 @@ const createMcpPreviewHandlers = ({
fullPage: input.fullPage,
includeImageMetrics: input.includeImageMetrics,
includeResourceMetrics: input.includeResourceMetrics,
+ includeContrastMetrics: input.includeContrastMetrics,
browser: input.browser ?? "auto",
browserPath: input.browserPath,
waitUntil: input.waitUntil,
@@ -501,7 +490,12 @@ const createMcpPreviewHandlers = ({
restart: true,
});
markFresh();
- return result;
+ return {
+ ...result,
+ generatedBuildMetrics: await inspectGeneratedBuildMetrics(
+ previewProject.cwd
+ ),
+ };
},
async captureScreenshot(
input: McpScreenshotInput,
@@ -618,7 +612,7 @@ export const mcpOptions = (yargs: CommonYargsArgv) =>
)
.command(
["run <input>"],
- "Run multiple MCP tool calls in one shared CLI session from JSON or a file",
+ "Run an MCP workflow manifest for one or more linked projects",
mcpRunOptions,
mcpRun
)
@@ -644,6 +638,10 @@ export const mcpOptions = (yargs: CommonYargsArgv) =>
"$0 mcp run .temp/mcp-calls.json",
"Run a larger bounded multi-step MCP workflow from a file"
)
+ .example(
+ "$0 mcp run .temp/projects.json --dry-run --concurrency 2",
+ "Run one resumable workflow across independently linked projects"
+ )
.example(
'$0 mcp single-op-call components.search \'{"brief":"radix select"}\'',
"Pass a JSON argument object to one MCP tool"
@@ -740,7 +738,7 @@ const mcpRunOptions = (yargs: CommonYargsArgv) =>
.positional("input", {
type: "string",
describe:
- 'Inline JSON or path to a JSON file containing { "calls": [{ "tool": "...", "input": {} }] }',
+ 'Inline JSON or path to a JSON workflow with "calls" and optional "projects"',
demandOption: true,
})
.option("dry-run", {
@@ -748,6 +746,20 @@ const mcpRunOptions = (yargs: CommonYargsArgv) =>
describe: "Run local-capable mutation tools without committing",
default: false,
})
+ .option("approve-mutations", {
+ type: "boolean",
+ describe: "Explicitly approve committed mutations in a projects batch",
+ default: false,
+ })
+ .option("concurrency", {
+ type: "number",
+ describe: "Maximum projects to run concurrently (projects batches only)",
+ })
+ .option("resume", {
+ type: "boolean",
+ describe: "Resume a projects batch and skip successful calls",
+ default: true,
+ })
.option("json", {
type: "boolean",
describe: "Accepted for compatibility. MCP run output is always JSON",
@@ -785,7 +797,7 @@ const parseMcpSingleOpCallInput = async ({
const parseMcpRunCalls = (value: unknown): McpRunCall[] => {
const calls = Array.isArray(value)
? value
- : isRecord(value) && Array.isArray(value.calls)
+ : isPlainRecord(value) && Array.isArray(value.calls)
? value.calls
: undefined;
if (calls === undefined) {
@@ -797,7 +809,7 @@ const parseMcpRunCalls = (value: unknown): McpRunCall[] => {
throw new Error("MCP run input must include at least one call.");
}
return calls.map((call, index): McpRunCall => {
- if (isRecord(call) === false) {
+ if (isPlainRecord(call) === false) {
throw new Error(`MCP run calls[${index}] must be an object.`);
}
if (typeof call.tool !== "string" || call.tool.length === 0) {
@@ -813,14 +825,17 @@ const parseMcpRunCalls = (value: unknown): McpRunCall[] => {
});
};
-const parseMcpRunInput = async (input: string | undefined) => {
+const readMcpRunInput = async (input: string | undefined) => {
if (input === undefined || input.length === 0) {
throw new Error("mcp run requires inline JSON or an input file.");
}
const trimmedInput = input.trim();
if (trimmedInput.startsWith("{") || trimmedInput.startsWith("[")) {
try {
- return parseMcpRunCalls(JSON.parse(trimmedInput));
+ return {
+ value: JSON.parse(trimmedInput) as unknown,
+ baseDirectory: cwd(),
+ };
} catch (error) {
if (error instanceof SyntaxError) {
throw createMcpInputError(
@@ -833,7 +848,10 @@ const parseMcpRunInput = async (input: string | undefined) => {
}
const inputPath = path.resolve(cwd(), input);
try {
- return parseMcpRunCalls(JSON.parse(await readFile(inputPath, "utf8")));
+ return {
+ value: JSON.parse(await readFile(inputPath, "utf8")) as unknown,
+ baseDirectory: path.dirname(inputPath),
+ };
} catch (error) {
if (error instanceof SyntaxError) {
throw createMcpInputError(
@@ -855,6 +873,9 @@ const parseMcpRunInput = async (input: string | undefined) => {
}
};
+const parseMcpRunInput = async (input: string | undefined) =>
+ parseMcpRunCalls((await readMcpRunInput(input)).value);
+
const applyMcpRunOptions = (
calls: McpRunCall[],
options: Pick<McpRunOptions, "dryRun">
@@ -900,7 +921,7 @@ const createMcpRunCheckpointStopPayload = ({
const getMcpRunError = (error: unknown) => {
const issues = getCliErrorIssues(error);
if (
- isRecord(error) &&
+ isPlainRecord(error) &&
typeof error.message === "string" &&
(error.code === undefined || typeof error.code === "string")
) {
@@ -920,7 +941,7 @@ const getMcpRunError = (error: unknown) => {
};
const validateSingleOpCallInput = (tool: string, input: unknown) => {
- if (tool !== "audit" || isRecord(input) === false) {
+ if (tool !== "audit" || isPlainRecord(input) === false) {
return;
}
const issues: SemanticValidationIssue[] = [];
@@ -1027,7 +1048,7 @@ const getMcpToolCallError = (result: {
if (isMcpToolCallFailure(result) === false) {
return;
}
- return isRecord(result.structuredContent.error)
+ return isPlainRecord(result.structuredContent.error)
? result.structuredContent.error
: { code: "MCP_TOOL_FAILED", message: "MCP tool call failed." };
};
@@ -1083,8 +1104,8 @@ export const __testing__ = {
updatePersistedMcpCheckpoint,
};
-const createCliMcpHost = async () => {
- const connection = await resolveApiConnection();
+const createCliMcpHost = async (projectRoot = cwd()) => {
+ const connection = await resolveApiConnection(undefined, projectRoot);
const apiConnection = {
...connection,
headers: apiCompatibilityHeaders,
@@ -1101,7 +1122,10 @@ const createCliMcpHost = async () => {
};
const apiContract = await getCliServerApiContract(apiConnection);
const operations = getSupportedPublicApiOperations(apiContract);
- const session = createCliProjectSession({ connection: apiConnection });
+ const session = createCliProjectSession({
+ connection: apiConnection,
+ projectRoot,
+ });
await prepareMcpProjectSession(session);
const preview = createPreviewController({ host: "127.0.0.1", port: 5173 });
let isPreviewStale = true;
@@ -1118,7 +1142,7 @@ const createCliMcpHost = async () => {
prepareSessionDataFile: async () => {
await writeCliProjectSessionDataFile(
getLoadedProjectSessionSnapshot(session),
- undefined,
+ path.join(projectRoot, LOCAL_DATA_FILE),
{ origin: connection.origin }
);
},
@@ -1184,7 +1208,20 @@ const createCliMcpHost = async () => {
markPreviewStale();
return { imported: true as const };
},
- startPreview: previewHandlers.startPreview,
+ async startPreview(input, progress) {
+ const resolvedInput =
+ input.port === 0
+ ? {
+ ...input,
+ port: await findAvailablePort(input.host ?? "127.0.0.1"),
+ }
+ : input;
+ const result = await previewHandlers.startPreview(
+ resolvedInput,
+ progress
+ );
+ return result;
+ },
async getPreviewStatus() {
return preview.status();
},
@@ -1204,7 +1241,7 @@ const createCliMcpHost = async () => {
return installTesseractForOcr();
},
async storeRenderedAuditArtifacts(manifest) {
- const directory = path.join(cwd(), renderedAuditArtifactDirectory);
+ const directory = path.join(projectRoot, renderedAuditArtifactDirectory);
await mkdir(directory, { recursive: true });
const artifactPath = path.join(
directory,
@@ -1237,6 +1274,58 @@ const createCliMcpHost = async () => {
};
};
+const createCliMcpCore = (host: CliMcpHost) =>
+ createProjectSessionMcpCore({
+ ...host,
+ reportToolProgress(message) {
+ stderr.write(`${formatMcpStatusLine(message)}\n`);
+ },
+ });
+
+type CliMcpCore = ReturnType<
+ typeof createProjectSessionMcpCore<PublicApiCommand>
+>;
+
+const assertMcpToolServerSupport = (
+ tool: string,
+ contract: CliServerApiContract
+) => {
+ const operation = publicApiOperationByCommand.get(tool as PublicApiCommand);
+ if (
+ operation !== undefined &&
+ publicApiOperationRequiresServerSupport(operation)
+ ) {
+ assertCliServerOperationSupported(operation.id, contract);
+ }
+};
+
+const executeMcpRunCall = async ({
+ core,
+ call,
+ projectRoot,
+}: {
+ core: CliMcpCore;
+ call: McpRunCall;
+ projectRoot?: string;
+}) => {
+ const result = await core.callTool({
+ name: call.tool,
+ input: call.input,
+ dryRun: call.dryRun,
+ });
+ const toolError = getMcpToolCallError(result);
+ if (toolError !== undefined) {
+ throw toolError;
+ }
+ const checkpoint = getResultCheckpoint(call.tool, result.structuredContent);
+ await updatePersistedMcpCheckpoint({
+ tool: call.tool,
+ structuredContent: result.structuredContent,
+ projectRoot,
+ });
+ return { result, checkpoint };
+};
+
export const mcpSingleOpCall = async (options: McpSingleOpCallOptions) => {
if (options.tool === undefined || options.tool === "") {
throw new Error("mcp single-op-call requires a tool name.");
@@ -1252,16 +1341,8 @@ export const mcpSingleOpCall = async (options: McpSingleOpCallOptions) => {
const input = await parseMcpSingleOpCallInput(options);
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);
+ assertMcpToolServerSupport(options.tool, apiContract);
+ const core = createCliMcpCore(host);
const persistedCheckpoint =
options.tool === "checkpoint.ack"
? await readPersistedMcpCheckpoint()
@@ -1287,7 +1368,7 @@ export const mcpSingleOpCall = async (options: McpSingleOpCallOptions) => {
if (
options.tool === "checkpoint.ack" &&
persistedCheckpoint?.nextCommand !== undefined &&
- isRecord(result.structuredContent.data)
+ isPlainRecord(result.structuredContent.data)
) {
result.structuredContent.data.nextCommand =
persistedCheckpoint.nextCommand;
@@ -1329,12 +1410,120 @@ export const mcpSingleOpCall = async (options: McpSingleOpCallOptions) => {
class McpRunCheckpointStop extends Error {}
+const runMcpProjectsBatch = async ({
+ source,
+ options,
+ startedAt,
+}: {
+ source: Awaited<ReturnType<typeof readMcpRunInput>>;
+ options: McpRunOptions;
+ startedAt: number;
+}) => {
+ const manifest = parseMcpProjectsManifest({
+ value: source.value,
+ baseDirectory: source.baseDirectory,
+ defaultProgressDirectory: cwd(),
+ parseCalls: (value) => applyMcpRunOptions(parseMcpRunCalls(value), options),
+ concurrency: options.concurrency,
+ });
+ stderr.write(
+ `${formatMcpStatusLine(
+ `batch started for ${manifest.projects.length} projects with concurrency ${manifest.concurrency}`
+ )}\n`
+ );
+ const reports = await runMcpProjectBatch({
+ manifest,
+ resume: options.resume !== false,
+ runProject: async ({ project, startCall, callStarted, callSucceeded }) => {
+ stderr.write(
+ `${formatMcpStatusLine(
+ `batch project ${project.id} started at call ${startCall + 1}/${project.calls.length}`
+ )}\n`
+ );
+ const { host, apiContract } = await createCliMcpHost(project.root);
+ const core = createCliMcpCore(host);
+ const tools = new Map(core.listTools().map((tool) => [tool.name, tool]));
+ for (const call of project.calls.slice(startCall)) {
+ assertMcpToolServerSupport(call.tool, apiContract);
+ const tool = tools.get(call.tool);
+ assertMcpBatchMutationApproved({
+ projectId: project.id,
+ call,
+ method: tool?.annotations.method,
+ approved: options.approveMutations === true,
+ });
+ }
+ if (startCall < project.calls.length) {
+ await assertPersistedMcpCheckpointAcknowledged(
+ project.calls[startCall]!.tool,
+ project.root
+ );
+ }
+ for (let index = startCall; index < project.calls.length; index++) {
+ const call = project.calls[index]!;
+ const tool = tools.get(call.tool);
+ await callStarted(
+ index,
+ call.dryRun || tool?.annotations.method !== "mutation"
+ );
+ const { checkpoint } = await executeMcpRunCall({
+ core,
+ call,
+ projectRoot: project.root,
+ });
+ await callSucceeded(index + 1);
+ if (checkpoint !== undefined && index + 1 < project.calls.length) {
+ throw createMcpInputError(checkpoint.message, "CHECKPOINT_REQUIRED");
+ }
+ }
+ },
+ });
+ const succeeded = reports.filter(
+ (report) => report.status === "succeeded"
+ ).length;
+ const skipped = reports.filter(
+ (report) => report.status === "skipped"
+ ).length;
+ const failed = reports.length - succeeded - skipped;
+ const payload = {
+ ok: failed === 0,
+ data: {
+ projects: {
+ total: reports.length,
+ succeeded,
+ failed,
+ skipped,
+ },
+ results: reports,
+ progressFile: manifest.progressFile,
+ },
+ meta: { elapsedMs: Date.now() - startedAt },
+ };
+ stderr.write(
+ `${formatMcpStatusLine(
+ `batch finished: ${succeeded} succeeded, ${failed} failed, ${skipped} skipped`
+ )}\n`
+ );
+ printJson(payload);
+ if (failed > 0) {
+ throw new HandledCliError();
+ }
+};
+
export const mcpRun = async (options: McpRunOptions) => {
const startedAt = Date.now();
let calls: McpRunCall[];
try {
- calls = await parseMcpRunInput(options.input);
+ const source = await readMcpRunInput(options.input);
+ if (isMcpProjectsManifest(source.value)) {
+ await runMcpProjectsBatch({ source, options, startedAt });
+ return;
+ }
+ calls = parseMcpRunCalls(source.value);
} catch (error) {
+ if (isHandledCliError(error)) {
+ throw error;
+ }
reportMcpRunPreflightFailure({
error,
startedAt,
@@ -1353,17 +1542,9 @@ export const mcpRun = async (options: McpRunOptions) => {
try {
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);
- }
+ assertMcpToolServerSupport(call.tool, apiContract);
}
- core = createProjectSessionMcpCore(host);
+ core = createCliMcpCore(host);
if (calls.length > 0) {
await assertPersistedMcpCheckpointAcknowledged(calls[0]!.tool);
}
@@ -1383,23 +1564,7 @@ export const mcpRun = async (options: McpRunOptions) => {
)}\n`
);
try {
- const result = await core.callTool({
- name: call.tool,
- input: call.input,
- dryRun: call.dryRun,
- });
- const toolError = getMcpToolCallError(result);
- if (toolError !== undefined) {
- throw toolError;
- }
- const checkpoint = getResultCheckpoint(
- call.tool,
- result.structuredContent
- );
- await updatePersistedMcpCheckpoint({
- tool: call.tool,
- structuredContent: result.structuredContent,
- });
+ const { result, checkpoint } = await executeMcpRunCall({ core, call });
const session = result.structuredContent.meta.session;
const committed =
session === undefined ? "" : `; committed=${session.committed}`;
@@ -1477,7 +1642,7 @@ export const mcpListTools = async (_options: McpListToolsOptions) => {
const startedAt = Date.now();
stderr.write(`${formatMcpStatusLine("list-tools started")}\n`);
const { host } = await createCliMcpHost();
- const core = createProjectSessionMcpCore(host);
+ const core = createCliMcpCore(host);
const result = await core.callTool({
name: "meta.index",
input: {},
@@ -1494,7 +1659,7 @@ export const mcpListTools = async (_options: McpListToolsOptions) => {
export const mcpListResources = async (_options: McpListResourcesOptions) => {
const startedAt = Date.now();
const { host } = await createCliMcpHost();
- const core = createProjectSessionMcpCore(host);
+ const core = createCliMcpCore(host);
printJson({
ok: true,
data: { resources: core.listResources() },
@@ -1509,7 +1674,7 @@ export const mcpReadResource = async (options: McpReadResourceOptions) => {
const startedAt = Date.now();
try {
const { host } = await createCliMcpHost();
- const core = createProjectSessionMcpCore(host);
+ const core = createCliMcpCore(host);
printJson({
ok: true,
data: await core.readResource({ uri: options.uri }),
diff --git a/packages/cli/src/commands/schema.ts b/packages/cli/src/commands/schema.ts
index bd28c40684..53b7f468a5 100644
--- a/packages/cli/src/commands/schema.ts
+++ b/packages/cli/src/commands/schema.ts
@@ -5,9 +5,11 @@ import {
import {
listProjectSessionMcpResources,
listProjectSessionMcpTools,
+} from "@webstudio-is/project-build/mcp";
+import {
paginateOutput,
projectOutput,
-} from "@webstudio-is/project-build/mcp";
+} from "@webstudio-is/project-build/runtime";
import { HandledCliError } from "../errors";
import { printJson } from "../json-output";
import { useCaseScenarios } from "./api-command-docs";
diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.ts
index 44d6abeef3..52d653aff1 100644
--- a/packages/cli/src/docs.generated.ts
+++ b/packages/cli/src/docs.generated.ts
@@ -2,13 +2,13 @@
// 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- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use 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- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\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\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\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 {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose: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: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\\"article\\"><ws.element ws:tag=\\"h2\\">{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\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- Pass `insert-collection` the complete array or object. Do not pass 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- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\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',
+ '# 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 compact machine-readable MCP tool overview. Add `--verbose` or use 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- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\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 {}\n- MCP tool: list-folders {}\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":{"method":"basic","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 {}\n- MCP tool: list-pages {}\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\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\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 {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose: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 {"scopes":["craft"],"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- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\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## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\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 {}\n- MCP tool: list-folders {}\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: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\\"article\\"><ws.element ws:tag=\\"h2\\">{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\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- Pass `insert-collection` the complete array or object. Do not pass 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- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\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: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\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 `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","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- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}\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: list-breakpoints {}\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":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Verify one familiar viewport inside every distinct Builder breakpoint range,\n then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\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:\nCall `meta.guide` with the provider-authenticated page goal, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\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:\nCall `meta.guide` with the design-input goal, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\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 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 compact MCP tool overview. Add `--verbose` 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- Draft a page with `update-page` and `{"pageId":"page-id","values":{"isDraft":true}}`. It remains editable and previewable but is omitted from every publish target, including staging, and from sitemap output.\n- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.\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, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. 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. 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',
+ '# 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\nEvery supported client follows the same generated quickstart: link the project,\nsync it, run `webstudio connect <client>`, reload or restart the client, then ask\nthe agent to use Webstudio MCP to list the project pages. The supported client\nnames are `claude`, `codex`, `cursor`, and `vscode`.\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### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\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":
diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.md
index 78a4070948..6c567fbcdd 100644
--- a/packages/cli/src/docs/api-use-cases.md
+++ b/packages/cli/src/docs/api-use-cases.md
@@ -163,7 +163,8 @@ Notes:
Commands:
-- MCP tool: list-pages {"includeFolders":true}
+- MCP tool: list-pages {}
+- MCP tool: list-folders {}
## Read page by id
@@ -194,7 +195,7 @@ Notes:
Commands:
- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":"200"}}}
-- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}
+- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}
Notes:
@@ -346,7 +347,8 @@ Commands:
Commands:
-- MCP tool: list-folders {"includePages":true}
+- MCP tool: list-folders {}
+- MCP tool: list-pages {}
## Create folder
@@ -896,11 +898,13 @@ Commands:
- MCP tool: audit {}
- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}
- MCP tool: audit {"scopes":["accessibility"],"verbose":true}
+- MCP tool: audit {"scopes":["craft"],"verbose":true}
- MCP tool: audit {"rendered":true,"verbose":true}
Notes:
- 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.
+- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.
- 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.
- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.
- 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.
@@ -932,6 +936,21 @@ Notes:
`.woff` fonts without applying a universal transfer-size threshold.
- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.
+## Verify dynamic bindings
+
+Commands:
+
+- webstudio verify-bindings --json
+- MCP tool: verify-bindings {"pagePath":"/pricing"}
+- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}
+
+Notes:
+
+- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.
+- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.
+- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.
+- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.
+
## Refactor targeted content
Commands:
@@ -955,7 +974,8 @@ Notes:
Commands:
-- MCP tool: list-pages {"includeFolders":true}
+- MCP tool: list-pages {}
+- MCP tool: list-folders {}
- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}
- MCP tool: update-props {"updates":"props.json contents"}
- MCP tool: list-breakpoints {}
@@ -1011,6 +1031,7 @@ Notes:
Commands:
+- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}
- MCP tool: update-props {"updates":"props.json contents"}
- MCP tool: bind-props {"bindings":"bindings.json contents"}
- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}
@@ -1019,15 +1040,18 @@ Commands:
Notes:
-- Use existing scripts/resources for behavior, then move presentational structure into editable Webstudio instances where possible.
-- There is no dedicated semantic command yet for converting script-generated UI into editable Webstudio structure.
+- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.
+- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.
+- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.
+- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.
## Build authenticated pages
Commands:
+- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}
- MCP tool: create-page {"name":"Account","path":"/account"}
-- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}
+- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}
- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}
- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}
- MCP tool: update-props {"updates":"props.json contents"}
@@ -1035,36 +1059,56 @@ Commands:
Notes:
-- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still requires manual resources, props, embeds, or patches.
+- Inspect and reuse the project's existing auth convention before authoring. Do
+ not add a second provider or session model implicitly.
+- Model signed-out, loading, signed-in, and failed-auth states explicitly.
+- Never store credentials, service-role keys, refresh tokens, private session
+ values, or authenticated response bodies in project data, command output,
+ screenshots, agent instructions, or error reports. Privileged provider calls
+ and authorization enforcement belong server-side.
+- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still
+ uses the existing resource, variable, prop, binding, and embed tools; there is
+ no provider-specific installer.
## Generate from design input
Commands:
+- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}
- MCP tool: create-page {"name":"Landing","path":"/landing"}
- MCP tool: create-design-token {"tokens":"tokens.json contents"}
- MCP tool: define-css-variable {"vars":"vars.json contents"}
+- MCP tool: list-breakpoints {}
- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\"section\"><ws.element ws:tag=\"p\">Section copy</ws.element></ws.element>"}
-- MCP tool: update-styles {"updates":"styles.json contents"}
+- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}
- MCP tool: preview.start {"host":"127.0.0.1","port":5173}
-- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}
-- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}
+- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}
+- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}
+- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}
Notes:
-- Use this after external design interpretation. There is no dedicated import command for Figma, screenshots, Inception output, or design.md yet.
+- Use this after the agent can inspect the supplied design. There is no direct
+ Figma, screenshot, Inception, or `design.md` import command.
+- Inspect and reuse existing variables, tokens, styles, components, assets, and
+ page patterns before authoring. Build semantic editable structure rather than
+ flattening the design into an image or absolute-positioned approximation.
+- Verify one familiar viewport inside every distinct Builder breakpoint range,
+ then run rendered audit and inspect the screenshots before completion.
## Cross-project maintenance
Commands:
-- webstudio init --link <api-share-link> --json
-- webstudio permissions --json
-- webstudio mcp
+- webstudio mcp run .temp/projects.json
+- webstudio mcp run .temp/projects.json --dry-run
+- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2
Notes:
-- Public API and CLI intentionally operate on one configured project at a time. Use an external script to loop over projects.
+- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.
+- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.
+- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.
# Known CLI Gaps
@@ -1074,31 +1118,24 @@ Missing:
CLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.
Current fallback:
-Create the page, resources, variables, props, and embeds manually with existing MCP semantic tools.
+Call `meta.guide` with the provider-authenticated page goal, then create the
+page, resources, variables, props, bindings, and embeds with existing semantic
+tools.
Suggested commands:
- setup-auth-page
-## Dynamic script/runtime integration helpers
-
-Missing:
-CLI can manipulate props/resources/embeds, but has no semantic workflow for converting script-generated UI into editable Webstudio structures.
-
-Current fallback:
-Use MCP props, resources, and raw patch where necessary.
-
-Suggested commands:
-
-- integrate-runtime-ui
-
## Generate from design input
Missing:
No command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.
Current fallback:
-Use external generation, then apply semantic CLI commands or apply-patch.
+Call `meta.guide` with the design-input goal, let the agent inspect the supplied
+design, then use semantic page, token, asset, fragment, style, preview,
+screenshot, and audit tools. Use `apply-patch` only when no semantic operation
+fits.
Suggested commands:
diff --git a/packages/cli/src/docs/manual-mcp.md b/packages/cli/src/docs/manual-mcp.md
index a966fc82c7..2fa75d4241 100644
--- a/packages/cli/src/docs/manual-mcp.md
+++ b/packages/cli/src/docs/manual-mcp.md
@@ -13,6 +13,11 @@
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"}'`.
+Every supported client follows the same generated quickstart: link the project,
+sync it, run `webstudio connect <client>`, reload or restart the client, then ask
+the agent to use Webstudio MCP to list the project pages. The supported client
+names are `claude`, `codex`, `cursor`, and `vscode`.
+
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.
When 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.
@@ -158,6 +163,35 @@ Rules:
- 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>"}`.
- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.
+### Cross-project batches
+
+Add `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:
+
+```json
+{
+ "concurrency": 2,
+ "calls": [
+ { "tool": "status" },
+ { "tool": "audit", "input": {} },
+ {
+ "tool": "update-project-settings",
+ "input": { "meta": { "siteName": "Reviewed" } },
+ "dryRun": true
+ }
+ ],
+ "projects": [
+ { "id": "site-a", "root": "../site-a" },
+ { "id": "site-b", "root": "../site-b" }
+ ]
+}
+```
+
+Project roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.
+
+Concurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.
+
+Committed mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.
+
## Discovery
Use MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:
diff --git a/packages/cli/src/generated-build-metrics.test.ts b/packages/cli/src/generated-build-metrics.test.ts
new file mode 100644
index 0000000000..e7da113d64
--- /dev/null
+++ b/packages/cli/src/generated-build-metrics.test.ts
@@ -0,0 +1,69 @@
+import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, expect, test } from "vitest";
+import { inspectGeneratedBuildMetrics } from "./generated-build-metrics";
+
+const directories: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ directories.splice(0).map((path) => rm(path, { recursive: true }))
+ );
+});
+
+test("returns bounded privacy-safe generated build metrics", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "webstudio-build-metrics-"));
+ directories.push(directory);
+ await mkdir(join(directory, "build/client/assets"), { recursive: true });
+ await mkdir(join(directory, "build/server"), { recursive: true });
+ await writeFile(
+ join(directory, "build/client/assets/index.js"),
+ "export const value = 1;".repeat(100)
+ );
+ await writeFile(
+ join(directory, "build/client/assets/hero.webp"),
+ Buffer.alloc(512)
+ );
+ await writeFile(
+ join(directory, "build/server/index.js"),
+ "server".repeat(50)
+ );
+
+ const metrics = await inspectGeneratedBuildMetrics(directory);
+
+ expect(metrics).toMatchObject({
+ version: 1,
+ fileCount: 3,
+ client: { fileCount: 2 },
+ server: { fileCount: 1 },
+ largestFiles: expect.arrayContaining([
+ expect.objectContaining({
+ path: "client/assets/index.js",
+ kind: "script",
+ }),
+ expect.objectContaining({
+ path: "client/assets/hero.webp",
+ kind: "image",
+ }),
+ ]),
+ });
+ expect(metrics.gzipBytes).toBeLessThan(metrics.bytes);
+ expect(JSON.stringify(metrics)).not.toContain(directory);
+ expect(metrics.largestFiles).toHaveLength(3);
+});
+
+test("returns empty metrics when no generated build exists", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "webstudio-build-metrics-"));
+ directories.push(directory);
+
+ await expect(inspectGeneratedBuildMetrics(directory)).resolves.toEqual({
+ version: 1,
+ fileCount: 0,
+ bytes: 0,
+ gzipBytes: 0,
+ client: { fileCount: 0, bytes: 0, gzipBytes: 0 },
+ server: { fileCount: 0, bytes: 0, gzipBytes: 0 },
+ largestFiles: [],
+ });
+});
diff --git a/packages/cli/src/generated-build-metrics.ts b/packages/cli/src/generated-build-metrics.ts
new file mode 100644
index 0000000000..4756d925d4
--- /dev/null
+++ b/packages/cli/src/generated-build-metrics.ts
@@ -0,0 +1,103 @@
+import { gzip } from "node:zlib";
+import { promisify } from "node:util";
+import { readdir, readFile, stat } from "node:fs/promises";
+import { extname, join, relative, sep } from "node:path";
+
+const gzipAsync = promisify(gzip);
+const compressibleExtensions = new Set([
+ ".css",
+ ".html",
+ ".js",
+ ".json",
+ ".map",
+ ".svg",
+ ".txt",
+ ".xml",
+]);
+
+type BuildFile = {
+ path: string;
+ bytes: number;
+ gzipBytes: number;
+ kind: "script" | "style" | "image" | "font" | "other";
+};
+
+const getFileKind = (path: string): BuildFile["kind"] => {
+ const extension = extname(path).toLowerCase();
+ if ([".js", ".mjs", ".cjs"].includes(extension)) {
+ return "script";
+ }
+ if (extension === ".css") {
+ return "style";
+ }
+ if (
+ [".avif", ".gif", ".jpeg", ".jpg", ".png", ".svg", ".webp"].includes(
+ extension
+ )
+ ) {
+ return "image";
+ }
+ if ([".eot", ".otf", ".ttf", ".woff", ".woff2"].includes(extension)) {
+ return "font";
+ }
+ return "other";
+};
+
+const listFiles = async (root: string, directory = root): Promise<string[]> => {
+ const entries = await readdir(directory, { withFileTypes: true });
+ const files = await Promise.all(
+ entries.map(async (entry) => {
+ const path = join(directory, entry.name);
+ if (entry.isDirectory()) {
+ return listFiles(root, path);
+ }
+ return entry.isFile() ? [path] : [];
+ })
+ );
+ return files.flat();
+};
+
+const summarizeFiles = (files: readonly BuildFile[]) => ({
+ fileCount: files.length,
+ bytes: files.reduce((total, file) => total + file.bytes, 0),
+ gzipBytes: files.reduce((total, file) => total + file.gzipBytes, 0),
+});
+
+export const inspectGeneratedBuildMetrics = async (
+ projectDirectory: string
+) => {
+ const buildDirectory = join(projectDirectory, "build");
+ const paths = await listFiles(buildDirectory).catch(
+ (error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") {
+ return [];
+ }
+ throw error;
+ }
+ );
+ const files = await Promise.all(
+ paths.map(async (path): Promise<BuildFile> => {
+ const fileStat = await stat(path);
+ const extension = extname(path).toLowerCase();
+ const gzipBytes = compressibleExtensions.has(extension)
+ ? (await gzipAsync(await readFile(path))).byteLength
+ : fileStat.size;
+ return {
+ path: relative(buildDirectory, path).split(sep).join("/"),
+ bytes: fileStat.size,
+ gzipBytes,
+ kind: getFileKind(path),
+ };
+ })
+ );
+ files.sort((left, right) => right.gzipBytes - left.gzipBytes);
+ const client = files.filter((file) => file.path.startsWith("client/"));
+ const server = files.filter((file) => file.path.startsWith("server/"));
+ return {
+ version: 1 as const,
+ ...summarizeFiles(files),
+ client: summarizeFiles(client),
+ server: summarizeFiles(server),
+ largestFiles: files.slice(0, 20),
+ };
+};
diff --git a/packages/cli/src/preview-server.test.ts b/packages/cli/src/preview-server.test.ts
index 7d263f222a..5c87e23683 100644
--- a/packages/cli/src/preview-server.test.ts
+++ b/packages/cli/src/preview-server.test.ts
@@ -4,6 +4,7 @@ import { join } from "node:path";
import { expect, test, vi } from "vitest";
import {
createPreviewController,
+ findAvailablePort,
getPreviewBuildArgs,
getPreviewCommand,
getPreviewStartArgs,
@@ -15,6 +16,13 @@ import {
type PreviewServerDependencies,
} from "./preview-server";
+test("allocates an available local preview port", async () => {
+ const port = await findAvailablePort();
+
+ expect(port).toBeGreaterThan(0);
+ expect(port).toBeLessThanOrEqual(65_535);
+});
+
const createDependencies = (
overrides: Partial<PreviewServerDependencies> = {}
): PreviewServerDependencies => ({
diff --git a/packages/cli/src/preview-server.ts b/packages/cli/src/preview-server.ts
index 90a0c4dcdb..bccd4b407f 100644
--- a/packages/cli/src/preview-server.ts
+++ b/packages/cli/src/preview-server.ts
@@ -4,6 +4,7 @@ import {
type StdioOptions,
} from "node:child_process";
import { cp, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
+import { createServer as createTcpServer } from "node:net";
import { delimiter, dirname, join, parse } from "node:path";
export type PreviewServerOptions = {
@@ -42,6 +43,24 @@ export const defaultPreviewServerDependencies: PreviewServerDependencies = {
platform: process.platform,
};
+export const findAvailablePort = (host = "127.0.0.1") =>
+ new Promise<number>((resolve, reject) => {
+ const server = createTcpServer();
+ server.unref();
+ server.once("error", reject);
+ server.listen({ host, port: 0, exclusive: true }, () => {
+ const address = server.address();
+ if (address === null || typeof address === "string") {
+ server.close();
+ reject(new Error("Could not allocate a local preview port."));
+ return;
+ }
+ server.close((error) =>
+ error === undefined ? resolve(address.port) : reject(error)
+ );
+ });
+ });
+
const processEnv = () => process.env;
const pathKey = () => (process.platform === "win32" ? "Path" : "PATH");
diff --git a/packages/cli/src/project-session-api.test.ts b/packages/cli/src/project-session-api.test.ts
index cfa3303443..33163b5f3b 100644
--- a/packages/cli/src/project-session-api.test.ts
+++ b/packages/cli/src/project-session-api.test.ts
@@ -35,7 +35,7 @@ describe("project session api adapter", () => {
const result = await executeProjectSessionApiOperation({
command: "list-pages",
- input: { includeFolders: true },
+ input: { limit: 20 },
connection: {
projectId: "project-1",
origin: "https://example.com",
@@ -46,7 +46,7 @@ describe("project session api adapter", () => {
expect(session.read).toHaveBeenCalledWith(
"pages.list",
- { projectId: "project-1", includeFolders: true },
+ { projectId: "project-1", limit: 20 },
{ permit: "view" }
);
expect(result.result).toEqual(["page"]);
diff --git a/packages/cli/src/project-session-api.ts b/packages/cli/src/project-session-api.ts
index 232a269865..40a0d0c2a9 100644
--- a/packages/cli/src/project-session-api.ts
+++ b/packages/cli/src/project-session-api.ts
@@ -15,13 +15,7 @@ import {
createCliProjectSession,
getCliServerApiContract,
} from "./project-session";
-
-export type ProjectSessionApiConnection = {
- projectId: string;
- origin: string;
- authToken: string;
- headers?: Record<string, string | undefined>;
-};
+import type { ApiConnection } from "./api-connection";
export type ProjectSessionApiCommand = PublicApiCommand;
@@ -86,7 +80,7 @@ export const executeProjectSessionApiOperation = async ({
}: {
command: ProjectSessionApiCommand;
input: unknown;
- connection: ProjectSessionApiConnection;
+ connection: ApiConnection;
createProjectSession?: CreateProjectSession;
getServerApiContract?: typeof getCliServerApiContract;
dryRun?: boolean;
diff --git a/packages/cli/src/project-session.ts b/packages/cli/src/project-session.ts
index fe1aeff577..0fab0d1b1f 100644
--- a/packages/cli/src/project-session.ts
+++ b/packages/cli/src/project-session.ts
@@ -8,6 +8,7 @@ import {
import * as httpClient from "@webstudio-is/http-client";
import {
bundleVersion,
+ getPublicBuildIncludes,
publicApiContractVersion,
publicApiOperationRequiresServerSupport,
publicApiOperations,
@@ -29,6 +30,7 @@ import type { BuilderNamespace } from "@webstudio-is/project-build/contracts";
import {
createBuilderStateFromBuildData,
createBuilderStateFromSerializedSnapshot,
+ createSerializedBuilderBuildDataFromState,
createSerializedBuilderStateSnapshotFromState,
type BuilderBuildDataSnapshot,
type SerializedBuilderStateSnapshot,
@@ -36,15 +38,10 @@ import {
import { removeLegacyProjectSettingsFromPages } from "@webstudio-is/project-build";
import type { BuilderStateFreshness } from "@webstudio-is/project-build/state";
import { LOCAL_CONFIG_FILE, LOCAL_DATA_FILE } from "./config";
+import type { ApiConnection } from "./api-connection";
import { getStableErrorCode } from "./error-codes";
import { writeFileAtomic } from "./fs-utils";
-
-type ApiConnection = {
- projectId: string;
- origin: string;
- authToken: string;
- headers?: Record<string, string | undefined>;
-};
+import { isPlainRecord } from "./type-utils";
export type CliServerApiContract = {
clientVersion: string;
@@ -54,23 +51,20 @@ export type CliServerApiContract = {
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)
+ const apiContract = isPlainRecord(permissions)
? permissions.apiContract
: undefined;
const serverVersion =
- isRecord(apiContract) && typeof apiContract.version === "string"
+ isPlainRecord(apiContract) && typeof apiContract.version === "string"
? apiContract.version
: undefined;
const operationIds =
- isRecord(apiContract) && Array.isArray(apiContract.operationIds)
+ isPlainRecord(apiContract) && Array.isArray(apiContract.operationIds)
? apiContract.operationIds.filter(
(operationId): operationId is string =>
typeof operationId === "string"
@@ -148,7 +142,8 @@ type PersistedCliProjectSessionSnapshot = Omit<
state: SerializedBuilderStateSnapshot;
};
-const sessionFile = join(dirname(LOCAL_CONFIG_FILE), "project-session.json");
+export const getCliProjectSessionFile = (projectRoot = cwd()) =>
+ join(projectRoot, dirname(LOCAL_CONFIG_FILE), "project-session.json");
const compatibilityVersion = "cli-project-session-v1";
const createCliProjectSessionCompatibility = (
@@ -158,23 +153,6 @@ const createCliProjectSessionCompatibility = (
apiCompatibilityVersion: connection.headers?.["x-webstudio-client-version"],
});
-const toPublicApiInclude = (namespaces: readonly BuilderNamespace[]) => [
- ...new Set(
- namespaces.flatMap((namespace) => {
- if (namespace === "dataSources") {
- return ["variables"];
- }
- if (namespace === "pages") {
- return ["pages", "folders"];
- }
- if (namespace === "projectSettings") {
- return ["projectSettings"];
- }
- return [namespace];
- })
- ),
-];
-
const isUnsupportedProjectSettingsIncludeError = (error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
return (
@@ -184,7 +162,7 @@ const isUnsupportedProjectSettingsIncludeError = (error: unknown) => {
};
const getLegacyPublicApiInclude = (namespaces: readonly BuilderNamespace[]) =>
- toPublicApiInclude([
+ getPublicBuildIncludes([
...namespaces.filter((namespace) => namespace !== "projectSettings"),
"pages",
]);
@@ -282,7 +260,7 @@ const serializePersistedSnapshot = (
});
export const createCliProjectSessionStorage = (
- path = join(cwd(), sessionFile)
+ path = getCliProjectSessionFile()
): ProjectSessionStorage => ({
async load() {
try {
@@ -347,7 +325,7 @@ export const createCliProjectSessionTransport = ({
) as Promise<PublicBuildSnapshot>;
let snapshot: PublicBuildSnapshot;
try {
- snapshot = await fetchSnapshot(toPublicApiInclude(namespaces));
+ snapshot = await fetchSnapshot(getPublicBuildIncludes(namespaces));
} catch (error) {
if (
namespaces.includes("projectSettings") === false ||
@@ -402,12 +380,14 @@ export const createCliProjectSessionTransport = ({
export const createCliProjectSession = ({
connection,
- storage = createCliProjectSessionStorage(),
+ storage,
+ projectRoot,
executeServerOperation,
getPermissions,
}: {
connection: ApiConnection;
storage?: ProjectSessionStorage;
+ projectRoot?: string;
executeServerOperation?: ProjectSessionTransport["executeServerOperation"];
getPermissions?: ProjectSessionTransport["getPermissions"];
}) =>
@@ -418,7 +398,9 @@ export const createCliProjectSession = ({
executeServerOperation,
getPermissions,
}),
- storage,
+ storage:
+ storage ??
+ createCliProjectSessionStorage(getCliProjectSessionFile(projectRoot)),
compatibilityVersion,
});
@@ -444,6 +426,8 @@ export const createLocalProjectBundleFromSessionSnapshot = (
structuredClone(pages)
);
const serializedPages = serializePages(persistedPages);
+ const { pages: _pages, ...serializedBuildState } =
+ createSerializedBuilderBuildDataFromState(snapshot.state);
const homePage = getHomePage(persistedPages);
return {
bundleVersion,
@@ -462,19 +446,8 @@ export const createLocalProjectBundleFromSessionSnapshot = (
version: snapshot.version,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
+ ...serializedBuildState,
pages: serializedPages,
- breakpoints: Array.from(snapshot.state.breakpoints?.entries() ?? []),
- styles: Array.from(snapshot.state.styles?.entries() ?? []),
- styleSources: Array.from(snapshot.state.styleSources?.entries() ?? []),
- styleSourceSelections: Array.from(
- snapshot.state.styleSourceSelections?.entries() ?? []
- ),
- props: Array.from(snapshot.state.props?.entries() ?? []),
- instances: Array.from(snapshot.state.instances?.entries() ?? []),
- dataSources: Array.from(snapshot.state.dataSources?.entries() ?? []),
- resources: Array.from(snapshot.state.resources?.entries() ?? []),
- marketplaceProduct: snapshot.state.marketplaceProduct,
- projectSettings,
},
};
};
diff --git a/packages/cli/src/screenshot-browser-cdp.test.ts b/packages/cli/src/screenshot-browser-cdp.test.ts
index 8472e360cf..3a162d88b5 100644
--- a/packages/cli/src/screenshot-browser-cdp.test.ts
+++ b/packages/cli/src/screenshot-browser-cdp.test.ts
@@ -135,6 +135,82 @@ class FakeWebSocket {
);
return;
}
+ if (
+ message.method === "Runtime.evaluate" &&
+ typeof message.params?.expression === "string" &&
+ message.params.expression.includes("parseOpaqueRgb")
+ ) {
+ setTimeout(
+ () =>
+ respond({
+ result: {
+ value: [
+ {
+ instanceId: "hero-title",
+ tagName: "h1",
+ foreground: "rgb(120, 120, 120)",
+ background: "rgb(255, 255, 255)",
+ ratio: 4.42,
+ requiredRatio: 4.5,
+ fontSize: 16,
+ fontWeight: 400,
+ },
+ ],
+ },
+ }),
+ 0
+ );
+ return;
+ }
+ if (
+ message.method === "Runtime.evaluate" &&
+ typeof message.params?.expression === "string" &&
+ message.params.expression.includes(
+ 'document.querySelectorAll("[data-ws-id]")'
+ )
+ ) {
+ setTimeout(
+ () =>
+ respond({
+ result: {
+ value: {
+ total: 2,
+ sampled: 2,
+ truncated: false,
+ elements: [
+ {
+ instanceId: "hero",
+ tagName: "section",
+ x: 0,
+ y: 0,
+ width: 800,
+ height: 600,
+ visible: true,
+ clippedX: false,
+ clippedY: true,
+ overlapsWith: ["overlay"],
+ },
+ {
+ instanceId: "overlay",
+ tagName: "div",
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 100,
+ visible: false,
+ hiddenReason: "display",
+ clippedX: false,
+ clippedY: false,
+ overlapsWith: [],
+ },
+ ],
+ },
+ },
+ }),
+ 0
+ );
+ return;
+ }
if (
message.method === "Runtime.evaluate" &&
typeof message.params?.expression === "string" &&
@@ -760,6 +836,7 @@ test("captures full page and returns DevTools layout metrics", async () => {
fullPage: true,
includeImageMetrics: true,
includeResourceMetrics: true,
+ includeContrastMetrics: true,
browserPath: "/usr/bin/chromium",
uid: 1000,
waitUntil: "networkidle",
@@ -787,6 +864,38 @@ test("captures full page and returns DevTools layout metrics", async () => {
contentWidth: 813,
contentHeight: 2346,
horizontalOverflow: false,
+ elementGeometry: {
+ total: 2,
+ sampled: 2,
+ truncated: false,
+ elements: [
+ {
+ instanceId: "hero",
+ tagName: "section",
+ x: 0,
+ y: 0,
+ width: 800,
+ height: 600,
+ visible: true,
+ clippedX: false,
+ clippedY: true,
+ overlapsWith: ["overlay"],
+ },
+ {
+ instanceId: "overlay",
+ tagName: "div",
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 100,
+ visible: false,
+ hiddenReason: "display",
+ clippedX: false,
+ clippedY: false,
+ overlapsWith: [],
+ },
+ ],
+ },
images: [
{
instanceId: "hero-image",
@@ -821,6 +930,18 @@ test("captures full page and returns DevTools layout metrics", async () => {
duration: 40,
},
],
+ contrasts: [
+ {
+ instanceId: "hero-title",
+ tagName: "h1",
+ foreground: "rgb(120, 120, 120)",
+ background: "rgb(255, 255, 255)",
+ ratio: 4.42,
+ requiredRatio: 4.5,
+ fontSize: 16,
+ fontWeight: 400,
+ },
+ ],
timings: {
wallMs: expect.any(Number),
targetSetupMs: expect.any(Number),
@@ -1018,6 +1139,35 @@ test("times out when browser page target creation does not respond", async () =>
});
});
+test("stops polling when the browser DevTools port is not created", async () => {
+ const browserProcess = new FakeBrowserProcess();
+ const dependencies = createDependencies({ browserProcess });
+ vi.mocked(dependencies.readFile).mockRejectedValue(
+ Object.assign(new Error("not ready"), { code: "ENOENT" })
+ );
+
+ await expect(
+ captureBrowserScreenshot(
+ {
+ url: "https://example.com",
+ output: "/tmp/current.png",
+ width: 800,
+ height: 600,
+ browserPath: "/usr/bin/chromium",
+ waitUntil: "load",
+ waitForTimeout: 0,
+ timeout: 10,
+ },
+ dependencies
+ )
+ ).rejects.toThrow("Browser DevTools endpoint was not created within 10ms.");
+
+ const callsAfterTimeout = vi.mocked(dependencies.readFile).mock.calls.length;
+ await new Promise((resolve) => setTimeout(resolve, 75));
+ expect(dependencies.readFile).toHaveBeenCalledTimes(callsAfterTimeout);
+ expect(browserProcess.kill).toHaveBeenCalled();
+});
+
test("reports browser navigation errors directly", async () => {
const browserProcess = new FakeBrowserProcess();
const socket = new NavigationErrorWebSocket();
diff --git a/packages/cli/src/screenshot-browser-cdp.ts b/packages/cli/src/screenshot-browser-cdp.ts
index 163aa407b6..d79b4d76aa 100644
--- a/packages/cli/src/screenshot-browser-cdp.ts
+++ b/packages/cli/src/screenshot-browser-cdp.ts
@@ -15,6 +15,7 @@ export type BrowserScreenshotOptions = {
fullPage?: boolean;
includeImageMetrics?: boolean;
includeResourceMetrics?: boolean;
+ includeContrastMetrics?: boolean;
url: string;
uid?: number;
waitUntil: ScreenshotWaitUntil;
@@ -227,29 +228,29 @@ const waitForDevToolsPort = async (
userDataDir: string,
dependencies: BrowserScreenshotDependencies,
timeout: number
-) =>
- await withDeadline(
- (async () => {
- const portFile = join(userDataDir, "DevToolsActivePort");
- while (true) {
- try {
- const [port, browserPath] = (
- await dependencies.readFile(portFile, "utf8")
- )
- .trim()
- .split(/\r?\n/);
- if (port !== undefined && browserPath !== undefined) {
- return { port, browserPath };
- }
- } catch {
- // Keep polling until Chromium creates DevToolsActivePort.
- }
- await delay(50);
+) => {
+ const portFile = join(userDataDir, "DevToolsActivePort");
+ const deadline = Date.now() + timeout;
+ while (Date.now() < deadline) {
+ try {
+ const [port, browserPath] = (
+ await dependencies.readFile(portFile, "utf8")
+ )
+ .trim()
+ .split(/\r?\n/);
+ if (port !== undefined && browserPath !== undefined) {
+ return { port, browserPath };
}
- })(),
+ } catch {
+ // Chromium creates DevToolsActivePort asynchronously.
+ }
+ await delay(Math.min(50, Math.max(0, deadline - Date.now())));
+ }
+ throw createTimeoutError(
"Browser DevTools endpoint was not created",
timeout
);
+};
const getPageWebSocketUrl = async ({
port,
@@ -343,25 +344,22 @@ const waitForSelector = async (
selector: string,
timeout: number
) => {
- await withDeadline(
- (async () => {
- while (true) {
- const result = await cdp.send<{ result?: { value?: boolean } }>(
- "Runtime.evaluate",
- {
- expression: `document.querySelector(${JSON.stringify(selector)}) !== null`,
- returnByValue: true,
- }
- );
- if (result.result?.value === true) {
- return;
- }
- await delay(100);
- }
- })(),
- `Selector ${selector} was not found`,
- timeout
- );
+ const deadline = Date.now() + timeout;
+ while (Date.now() < deadline) {
+ const result = await withDeadline(
+ cdp.send<{ result?: { value?: boolean } }>("Runtime.evaluate", {
+ expression: `document.querySelector(${JSON.stringify(selector)}) !== null`,
+ returnByValue: true,
+ }),
+ `Selector ${selector} was not found`,
+ Math.max(1, deadline - Date.now())
+ );
+ if (result.result?.value === true) {
+ return;
+ }
+ await delay(Math.min(100, Math.max(0, deadline - Date.now())));
+ }
+ throw createTimeoutError(`Selector ${selector} was not found`, timeout);
};
type BrowserReadiness = {
@@ -498,11 +496,34 @@ export type BrowserScreenshotLayout = {
contentWidth: number;
contentHeight: number;
horizontalOverflow: boolean;
+ elementGeometry?: BrowserScreenshotElementGeometry;
images?: BrowserScreenshotImage[];
resources?: BrowserScreenshotResource[];
+ contrasts?: BrowserScreenshotContrast[];
timings?: BrowserScreenshotTimings;
};
+export type BrowserScreenshotElement = {
+ instanceId: string;
+ tagName: string;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ visible: boolean;
+ hiddenReason?: "display" | "visibility" | "opacity" | "hidden";
+ clippedX: boolean;
+ clippedY: boolean;
+ overlapsWith: string[];
+};
+
+export type BrowserScreenshotElementGeometry = {
+ total: number;
+ sampled: number;
+ truncated: boolean;
+ elements: BrowserScreenshotElement[];
+};
+
export type BrowserScreenshotNavigation = {
requestedUrl: string;
finalUrl: string;
@@ -539,6 +560,151 @@ export type BrowserScreenshotResource = {
renderBlockingStatus?: string;
};
+export type BrowserScreenshotContrast = {
+ instanceId: string;
+ tagName: string;
+ foreground: string;
+ background: string;
+ ratio: number;
+ requiredRatio: 3 | 4.5;
+ fontSize: number;
+ fontWeight: number;
+};
+
+const maxBrowserScreenshotElements = 250;
+const maxBrowserScreenshotOverlapsPerElement = 5;
+
+const getBrowserScreenshotElementGeometry = async (
+ send: <Result = unknown>(
+ method: string,
+ params?: Record<string, unknown>
+ ) => Promise<Result>
+): Promise<BrowserScreenshotElementGeometry> => {
+ const response = await send<{
+ result?: { value?: unknown };
+ }>("Runtime.evaluate", {
+ expression: `(() => {
+ const limit = ${maxBrowserScreenshotElements};
+ const overlapLimit = ${maxBrowserScreenshotOverlapsPerElement};
+ const candidates = Array.from(document.querySelectorAll("[data-ws-id]"));
+ const elements = candidates.slice(0, limit).map((element) => {
+ const style = getComputedStyle(element);
+ const rect = element.getBoundingClientRect();
+ let hiddenReason;
+ if (element.hidden) hiddenReason = "hidden";
+ else if (style.display === "none") hiddenReason = "display";
+ else if (style.visibility === "hidden" || style.visibility === "collapse") hiddenReason = "visibility";
+ else if (Number(style.opacity) === 0) hiddenReason = "opacity";
+ const visible = hiddenReason === undefined && rect.width > 0 && rect.height > 0;
+ const clipsX = style.overflowX === "hidden" || style.overflowX === "clip";
+ const clipsY = style.overflowY === "hidden" || style.overflowY === "clip";
+ return {
+ element,
+ instanceId: element.getAttribute("data-ws-id"),
+ tagName: element.tagName.toLowerCase(),
+ x: rect.left + window.scrollX,
+ y: rect.top + window.scrollY,
+ width: rect.width,
+ height: rect.height,
+ visible,
+ hiddenReason,
+ clippedX: visible && clipsX && element.scrollWidth > element.clientWidth + 1,
+ clippedY: visible && clipsY && element.scrollHeight > element.clientHeight + 1,
+ overlapsWith: [],
+ };
+ }).filter((item) => item.instanceId !== null);
+ const visible = elements.filter((item) => item.visible);
+ for (let leftIndex = 0; leftIndex < visible.length; leftIndex += 1) {
+ const left = visible[leftIndex];
+ const leftRect = left.element.getBoundingClientRect();
+ for (let rightIndex = leftIndex + 1; rightIndex < visible.length; rightIndex += 1) {
+ const right = visible[rightIndex];
+ if (left.overlapsWith.length >= overlapLimit && right.overlapsWith.length >= overlapLimit) continue;
+ if (left.element.contains(right.element) || right.element.contains(left.element)) continue;
+ const rightRect = right.element.getBoundingClientRect();
+ const intersectionWidth = Math.min(leftRect.right, rightRect.right) - Math.max(leftRect.left, rightRect.left);
+ const intersectionHeight = Math.min(leftRect.bottom, rightRect.bottom) - Math.max(leftRect.top, rightRect.top);
+ if (intersectionWidth <= 1 || intersectionHeight <= 1) continue;
+ if (left.overlapsWith.length < overlapLimit) left.overlapsWith.push(right.instanceId);
+ if (right.overlapsWith.length < overlapLimit) right.overlapsWith.push(left.instanceId);
+ }
+ }
+ return {
+ total: candidates.length,
+ sampled: elements.length,
+ truncated: candidates.length > limit,
+ elements: elements.map(({ element: _element, ...item }) => item),
+ };
+ })()`,
+ returnByValue: true,
+ });
+ const value = response.result?.value;
+ if (typeof value !== "object" || value === null) {
+ return { total: 0, sampled: 0, truncated: false, elements: [] };
+ }
+ const geometry = value as Record<string, unknown>;
+ if (
+ typeof geometry.total !== "number" ||
+ typeof geometry.sampled !== "number" ||
+ typeof geometry.truncated !== "boolean" ||
+ Array.isArray(geometry.elements) === false
+ ) {
+ return { total: 0, sampled: 0, truncated: false, elements: [] };
+ }
+ const elements = geometry.elements.flatMap((value) => {
+ if (typeof value !== "object" || value === null) {
+ return [];
+ }
+ const element = value as Record<string, unknown>;
+ if (
+ typeof element.instanceId !== "string" ||
+ typeof element.tagName !== "string" ||
+ typeof element.x !== "number" ||
+ typeof element.y !== "number" ||
+ typeof element.width !== "number" ||
+ typeof element.height !== "number" ||
+ typeof element.visible !== "boolean" ||
+ typeof element.clippedX !== "boolean" ||
+ typeof element.clippedY !== "boolean" ||
+ Array.isArray(element.overlapsWith) === false ||
+ element.overlapsWith.some((id) => typeof id !== "string")
+ ) {
+ return [];
+ }
+ const hiddenReason: BrowserScreenshotElement["hiddenReason"] =
+ element.hiddenReason === "display" ||
+ element.hiddenReason === "visibility" ||
+ element.hiddenReason === "opacity" ||
+ element.hiddenReason === "hidden"
+ ? element.hiddenReason
+ : undefined;
+ const overlapsWith = (element.overlapsWith as unknown[])
+ .filter((id): id is string => typeof id === "string")
+ .slice(0, maxBrowserScreenshotOverlapsPerElement);
+ return [
+ {
+ instanceId: element.instanceId,
+ tagName: element.tagName,
+ x: element.x,
+ y: element.y,
+ width: element.width,
+ height: element.height,
+ visible: element.visible,
+ ...(hiddenReason === undefined ? {} : { hiddenReason }),
+ clippedX: element.clippedX,
+ clippedY: element.clippedY,
+ overlapsWith,
+ },
+ ];
+ });
+ return {
+ total: Math.max(0, Math.round(geometry.total)),
+ sampled: elements.length,
+ truncated: geometry.truncated,
+ elements,
+ };
+};
+
const getBrowserScreenshotResources = async (
send: <Result = unknown>(
method: string,
@@ -597,6 +763,128 @@ const getBrowserScreenshotResources = async (
});
};
+const getBrowserScreenshotContrasts = async (
+ send: <Result = unknown>(
+ method: string,
+ params?: Record<string, unknown>
+ ) => Promise<Result>
+): Promise<BrowserScreenshotContrast[]> => {
+ const response = await send<{
+ result?: { value?: unknown };
+ }>("Runtime.evaluate", {
+ expression: `(() => {
+ const limit = ${maxBrowserScreenshotElements};
+ const parseOpaqueRgb = (value) => {
+ const match = value.match(/^rgba?\\(\\s*(\\d+(?:\\.\\d+)?)\\D+(\\d+(?:\\.\\d+)?)\\D+(\\d+(?:\\.\\d+)?)(?:\\D+(\\d+(?:\\.\\d+)?))?\\s*\\)$/i);
+ if (match === null || (match[4] !== undefined && Number(match[4]) !== 1)) return undefined;
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
+ };
+ const luminance = (rgb) => {
+ const channels = rgb.map((value) => {
+ const channel = value / 255;
+ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
+ });
+ return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2];
+ };
+ const candidates = Array.from(document.querySelectorAll("[data-ws-id]"))
+ .filter((element) => Array.from(element.childNodes).some((node) => node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== ""))
+ .slice(0, limit);
+ return candidates.flatMap((element) => {
+ if (element.closest(":disabled,[aria-disabled='true']") !== null) return [];
+ const style = getComputedStyle(element);
+ const rect = element.getBoundingClientRect();
+ if (rect.width <= 0 || rect.height <= 0 || style.display === "none" || style.visibility !== "visible") return [];
+ const foreground = parseOpaqueRgb(style.color);
+ if (foreground === undefined || style.textShadow !== "none" || style.webkitBackgroundClip === "text") return [];
+ const ancestors = [];
+ let current = element;
+ let background;
+ while (current instanceof Element) {
+ ancestors.push(current);
+ const currentStyle = getComputedStyle(current);
+ const before = getComputedStyle(current, "::before");
+ const after = getComputedStyle(current, "::after");
+ if (
+ Number(currentStyle.opacity) !== 1 ||
+ currentStyle.backgroundImage !== "none" ||
+ currentStyle.mixBlendMode !== "normal" ||
+ currentStyle.filter !== "none" ||
+ currentStyle.backdropFilter !== "none" ||
+ (before.content !== "none" && before.content !== "normal") ||
+ (after.content !== "none" && after.content !== "normal")
+ ) return [];
+ const color = parseOpaqueRgb(currentStyle.backgroundColor);
+ if (color !== undefined) {
+ background = { rgb: color, value: currentStyle.backgroundColor, element: current };
+ break;
+ }
+ if (currentStyle.backgroundColor !== "rgba(0, 0, 0, 0)" && currentStyle.backgroundColor !== "transparent") return [];
+ current = current.parentElement;
+ }
+ if (background === undefined) return [];
+ const range = document.createRange();
+ const textNode = Array.from(element.childNodes).find((node) => node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== "");
+ if (textNode === undefined) return [];
+ range.selectNodeContents(textNode);
+ const textRect = range.getBoundingClientRect();
+ if (
+ textRect.width <= 0 ||
+ textRect.height <= 0 ||
+ textRect.right <= 0 ||
+ textRect.bottom <= 0 ||
+ textRect.left >= window.innerWidth ||
+ textRect.top >= window.innerHeight
+ ) return [];
+ const x = Math.min(window.innerWidth - 1, Math.max(0, textRect.left + textRect.width / 2));
+ const y = Math.min(window.innerHeight - 1, Math.max(0, textRect.top + textRect.height / 2));
+ const stack = document.elementsFromPoint(x, y);
+ const backgroundIndex = stack.indexOf(background.element);
+ if (backgroundIndex < 0 || stack.slice(0, backgroundIndex).some((candidate) => !element.contains(candidate) && !candidate.contains(element))) return [];
+ const foregroundLuminance = luminance(foreground);
+ const backgroundLuminance = luminance(background.rgb);
+ const ratio = (Math.max(foregroundLuminance, backgroundLuminance) + 0.05) / (Math.min(foregroundLuminance, backgroundLuminance) + 0.05);
+ const fontSize = Number.parseFloat(style.fontSize);
+ const parsedWeight = Number.parseInt(style.fontWeight, 10);
+ const fontWeight = Number.isFinite(parsedWeight) ? parsedWeight : style.fontWeight === "bold" ? 700 : 400;
+ const requiredRatio = fontSize >= 24 || (fontSize >= 18.66 && fontWeight >= 700) ? 3 : 4.5;
+ return [{
+ instanceId: element.getAttribute("data-ws-id"),
+ tagName: element.tagName.toLowerCase(),
+ foreground: style.color,
+ background: background.value,
+ ratio,
+ requiredRatio,
+ fontSize,
+ fontWeight,
+ }];
+ });
+ })()`,
+ returnByValue: true,
+ });
+ if (Array.isArray(response.result?.value) === false) {
+ return [];
+ }
+ return response.result.value.flatMap((value) => {
+ if (typeof value !== "object" || value === null) {
+ return [];
+ }
+ const contrast = value as Record<string, unknown>;
+ if (
+ typeof contrast.instanceId !== "string" ||
+ typeof contrast.tagName !== "string" ||
+ typeof contrast.foreground !== "string" ||
+ typeof contrast.background !== "string" ||
+ typeof contrast.ratio !== "number" ||
+ (contrast.requiredRatio !== 3 && contrast.requiredRatio !== 4.5) ||
+ typeof contrast.fontSize !== "number" ||
+ typeof contrast.fontWeight !== "number"
+ ) {
+ return [];
+ }
+ return [contrast as BrowserScreenshotContrast];
+ });
+};
+
const getBrowserScreenshotImages = async (
send: <Result = unknown>(
method: string,
@@ -699,8 +987,10 @@ const getBrowserScreenshotLayout = (
metrics: BrowserLayoutMetricsResponse,
documentMetrics: BrowserDocumentMetrics,
viewport: { width: number; height: number },
+ elementGeometry: BrowserScreenshotElementGeometry,
images: BrowserScreenshotImage[],
- resources: BrowserScreenshotResource[]
+ resources: BrowserScreenshotResource[],
+ contrasts: BrowserScreenshotContrast[]
): BrowserScreenshotLayout => {
const contentWidth = documentMetrics.scrollWidth;
const contentHeight = documentMetrics.scrollHeight;
@@ -727,8 +1017,10 @@ const getBrowserScreenshotLayout = (
horizontalOverflow:
documentMetrics.horizontalOverflowSuppressed === false &&
contentWidth > viewportWidth + 1,
+ elementGeometry,
images,
resources,
+ contrasts,
};
};
@@ -1105,6 +1397,8 @@ const capturePageWithBrowserRuntime = async (
options.timeout
);
const documentMetricsPromise = getBrowserDocumentMetrics(send);
+ const elementGeometryPromise =
+ getBrowserScreenshotElementGeometry(send);
const imageInspectionPromise = measureDuration(async () =>
options.includeImageMetrics === true
? await getBrowserScreenshotImages(send)
@@ -1115,6 +1409,11 @@ const capturePageWithBrowserRuntime = async (
? await getBrowserScreenshotResources(send)
: undefined
);
+ const contrastInspectionPromise = measureDuration(async () =>
+ options.includeContrastMetrics === true
+ ? await getBrowserScreenshotContrasts(send)
+ : undefined
+ );
const screenshotPromise = (async () => {
const metrics = await metricsPromise;
const captureParams = await getScreenshotCaptureParams({
@@ -1146,15 +1445,19 @@ const capturePageWithBrowserRuntime = async (
locationResult,
metrics,
documentMetrics,
+ elementGeometry,
imageInspection,
resourceInspection,
+ contrastInspection,
screenshot,
] = await Promise.all([
locationPromise,
metricsPromise,
documentMetricsPromise,
+ elementGeometryPromise,
imageInspectionPromise,
resourceInspectionPromise,
+ contrastInspectionPromise,
screenshotPromise,
]);
const finalUrl =
@@ -1174,12 +1477,15 @@ const capturePageWithBrowserRuntime = async (
: (redirectsByFrame.get(navigationFrameId) ?? []);
const images = imageInspection.value;
const resources = resourceInspection.value;
+ const contrasts = contrastInspection.value;
const layout = getBrowserScreenshotLayout(
metrics,
documentMetrics,
{ width: options.width, height: options.height },
+ elementGeometry,
images ?? [],
- resources ?? []
+ resources ?? [],
+ contrasts ?? []
);
layout.navigation = {
requestedUrl: options.url,
@@ -1204,6 +1510,9 @@ const capturePageWithBrowserRuntime = async (
if (resources === undefined) {
delete layout.resources;
}
+ if (contrasts === undefined) {
+ delete layout.contrasts;
+ }
layout.timings = {
wallMs: Date.now() - viewportStartedAt,
targetSetupMs: index === 0 ? targetSetupMs : 0,
diff --git a/packages/cli/src/screenshot.ts b/packages/cli/src/screenshot.ts
index 270653ff60..81a5631db1 100644
--- a/packages/cli/src/screenshot.ts
+++ b/packages/cli/src/screenshot.ts
@@ -511,6 +511,7 @@ type CaptureScreenshotOptions = {
fullPage?: boolean;
includeImageMetrics?: boolean;
includeResourceMetrics?: boolean;
+ includeContrastMetrics?: boolean;
browser: ScreenshotBrowser;
browserPath?: string;
waitUntil?: ScreenshotWaitUntil;
@@ -522,6 +523,31 @@ type CaptureScreenshotOptions = {
scale?: number;
};
+const getBrowserScreenshotOptions = (
+ options: CaptureScreenshotOptions,
+ browserPath: string,
+ output: string,
+ dependencies: ScreenshotDependencies
+): BrowserScreenshotOptions => ({
+ browserPath,
+ output,
+ width: options.width,
+ height: options.height,
+ fullPage: options.fullPage,
+ includeImageMetrics: options.includeImageMetrics,
+ includeResourceMetrics: options.includeResourceMetrics,
+ includeContrastMetrics: options.includeContrastMetrics,
+ 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,
+});
+
const captureResolvedScreenshot = async (
options: CaptureScreenshotOptions,
browser: BrowserCandidate,
@@ -535,24 +561,12 @@ const captureResolvedScreenshot = async (
format: options.format,
});
await dependencies.mkdir(dirname(output), { recursive: true });
- const browserScreenshotOptions = {
- browserPath: browser.path,
+ const browserScreenshotOptions = getBrowserScreenshotOptions(
+ options,
+ browser.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,
- };
+ dependencies
+ );
const layout =
browserSession !== undefined
? await browserSession.capture(browserScreenshotOptions)
@@ -609,22 +623,12 @@ export const createScreenshotCaptureSession = (
);
}
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,
- },
+ getBrowserScreenshotOptions(
+ options,
+ resolvedBrowser.path,
+ options.output ?? "",
+ dependencies
+ ),
dependencies
);
browserSession ??= await browserSessionPromise;
@@ -670,25 +674,12 @@ export const createScreenshotCaptureSession = (
return {
options,
output,
- browserOptions: {
- browserPath: resolvedBrowser.path,
+ browserOptions: getBrowserScreenshotOptions(
+ options,
+ 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,
- },
+ dependencies
+ ),
};
})
);
@@ -742,6 +733,7 @@ export const captureScreenshotWithBrowserInstall = async (
fullPage?: boolean;
includeImageMetrics?: boolean;
includeResourceMetrics?: boolean;
+ includeContrastMetrics?: boolean;
browser: ScreenshotBrowser;
browserPath?: string;
waitUntil?: ScreenshotWaitUntil;
diff --git a/packages/cli/src/type-utils.ts b/packages/cli/src/type-utils.ts
new file mode 100644
index 0000000000..09606b7609
--- /dev/null
+++ b/packages/cli/src/type-utils.ts
@@ -0,0 +1,6 @@
+export const isPlainRecord = (
+ value: unknown
+): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && Array.isArray(value) === false;
+
+export const boundedIdentifierPattern = /^[A-Za-z0-9._:/-]{1,128}$/;
diff --git a/packages/css-data/src/selector-validation.test.ts b/packages/css-data/src/selector-validation.test.ts
index bd0dd54a9d..d50f660d18 100644
--- a/packages/css-data/src/selector-validation.test.ts
+++ b/packages/css-data/src/selector-validation.test.ts
@@ -2,6 +2,39 @@ import { describe, test, expect } from "vitest";
import { validateSelector } from "./selector-validation";
describe("validateSelector", () => {
+ test.each([
+ ":hover, body",
+ ":hover > div",
+ ":hover .child",
+ "body:hover",
+ ".class",
+ "#identifier",
+ ])(
+ "rejects selector syntax that can escape element scope: %s",
+ (selector) => {
+ expect(validateSelector(selector)).toMatchObject({ success: false });
+ }
+ );
+
+ test.each([
+ ":hover:focus-visible",
+ "[data-state=open]:hover",
+ ":not(.disabled, [aria-disabled=true])",
+ ])("accepts compound state suffixes: %s", (selector) => {
+ expect(validateSelector(selector).success).toBe(true);
+ });
+
+ test.each([
+ ":not-a-real-state:hover",
+ ":hover:not-a-real-state",
+ ":hover::not-a-real-element",
+ ":not(:not-a-real-state)",
+ ])(
+ "rejects invalid selectors anywhere in a compound state: %s",
+ (selector) => {
+ expect(validateSelector(selector)).toMatchObject({ success: false });
+ }
+ );
describe("valid selectors", () => {
test("simple pseudo-classes", () => {
const selectors = [
diff --git a/packages/css-data/src/selector-validation.ts b/packages/css-data/src/selector-validation.ts
index 2ea4dc92c5..a5006fe43c 100644
--- a/packages/css-data/src/selector-validation.ts
+++ b/packages/css-data/src/selector-validation.ts
@@ -7,7 +7,12 @@ export type SelectorValidationResult =
| { success: true; type: "pseudo-class" | "pseudo-element" | "attribute" };
/**
- * Validates a CSS pseudo-class, pseudo-element, or attribute selector
+ * Validates an open CSS state suffix scoped to the current element.
+ *
+ * Builder states are not a closed component-state enum. Valid pseudo-classes,
+ * pseudo-elements, and attribute selectors may be compounded, but selector
+ * lists, type/class/id selectors, and combinators are rejected because the CSS
+ * engine appends this value directly to the generated instance selector.
* @param selector - The selector to validate (e.g., ":hover", "::before", "[data-state=open]")
* @returns SelectorValidationResult with success status and type or error message
*/
@@ -28,25 +33,43 @@ export const validateSelector = (
}
try {
- // Parse as a rule to validate syntax
- // We wrap it in a dummy selector because css-tree requires a full rule
- const ast = csstree.parse(`dummy${selector} {}`);
+ const ast = csstree.parse(selector, { context: "selectorList" });
+ if (ast.type !== "SelectorList" || ast.children.size !== 1) {
+ return {
+ success: false,
+ error: "Selector must be one state scoped to the current element",
+ };
+ }
+ const parsedSelector = ast.children.first;
+ if (
+ parsedSelector?.type !== "Selector" ||
+ parsedSelector.children
+ .toArray()
+ .some(
+ (node) =>
+ node.type !== "PseudoClassSelector" &&
+ node.type !== "PseudoElementSelector" &&
+ node.type !== "AttributeSelector"
+ )
+ ) {
+ return {
+ success: false,
+ error:
+ "Selector must be a pseudo-class, pseudo-element, or attribute suffix scoped to the current element",
+ };
+ }
- let foundPseudoClass = false;
- let foundPseudoElement = false;
+ const pseudoClassNames: string[] = [];
+ const pseudoElementNames: string[] = [];
let foundAttribute = false;
- let pseudoClassName: string | undefined;
- let pseudoElementName: string | undefined;
// Walk the AST to find pseudo-class, pseudo-element, or attribute selectors
csstree.walk(ast, (node) => {
if (node.type === "PseudoClassSelector") {
- foundPseudoClass = true;
- pseudoClassName = node.name;
+ pseudoClassNames.push(node.name);
}
if (node.type === "PseudoElementSelector") {
- foundPseudoElement = true;
- pseudoElementName = node.name;
+ pseudoElementNames.push(node.name);
}
if (node.type === "AttributeSelector") {
foundAttribute = true;
@@ -54,54 +77,40 @@ export const validateSelector = (
});
// Determine the type based on what we found
- if (foundPseudoElement) {
+ const isKnownSelector = (name: string, known: readonly string[]) =>
+ known.includes(name) || known.includes(`${name}()`);
+ if (
+ pseudoElementNames.some(
+ (name) => isKnownSelector(name, pseudoElements) === false
+ )
+ ) {
+ return { success: false, error: "Invalid pseudo-element" };
+ }
+ const invalidPseudoClass = pseudoClassNames.find(
+ (name) =>
+ isKnownSelector(name, pseudoClasses) === false &&
+ isKnownSelector(name, pseudoElements) === false
+ );
+ if (invalidPseudoClass !== undefined) {
+ return { success: false, error: "Invalid pseudo-class" };
+ }
+
+ if (pseudoElementNames.length > 0) {
// Validate that the pseudo-element actually exists
// Some pseudo-elements are functional (e.g., ::part(), ::slotted())
// The list includes both "part" and "part()" variants
- if (pseudoElementName) {
- const withParens = `${pseudoElementName}()`;
- if (
- (pseudoElements as readonly string[]).includes(pseudoElementName) ||
- (pseudoElements as readonly string[]).includes(withParens)
- ) {
- return { success: true, type: "pseudo-element" };
- }
- }
- // Invalid pseudo-element name
- return {
- success: false,
- error: "Invalid pseudo-element",
- };
+ return { success: true, type: "pseudo-element" };
}
- if (foundPseudoClass) {
+ if (pseudoClassNames.length > 0) {
// Check if it's actually a legacy pseudo-element (single colon)
// Legacy syntax: :before, :after, :first-line, :first-letter
if (
- pseudoClassName &&
- (pseudoElements as readonly string[]).includes(pseudoClassName)
+ pseudoClassNames.every((name) => isKnownSelector(name, pseudoElements))
) {
return { success: true, type: "pseudo-element" };
}
-
- // Validate that the pseudo-class actually exists
- // Some pseudo-classes are functional (e.g., :has(), :not())
- // The list includes both "has" and "has()" variants
- if (pseudoClassName) {
- const withParens = `${pseudoClassName}()`;
- if (
- (pseudoClasses as readonly string[]).includes(pseudoClassName) ||
- (pseudoClasses as readonly string[]).includes(withParens)
- ) {
- return { success: true, type: "pseudo-class" };
- }
- }
-
- // Invalid pseudo-class name
- return {
- success: false,
- error: "Invalid pseudo-class",
- };
+ return { success: true, type: "pseudo-class" };
}
if (foundAttribute) {
diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.ts
index 7c2fca24da..43a2737b5a 100644
--- a/packages/http-client/src/index.test.ts
+++ b/packages/http-client/src/index.test.ts
@@ -435,7 +435,8 @@ test("wraps project api trpc calls in named functions", async () => {
});
await listPages({
...params,
- includeFolders: true,
+ limit: 20,
+ verbose: true,
});
await getPage({
...params,
@@ -807,7 +808,8 @@ test("wraps project api trpc calls in named functions", async () => {
await getProjectPermissions(params);
await listFolders({
...params,
- includePages: true,
+ cursor: "20",
+ limit: 20,
});
await applyBuildPatch({
...params,
diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.ts
index 1d01938cc2..39059ad865 100644
--- a/packages/http-client/src/index.ts
+++ b/packages/http-client/src/index.ts
@@ -201,6 +201,12 @@ type AuthProjectParams = {
headers?: RequestHeaders;
};
+type PaginatedQueryInput = {
+ cursor?: string;
+ limit?: number;
+ verbose?: boolean;
+};
+
type AuthTokenParams = {
origin: string;
authToken: string;
@@ -694,6 +700,9 @@ export const getBuildSnapshot = projectQueryInput<
AuthProjectParams & {
include?: string[];
version?: number;
+ verbose?: boolean;
+ cursor?: string;
+ limit?: number;
}
>("snapshot");
@@ -737,9 +746,7 @@ type PageFieldsInput = {
};
export const listPages = projectQueryInput<
- AuthProjectParams & {
- includeFolders?: boolean;
- }
+ AuthProjectParams & PaginatedQueryInput
>("list-pages");
export const getPage = projectQueryInput<
@@ -901,6 +908,10 @@ export const upsertResourceProp = runtimeProjectMutation(
"upsert-resource-prop"
);
+export const integrateRuntimeUi = runtimeProjectMutation(
+ "integrate-runtime-ui"
+);
+
export const updateAsset = runtimeProjectMutation("update-asset");
export const addAsset = runtimeProjectMutation("add-asset");
@@ -918,17 +929,17 @@ type ProjectSettingsInput = {
};
};
-export const getProjectSettings = projectQuery(
- getPublicApiOperationPath("get-project-settings")
-);
+export const getProjectSettings = projectQueryInput<
+ AuthProjectParams & Pick<PaginatedQueryInput, "verbose">
+>("get-project-settings");
export const updateProjectSettings = projectMutationInput<
AuthProjectParams & ProjectSettingsInput
>("update-project-settings");
-export const listRedirects = projectQuery(
- getPublicApiOperationPath("list-redirects")
-);
+export const listRedirects = projectQueryInput<
+ AuthProjectParams & PaginatedQueryInput
+>("list-redirects");
export const createRedirect = projectMutationInput<
AuthProjectParams & {
@@ -955,9 +966,9 @@ export const deleteRedirect = projectMutationInput<
}
>("delete-redirect");
-export const listBreakpoints = projectQuery(
- getPublicApiOperationPath("list-breakpoints")
-);
+export const listBreakpoints = projectQueryInput<
+ AuthProjectParams & PaginatedQueryInput
+>("list-breakpoints");
type BreakpointInput = {
id: string;
@@ -1005,9 +1016,9 @@ export const duplicatePage = projectMutationInput<
}
>("duplicate-page");
-export const listPageTemplates = projectQuery(
- getPublicApiOperationPath("list-page-templates")
-);
+export const listPageTemplates = projectQueryInput<
+ AuthProjectParams & PaginatedQueryInput
+>("list-page-templates");
export const createPageFromTemplate = projectMutationInput<
AuthProjectParams & {
@@ -1019,9 +1030,7 @@ export const createPageFromTemplate = projectMutationInput<
>("create-page-from-template");
export const listFolders = projectQueryInput<
- AuthProjectParams & {
- includePages?: boolean;
- }
+ AuthProjectParams & PaginatedQueryInput
>("list-folders");
export const createFolder = projectMutationInput<
@@ -1050,15 +1059,19 @@ export const deleteFolder = projectMutationInput<
>("delete-folder");
export const searchProject = projectQueryInput<
- AuthProjectParams & Record<string, unknown>
+ AuthProjectParams & PaginatedQueryInput & Record<string, unknown>
>("search-project");
export const audit = projectQueryInput<
AuthProjectParams & Record<string, unknown>
>("audit");
+export const verifyBindings = projectQueryInput<
+ AuthProjectParams & PaginatedQueryInput & Record<string, unknown>
+>("verify-bindings");
+
export const listFonts = projectQueryInput<
- AuthProjectParams & Record<string, unknown>
+ AuthProjectParams & PaginatedQueryInput & Record<string, unknown>
>("list-fonts");
export const replacePropText = projectMutationInput<
@@ -1078,16 +1091,17 @@ export const setImageDescriptions = projectMutationInput<
>("set-image-descriptions");
export const listInstances = projectQueryInput<
- AuthProjectParams & {
- pageId?: string;
- pagePath?: string;
- rootInstanceId?: string;
- maxDepth?: number;
- topLevelOnly?: boolean;
- component?: string;
- tag?: string;
- labelContains?: string;
- }
+ AuthProjectParams &
+ PaginatedQueryInput & {
+ pageId?: string;
+ pagePath?: string;
+ rootInstanceId?: string;
+ maxDepth?: number;
+ topLevelOnly?: boolean;
+ component?: string;
+ tag?: string;
+ labelContains?: string;
+ }
>("list-instances");
export const inspectInstance = projectQueryInput<
@@ -1200,8 +1214,7 @@ export const listTexts = projectQueryInput<
instanceId?: string;
mode?: "text" | "expression" | "all";
contains?: string;
- maxValueLength?: number;
- }
+ } & PaginatedQueryInput
>("list-texts");
export const updateText = projectMutationInput<
@@ -1265,11 +1278,12 @@ export const replaceStyleValues = projectMutationInput<
>("replace-styles");
export const listDesignTokens = projectQueryInput<
- AuthProjectParams & {
- filter?: string;
- withUsage?: boolean;
- sort?: "name" | "usage";
- }
+ AuthProjectParams &
+ PaginatedQueryInput & {
+ filter?: string;
+ withUsage?: boolean;
+ sort?: "name" | "usage";
+ }
>("list-design-tokens");
type DesignTokenStyleInput = {
@@ -1327,10 +1341,11 @@ export const extractDesignToken = projectMutationInput<
>("extract-design-token");
export const listCssVariables = projectQueryInput<
- AuthProjectParams & {
- filter?: string;
- withUsage?: boolean;
- }
+ AuthProjectParams &
+ PaginatedQueryInput & {
+ filter?: string;
+ withUsage?: boolean;
+ }
>("list-css-variables");
export const defineCssVariables = projectMutationInput<
@@ -1362,9 +1377,10 @@ type VariableValueInput =
| { type: "json"; value: unknown };
export const listVariables = projectQueryInput<
- AuthProjectParams & {
- scopeInstanceId?: string;
- }
+ AuthProjectParams &
+ PaginatedQueryInput & {
+ scopeInstanceId?: string;
+ }
>("list-variables");
export const createVariable = projectMutationInput<
@@ -1403,9 +1419,10 @@ type ResourceFieldsInput = {
};
export const listResources = projectQueryInput<
- AuthProjectParams & {
- scopeInstanceId?: string;
- }
+ AuthProjectParams &
+ PaginatedQueryInput & {
+ scopeInstanceId?: string;
+ }
>("list-resources");
export const createResource = projectMutationInput<
@@ -1432,9 +1449,9 @@ export const deleteResource = projectMutationInput<
}
>("delete-resource");
-export const listPublishes = projectQuery(
- getPublicApiOperationPath("list-publishes")
-);
+export const listPublishes = projectQueryInput<
+ AuthProjectParams & PaginatedQueryInput
+>("list-publishes");
export const publish = projectMutationInput<
AuthProjectParams & {
@@ -1458,9 +1475,9 @@ export const unpublish = projectConfirmedMutationInput<
}
>("unpublish");
-export const listDomains = projectQuery(
- getPublicApiOperationPath("list-domains")
-);
+export const listDomains = projectQueryInput<
+ AuthProjectParams & PaginatedQueryInput
+>("list-domains");
export const createDomain = projectMutationInput<
AuthProjectParams & { domain: string }
@@ -1482,19 +1499,19 @@ export const verifyDomain = projectMutationInput<
>("verify-domain");
export const listAssets = projectQueryInput<
- AuthProjectParams & {
- type?: "image" | "font";
- sort?: "name" | "size" | "createdAt" | "usage";
- withUsage?: boolean;
- cursor?: string;
- limit?: number;
- }
+ AuthProjectParams &
+ PaginatedQueryInput & {
+ type?: "image" | "font";
+ sort?: "name" | "size" | "createdAt" | "usage";
+ withUsage?: boolean;
+ }
>("list-assets");
export const findAssetUsage = projectQueryInput<
- AuthProjectParams & {
- assetId: string;
- }
+ AuthProjectParams &
+ PaginatedQueryInput & {
+ assetId: string;
+ }
>("find-asset-usage");
export const replaceAsset = projectConfirmedMutationInput<
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 bc8622cc3a..1d35b6515f 100644
--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
@@ -10,7 +10,17 @@ export const runtimeOperationContractData = [
inputSchema: {
type: "object",
properties: {
- includeFolders: {
+ cursor: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
type: "boolean",
},
},
@@ -66,36 +76,45 @@ export const runtimeOperationContractData = [
additionalProperties: {},
},
},
- folders: {
- type: "array",
- items: {
- type: "object",
- properties: {
- id: {
- type: "string",
- },
- name: {
- type: "string",
- },
- slug: {
- type: "string",
- },
- parentFolderId: {
- type: "string",
- },
- children: {
- type: "array",
- items: {
- type: "string",
- },
- },
+ detail: {
+ type: "string",
+ enum: ["compact", "verbose"],
+ },
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ returnedCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
},
- required: ["id", "name", "slug", "children"],
- additionalProperties: {},
- },
+ {
+ type: "null",
+ },
+ ],
+ },
+ filters: {
+ type: "object",
+ properties: {},
+ additionalProperties: {},
+ required: [],
},
},
- required: ["pages"],
+ required: [
+ "pages",
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ],
additionalProperties: {},
},
readNamespaces: ["pages"],
@@ -1164,9 +1183,14 @@ export const runtimeOperationContractData = [
kind: "read",
inputSchema: {
type: "object",
- properties: {},
+ properties: {
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
+ },
+ },
required: [],
- additionalProperties: true,
},
outputSchema: {
type: "object",
@@ -1228,7 +1252,7 @@ export const runtimeOperationContractData = [
},
},
},
- required: ["meta", "compiler", "redirects"],
+ required: ["meta", "compiler"],
additionalProperties: {},
},
readNamespaces: ["pages", "projectSettings"],
@@ -1560,9 +1584,22 @@ export const runtimeOperationContractData = [
kind: "read",
inputSchema: {
type: "object",
- properties: {},
+ properties: {
+ cursor: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
+ },
+ },
required: [],
- additionalProperties: true,
},
outputSchema: {
type: "object",
@@ -1588,8 +1625,45 @@ export const runtimeOperationContractData = [
additionalProperties: {},
},
},
+ detail: {
+ type: "string",
+ enum: ["compact", "verbose"],
+ },
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ returnedCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ filters: {
+ type: "object",
+ properties: {},
+ additionalProperties: {},
+ required: [],
+ },
},
- required: ["redirects"],
+ required: [
+ "redirects",
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ],
additionalProperties: {},
},
readNamespaces: ["pages"],
@@ -1768,9 +1842,22 @@ export const runtimeOperationContractData = [
kind: "read",
inputSchema: {
type: "object",
- properties: {},
+ properties: {
+ cursor: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
+ },
+ },
required: [],
- additionalProperties: true,
},
outputSchema: {
type: "object",
@@ -1800,8 +1887,45 @@ export const runtimeOperationContractData = [
additionalProperties: {},
},
},
+ detail: {
+ type: "string",
+ enum: ["compact", "verbose"],
+ },
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ returnedCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ filters: {
+ type: "object",
+ properties: {},
+ additionalProperties: {},
+ required: [],
+ },
},
- required: ["breakpoints"],
+ required: [
+ "breakpoints",
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ],
additionalProperties: {},
},
readNamespaces: ["breakpoints"],
@@ -2160,9 +2284,22 @@ export const runtimeOperationContractData = [
kind: "read",
inputSchema: {
type: "object",
- properties: {},
+ properties: {
+ cursor: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
+ },
+ },
required: [],
- additionalProperties: true,
},
outputSchema: {
type: "object",
@@ -2281,8 +2418,45 @@ export const runtimeOperationContractData = [
additionalProperties: {},
},
},
+ detail: {
+ type: "string",
+ enum: ["compact", "verbose"],
+ },
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ returnedCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ filters: {
+ type: "object",
+ properties: {},
+ additionalProperties: {},
+ required: [],
+ },
},
- required: ["templates"],
+ required: [
+ "templates",
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ],
additionalProperties: {},
},
readNamespaces: ["pages"],
@@ -2902,7 +3076,17 @@ export const runtimeOperationContractData = [
inputSchema: {
type: "object",
properties: {
- includePages: {
+ cursor: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
type: "boolean",
},
},
@@ -2939,55 +3123,45 @@ export const runtimeOperationContractData = [
additionalProperties: {},
},
},
- pages: {
- type: "array",
- items: {
- type: "object",
- properties: {
- id: {
- type: "string",
- },
- name: {
- type: "string",
- },
- path: {
- type: "string",
- },
- localPath: {
- type: "string",
- },
- title: {
- type: "string",
- },
- rootInstanceId: {
- type: "string",
- },
- parentFolderId: {
- type: "string",
- },
- isHome: {
- type: "boolean",
- },
- isDraft: {
- description:
- "True when the page is a draft. Missing or false means the page is publishable.",
- type: "boolean",
- },
+ detail: {
+ type: "string",
+ enum: ["compact", "verbose"],
+ },
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ returnedCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
},
- required: [
- "id",
- "name",
- "path",
- "localPath",
- "title",
- "rootInstanceId",
- "isHome",
- ],
- additionalProperties: {},
- },
+ {
+ type: "null",
+ },
+ ],
+ },
+ filters: {
+ type: "object",
+ properties: {},
+ additionalProperties: {},
+ required: [],
},
},
- required: ["folders"],
+ required: [
+ "folders",
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ],
additionalProperties: {},
},
readNamespaces: ["pages"],
@@ -32810,11 +32984,19 @@ export const runtimeOperationContractData = [
pagePath: {
type: "string",
},
+ cursor: {
+ type: "string",
+ },
limit: {
type: "integer",
minimum: 1,
maximum: 200,
},
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
+ },
},
required: ["query"],
additionalProperties: false,
@@ -32831,11 +33013,6 @@ export const runtimeOperationContractData = [
type: "string",
},
},
- total: {
- type: "integer",
- minimum: -9007199254740991,
- maximum: 9007199254740991,
- },
truncated: {
type: "boolean",
},
@@ -32852,8 +33029,48 @@ export const runtimeOperationContractData = [
additionalProperties: {},
},
},
+ detail: {
+ type: "string",
+ enum: ["compact", "verbose"],
+ },
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ returnedCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ filters: {
+ type: "object",
+ properties: {},
+ additionalProperties: {},
+ required: [],
+ },
},
- required: ["query", "scopes", "total", "truncated", "matches"],
+ required: [
+ "query",
+ "scopes",
+ "truncated",
+ "matches",
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ],
additionalProperties: {},
},
readNamespaces: [
@@ -32884,7 +33101,7 @@ export const runtimeOperationContractData = [
properties: {
scopes: {
description:
- "Audit scopes. Omit to run all scopes. accessibility errors: missing-alt, missing-image-input-alt, missing-iframe-title, missing-accessible-name, missing-form-label, invalid-aria-role, missing-required-aria-role-property, role-interactive-not-focusable, aria-hidden-focusable, invalid-aria-state, invalid-aria-number, autoplay-media-with-sound, invalid-label-reference, duplicate-id, and missing-aria-reference; warnings: missing-image-description, unsupported-aria-role-property, positive-tabindex, missing-page-heading, skipped-heading-level, missing-main-landmark, and multiple-main-landmarks. Documentation: https://www.w3.org/WAI/WCAG22/understanding/. security errors: non-get-resource-exposed-as-data-source; warning: target-blank-without-noopener. Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/noopener. seo errors: empty-page-title, invalid-json-ld, and json-ld-in-custom-metadata; warnings: missing-page-description, empty-page-description, invalid-page-language, missing-social-image-asset, duplicate-page-title, duplicate-page-description, missing-json-ld-context, unknown-schema-org-type, deprecated-schema-org-type, unknown-schema-org-property, deprecated-schema-org-property, unsupported-schema-org-property, and incompatible-schema-org-value. Documentation: https://developers.google.com/search/docs/fundamentals/seo-starter-guide. assets info: unused-asset. Documentation: https://docs.webstudio.is/university/foundations/anatomy-of-the-webstudio-builder. styles warning: style-on-dom-transparent-component; info: unused-design-token, unused-css-variable, unused-local-style-source, unused-breakpoint, and duplicate-design-token-declarations. Documentation: https://docs.webstudio.is/university/foundations/design-tokens. performance info: atomic-css-disabled. Rendered checks add image loading/sizing, render-blocking resource, and legacy font-format evidence. Documentation: https://docs.webstudio.is/university/foundations/project-settings#atomic-css.",
+ "Audit scopes. Omit to run all standard scopes; Craft remains opt-in. accessibility errors: missing-alt, missing-image-input-alt, missing-iframe-title, missing-accessible-name, missing-form-label, invalid-aria-role, missing-required-aria-role-property, role-interactive-not-focusable, aria-hidden-focusable, invalid-aria-state, invalid-aria-number, autoplay-media-with-sound, invalid-label-reference, duplicate-id, and missing-aria-reference; warnings: missing-image-description, unsupported-aria-role-property, positive-tabindex, missing-page-heading, skipped-heading-level, missing-main-landmark, and multiple-main-landmarks. Documentation: https://www.w3.org/WAI/WCAG22/understanding/. security errors: non-get-resource-exposed-as-data-source; warning: target-blank-without-noopener. Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/noopener. seo errors: empty-page-title, invalid-json-ld, and json-ld-in-custom-metadata; warnings: missing-page-description, empty-page-description, invalid-page-language, missing-social-image-asset, duplicate-page-title, duplicate-page-description, missing-json-ld-context, unknown-schema-org-type, deprecated-schema-org-type, unknown-schema-org-property, deprecated-schema-org-property, unsupported-schema-org-property, and incompatible-schema-org-value. Documentation: https://developers.google.com/search/docs/fundamentals/seo-starter-guide. assets info: unused-asset. Documentation: https://docs.webstudio.is/university/foundations/anatomy-of-the-webstudio-builder. styles warnings: style-on-dom-transparent-component, invalid-style-state-selector, and orphan-style-breakpoint; info: unused-design-token, unused-css-variable, unused-local-style-source, unused-breakpoint, and duplicate-design-token-declarations. Documentation: https://docs.webstudio.is/university/foundations/design-tokens. performance info: atomic-css-disabled. Rendered checks add image loading/sizing, render-blocking resource, and legacy font-format evidence. Documentation: https://docs.webstudio.is/university/foundations/project-settings#atomic-css. craft is an opt-in, read-only compatibility check and is excluded when scopes are omitted. Documentation: https://docs.webstudio.is/university/craft.",
minItems: 1,
type: "array",
items: {
@@ -32896,6 +33113,7 @@ export const runtimeOperationContractData = [
"assets",
"styles",
"performance",
+ "craft",
],
},
},
@@ -32958,6 +33176,7 @@ export const runtimeOperationContractData = [
"assets",
"styles",
"performance",
+ "craft",
],
},
},
@@ -32983,6 +33202,7 @@ export const runtimeOperationContractData = [
"assets",
"styles",
"performance",
+ "craft",
],
},
},
@@ -33031,6 +33251,7 @@ export const runtimeOperationContractData = [
"assets",
"styles",
"performance",
+ "craft",
],
},
additionalProperties: {
@@ -33045,6 +33266,7 @@ export const runtimeOperationContractData = [
"assets",
"styles",
"performance",
+ "craft",
],
},
},
@@ -33159,6 +33381,7 @@ export const runtimeOperationContractData = [
"oversized-image",
"render-blocking-resource",
"legacy-font-format",
+ "low-text-contrast",
],
},
},
@@ -33310,6 +33533,87 @@ export const runtimeOperationContractData = [
},
],
},
+ generatedBuildSummary: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ fileCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ bytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ gzipBytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ version: {
+ type: "number",
+ const: 1,
+ },
+ client: {
+ type: "object",
+ properties: {
+ fileCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ bytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ gzipBytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["fileCount", "bytes", "gzipBytes"],
+ },
+ server: {
+ type: "object",
+ properties: {
+ fileCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ bytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ gzipBytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["fileCount", "bytes", "gzipBytes"],
+ },
+ },
+ required: [
+ "fileCount",
+ "bytes",
+ "gzipBytes",
+ "version",
+ "client",
+ "server",
+ ],
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
nextCursor: {
anyOf: [
{
@@ -33320,6 +33624,89 @@ export const runtimeOperationContractData = [
},
],
},
+ profileStatuses: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ const: "craft",
+ },
+ profileVersion: {
+ type: "number",
+ const: 1,
+ },
+ craftVersion: {
+ type: "string",
+ const: "1.2",
+ },
+ sourceUrl: {
+ type: "string",
+ const: "https://docs.webstudio.is/university/craft",
+ },
+ status: {
+ type: "string",
+ enum: ["non-craft", "partial", "modified", "compatible"],
+ },
+ satisfiedRequiredChecks: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ totalRequiredChecks: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextAction: {
+ type: "string",
+ minLength: 1,
+ },
+ guidance: {
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ templateCompatibility: {
+ type: "object",
+ properties: {
+ profile: {
+ type: "string",
+ const: "[email protected]",
+ },
+ status: {
+ type: "string",
+ enum: [
+ "compatible",
+ "requires-review",
+ "not-applicable",
+ ],
+ },
+ reason: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ required: ["profile", "status", "reason"],
+ },
+ },
+ required: [
+ "id",
+ "profileVersion",
+ "craftVersion",
+ "sourceUrl",
+ "status",
+ "satisfiedRequiredChecks",
+ "totalRequiredChecks",
+ "nextAction",
+ "guidance",
+ "templateCompatibility",
+ ],
+ },
+ },
verbose: {
type: "boolean",
const: false,
@@ -33341,6 +33728,7 @@ export const runtimeOperationContractData = [
"assets",
"styles",
"performance",
+ "craft",
],
},
ruleId: {
@@ -33393,7 +33781,14 @@ export const runtimeOperationContractData = [
"unused-breakpoint",
"duplicate-design-token-declarations",
"style-on-dom-transparent-component",
+ "invalid-style-state-selector",
+ "orphan-style-breakpoint",
"atomic-css-disabled",
+ "craft-not-detected",
+ "craft-missing-semantic-variables",
+ "craft-container-token-missing",
+ "craft-container-token-incompatible",
+ "craft-style-guide-page-missing",
],
},
severity: {
@@ -33460,6 +33855,12 @@ export const runtimeOperationContractData = [
breakpointId: {
type: "string",
},
+ stateSelector: {
+ type: "string",
+ },
+ styleProperty: {
+ type: "string",
+ },
resourceId: {
type: "string",
},
@@ -33496,13 +33897,22 @@ export const runtimeOperationContractData = [
type: "string",
enum: [
"horizontal-overflow",
+ "clipped-content",
+ "hidden-content",
+ "overlapping-elements",
+ "cross-breakpoint-layout-change",
"broken-image",
"eager-below-fold-image",
"oversized-image",
"render-blocking-resource",
"legacy-font-format",
+ "low-text-contrast",
],
},
+ confidence: {
+ type: "string",
+ enum: ["exact", "advisory"],
+ },
count: {
type: "integer",
exclusiveMinimum: 0,
@@ -33521,7 +33931,13 @@ export const runtimeOperationContractData = [
},
},
},
- required: ["kind", "count", "captureCount", "pagePaths"],
+ required: [
+ "kind",
+ "confidence",
+ "count",
+ "captureCount",
+ "pagePaths",
+ ],
},
},
renderedFailureSummaries: {
@@ -33592,7 +34008,9 @@ export const runtimeOperationContractData = [
"renderedCaptureSummary",
"renderedCaptureStatuses",
"renderedArtifactManifest",
+ "generatedBuildSummary",
"nextCursor",
+ "profileStatuses",
"verbose",
"findings",
"renderedIssueSummaries",
@@ -33622,6 +34040,7 @@ export const runtimeOperationContractData = [
"assets",
"styles",
"performance",
+ "craft",
],
},
},
@@ -33647,6 +34066,7 @@ export const runtimeOperationContractData = [
"assets",
"styles",
"performance",
+ "craft",
],
},
},
@@ -33695,6 +34115,7 @@ export const runtimeOperationContractData = [
"assets",
"styles",
"performance",
+ "craft",
],
},
additionalProperties: {
@@ -33709,6 +34130,7 @@ export const runtimeOperationContractData = [
"assets",
"styles",
"performance",
+ "craft",
],
},
},
@@ -33823,6 +34245,7 @@ export const runtimeOperationContractData = [
"oversized-image",
"render-blocking-resource",
"legacy-font-format",
+ "low-text-contrast",
],
},
},
@@ -33974,6 +34397,87 @@ export const runtimeOperationContractData = [
},
],
},
+ generatedBuildSummary: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ fileCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ bytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ gzipBytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ version: {
+ type: "number",
+ const: 1,
+ },
+ client: {
+ type: "object",
+ properties: {
+ fileCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ bytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ gzipBytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["fileCount", "bytes", "gzipBytes"],
+ },
+ server: {
+ type: "object",
+ properties: {
+ fileCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ bytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ gzipBytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["fileCount", "bytes", "gzipBytes"],
+ },
+ },
+ required: [
+ "fileCount",
+ "bytes",
+ "gzipBytes",
+ "version",
+ "client",
+ "server",
+ ],
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
nextCursor: {
anyOf: [
{
@@ -33984,6 +34488,89 @@ export const runtimeOperationContractData = [
},
],
},
+ profileStatuses: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ const: "craft",
+ },
+ profileVersion: {
+ type: "number",
+ const: 1,
+ },
+ craftVersion: {
+ type: "string",
+ const: "1.2",
+ },
+ sourceUrl: {
+ type: "string",
+ const: "https://docs.webstudio.is/university/craft",
+ },
+ status: {
+ type: "string",
+ enum: ["non-craft", "partial", "modified", "compatible"],
+ },
+ satisfiedRequiredChecks: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ totalRequiredChecks: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextAction: {
+ type: "string",
+ minLength: 1,
+ },
+ guidance: {
+ type: "array",
+ items: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ templateCompatibility: {
+ type: "object",
+ properties: {
+ profile: {
+ type: "string",
+ const: "[email protected]",
+ },
+ status: {
+ type: "string",
+ enum: [
+ "compatible",
+ "requires-review",
+ "not-applicable",
+ ],
+ },
+ reason: {
+ type: "string",
+ minLength: 1,
+ },
+ },
+ required: ["profile", "status", "reason"],
+ },
+ },
+ required: [
+ "id",
+ "profileVersion",
+ "craftVersion",
+ "sourceUrl",
+ "status",
+ "satisfiedRequiredChecks",
+ "totalRequiredChecks",
+ "nextAction",
+ "guidance",
+ "templateCompatibility",
+ ],
+ },
+ },
verbose: {
type: "boolean",
const: true,
@@ -34005,6 +34592,7 @@ export const runtimeOperationContractData = [
"assets",
"styles",
"performance",
+ "craft",
],
},
ruleId: {
@@ -34057,7 +34645,14 @@ export const runtimeOperationContractData = [
"unused-breakpoint",
"duplicate-design-token-declarations",
"style-on-dom-transparent-component",
+ "invalid-style-state-selector",
+ "orphan-style-breakpoint",
"atomic-css-disabled",
+ "craft-not-detected",
+ "craft-missing-semantic-variables",
+ "craft-container-token-missing",
+ "craft-container-token-incompatible",
+ "craft-style-guide-page-missing",
],
},
severity: {
@@ -34130,6 +34725,12 @@ export const runtimeOperationContractData = [
breakpointId: {
type: "string",
},
+ stateSelector: {
+ type: "string",
+ },
+ styleProperty: {
+ type: "string",
+ },
resourceId: {
type: "string",
},
@@ -34185,6 +34786,7 @@ export const runtimeOperationContractData = [
"assets",
"styles",
"performance",
+ "craft",
],
},
checkId: {
@@ -34258,6 +34860,12 @@ export const runtimeOperationContractData = [
breakpointId: {
type: "string",
},
+ stateSelector: {
+ type: "string",
+ },
+ styleProperty: {
+ type: "string",
+ },
resourceId: {
type: "string",
},
@@ -34355,6 +34963,91 @@ export const runtimeOperationContractData = [
horizontalOverflow: {
type: "boolean",
},
+ elementGeometry: {
+ type: "object",
+ properties: {
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ sampled: {
+ type: "integer",
+ minimum: 0,
+ maximum: 250,
+ },
+ truncated: {
+ type: "boolean",
+ },
+ elements: {
+ maxItems: 250,
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ instanceId: {
+ type: "string",
+ },
+ tagName: {
+ type: "string",
+ },
+ x: {
+ type: "number",
+ },
+ y: {
+ type: "number",
+ },
+ width: {
+ type: "number",
+ minimum: 0,
+ },
+ height: {
+ type: "number",
+ minimum: 0,
+ },
+ visible: {
+ type: "boolean",
+ },
+ hiddenReason: {
+ type: "string",
+ enum: [
+ "display",
+ "visibility",
+ "opacity",
+ "hidden",
+ ],
+ },
+ clippedX: {
+ type: "boolean",
+ },
+ clippedY: {
+ type: "boolean",
+ },
+ overlapsWith: {
+ maxItems: 5,
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ },
+ required: [
+ "instanceId",
+ "tagName",
+ "x",
+ "y",
+ "width",
+ "height",
+ "visible",
+ "clippedX",
+ "clippedY",
+ "overlapsWith",
+ ],
+ },
+ },
+ },
+ required: ["total", "sampled", "truncated", "elements"],
+ },
images: {
type: "array",
items: {
@@ -34452,6 +35145,60 @@ export const runtimeOperationContractData = [
],
},
},
+ contrasts: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ instanceId: {
+ type: "string",
+ },
+ tagName: {
+ type: "string",
+ },
+ foreground: {
+ type: "string",
+ },
+ background: {
+ type: "string",
+ },
+ ratio: {
+ type: "number",
+ exclusiveMinimum: 0,
+ },
+ requiredRatio: {
+ anyOf: [
+ {
+ type: "number",
+ const: 3,
+ },
+ {
+ type: "number",
+ const: 4.5,
+ },
+ ],
+ },
+ fontSize: {
+ type: "number",
+ exclusiveMinimum: 0,
+ },
+ fontWeight: {
+ type: "number",
+ minimum: 0,
+ },
+ },
+ required: [
+ "instanceId",
+ "tagName",
+ "foreground",
+ "background",
+ "ratio",
+ "requiredRatio",
+ "fontSize",
+ "fontWeight",
+ ],
+ },
+ },
},
required: [
"viewportWidth",
@@ -34459,6 +35206,7 @@ export const runtimeOperationContractData = [
"contentWidth",
"contentHeight",
"horizontalOverflow",
+ "elementGeometry",
"images",
"resources",
],
@@ -34469,11 +35217,187 @@ export const runtimeOperationContractData = [
type: "string",
enum: [
"horizontal-overflow",
+ "clipped-content",
+ "hidden-content",
+ "overlapping-elements",
+ "cross-breakpoint-layout-change",
"broken-image",
"eager-below-fold-image",
"oversized-image",
"render-blocking-resource",
"legacy-font-format",
+ "low-text-contrast",
+ ],
+ },
+ },
+ geometryIssues: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ instanceId: {
+ type: "string",
+ },
+ relatedInstanceId: {
+ type: "string",
+ },
+ message: {
+ type: "string",
+ },
+ evidence: {
+ type: "object",
+ properties: {
+ clippedX: {
+ type: "boolean",
+ },
+ clippedY: {
+ type: "boolean",
+ },
+ hiddenReason: {
+ type: "string",
+ enum: [
+ "display",
+ "visibility",
+ "opacity",
+ "hidden",
+ ],
+ },
+ sourceViewportWidth: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ targetViewportWidth: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ sourceVisible: {
+ type: "boolean",
+ },
+ targetVisible: {
+ type: "boolean",
+ },
+ sourceX: {
+ type: "number",
+ },
+ targetX: {
+ type: "number",
+ },
+ sourceWidth: {
+ type: "number",
+ minimum: 0,
+ },
+ targetWidth: {
+ type: "number",
+ minimum: 0,
+ },
+ },
+ required: [],
+ },
+ kind: {
+ type: "string",
+ const: "clipped-content",
+ },
+ confidence: {
+ type: "string",
+ const: "exact",
+ },
+ },
+ required: [
+ "instanceId",
+ "message",
+ "evidence",
+ "kind",
+ "confidence",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ instanceId: {
+ type: "string",
+ },
+ relatedInstanceId: {
+ type: "string",
+ },
+ message: {
+ type: "string",
+ },
+ evidence: {
+ type: "object",
+ properties: {
+ clippedX: {
+ type: "boolean",
+ },
+ clippedY: {
+ type: "boolean",
+ },
+ hiddenReason: {
+ type: "string",
+ enum: [
+ "display",
+ "visibility",
+ "opacity",
+ "hidden",
+ ],
+ },
+ sourceViewportWidth: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ targetViewportWidth: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ sourceVisible: {
+ type: "boolean",
+ },
+ targetVisible: {
+ type: "boolean",
+ },
+ sourceX: {
+ type: "number",
+ },
+ targetX: {
+ type: "number",
+ },
+ sourceWidth: {
+ type: "number",
+ minimum: 0,
+ },
+ targetWidth: {
+ type: "number",
+ minimum: 0,
+ },
+ },
+ required: [],
+ },
+ kind: {
+ type: "string",
+ enum: [
+ "hidden-content",
+ "overlapping-elements",
+ "cross-breakpoint-layout-change",
+ ],
+ },
+ confidence: {
+ type: "string",
+ const: "advisory",
+ },
+ },
+ required: [
+ "instanceId",
+ "message",
+ "evidence",
+ "kind",
+ "confidence",
+ ],
+ },
],
},
},
@@ -34482,14 +35406,6 @@ export const runtimeOperationContractData = [
items: {
type: "object",
properties: {
- kind: {
- type: "string",
- enum: [
- "broken-image",
- "eager-below-fold-image",
- "oversized-image",
- ],
- },
instanceId: {
type: "string",
},
@@ -34526,15 +35442,23 @@ export const runtimeOperationContractData = [
top: {
type: "number",
},
+ kind: {
+ type: "string",
+ enum: [
+ "broken-image",
+ "eager-below-fold-image",
+ "oversized-image",
+ ],
+ },
},
required: [
- "kind",
"loading",
"naturalWidth",
"naturalHeight",
"renderedWidth",
"renderedHeight",
"top",
+ "kind",
],
},
},
@@ -34543,13 +35467,6 @@ export const runtimeOperationContractData = [
items: {
type: "object",
properties: {
- kind: {
- type: "string",
- enum: [
- "render-blocking-resource",
- "legacy-font-format",
- ],
- },
pathname: {
type: "string",
},
@@ -34575,15 +35492,86 @@ export const runtimeOperationContractData = [
renderBlockingStatus: {
type: "string",
},
+ kind: {
+ type: "string",
+ enum: [
+ "render-blocking-resource",
+ "legacy-font-format",
+ ],
+ },
},
required: [
- "kind",
"pathname",
"initiatorType",
"transferSize",
"encodedBodySize",
"decodedBodySize",
"duration",
+ "kind",
+ ],
+ },
+ },
+ contrastIssues: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ instanceId: {
+ type: "string",
+ },
+ tagName: {
+ type: "string",
+ },
+ foreground: {
+ type: "string",
+ },
+ background: {
+ type: "string",
+ },
+ ratio: {
+ type: "number",
+ exclusiveMinimum: 0,
+ },
+ requiredRatio: {
+ anyOf: [
+ {
+ type: "number",
+ const: 3,
+ },
+ {
+ type: "number",
+ const: 4.5,
+ },
+ ],
+ },
+ fontSize: {
+ type: "number",
+ exclusiveMinimum: 0,
+ },
+ fontWeight: {
+ type: "number",
+ minimum: 0,
+ },
+ kind: {
+ type: "string",
+ const: "low-text-contrast",
+ },
+ confidence: {
+ type: "string",
+ const: "exact",
+ },
+ },
+ required: [
+ "instanceId",
+ "tagName",
+ "foreground",
+ "background",
+ "ratio",
+ "requiredRatio",
+ "fontSize",
+ "fontWeight",
+ "kind",
+ "confidence",
],
},
},
@@ -34595,6 +35583,7 @@ export const runtimeOperationContractData = [
"screenshotPath",
"layout",
"issues",
+ "geometryIssues",
"imageIssues",
"resourceIssues",
],
@@ -34683,49 +35672,9990 @@ export const runtimeOperationContractData = [
],
},
},
+ generatedBuildMetrics: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ fileCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ bytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ gzipBytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ version: {
+ type: "number",
+ const: 1,
+ },
+ client: {
+ type: "object",
+ properties: {
+ fileCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ bytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ gzipBytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["fileCount", "bytes", "gzipBytes"],
+ },
+ server: {
+ type: "object",
+ properties: {
+ fileCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ bytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ gzipBytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["fileCount", "bytes", "gzipBytes"],
+ },
+ largestFiles: {
+ maxItems: 20,
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ path: {
+ type: "string",
+ },
+ bytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ gzipBytes: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ kind: {
+ type: "string",
+ enum: ["script", "style", "image", "font", "other"],
+ },
+ },
+ required: ["path", "bytes", "gzipBytes", "kind"],
+ },
+ },
+ },
+ required: [
+ "fileCount",
+ "bytes",
+ "gzipBytes",
+ "version",
+ "client",
+ "server",
+ "largestFiles",
+ ],
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ },
+ required: [
+ "contractVersion",
+ "projectVersion",
+ "scopes",
+ "pageFilter",
+ "summary",
+ "skippedCheckCount",
+ "manualCheckCount",
+ "renderedCheckCount",
+ "renderedIssueCount",
+ "renderedFailureCount",
+ "renderedState",
+ "renderedPlan",
+ "renderedCaptureSummary",
+ "renderedCaptureStatuses",
+ "renderedArtifactManifest",
+ "generatedBuildSummary",
+ "nextCursor",
+ "profileStatuses",
+ "verbose",
+ "findings",
+ "skippedChecks",
+ "manualChecks",
+ "renderedChecks",
+ "renderedFailures",
+ "generatedBuildMetrics",
+ ],
+ },
+ ],
+ },
+ readNamespaces: [
+ "pages",
+ "projectSettings",
+ "instances",
+ "props",
+ "styles",
+ "styleSources",
+ "styleSourceSelections",
+ "resources",
+ "dataSources",
+ "assets",
+ "breakpoints",
+ ],
+ writeNamespaces: [],
+ invalidatesNamespaces: [],
+ retryOnConflict: false,
+ requiresAssets: true,
+ },
+ {
+ id: "project.verifyBindings",
+ command: "verify-bindings",
+ client: "verifyBindings",
+ kind: "read",
+ inputSchema: {
+ type: "object",
+ properties: {
+ cursor: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
+ },
+ pageId: {
+ description: "Verify only bindings on this page.",
+ type: "string",
+ },
+ pagePath: {
+ description: "Verify only bindings on the page matching this path.",
+ type: "string",
+ },
+ instanceId: {
+ description: "Verify only bindings in this instance subtree.",
+ type: "string",
+ },
+ },
+ additionalProperties: false,
+ required: [],
+ },
+ outputSchema: {
+ type: "object",
+ properties: {
+ contractVersion: {
+ type: "number",
+ const: 1,
+ },
+ analysis: {
+ type: "object",
+ properties: {
+ staticIntegrity: {
+ type: "string",
+ const: "complete",
+ },
+ renderedResolution: {
+ type: "string",
+ const: "not-evaluated",
+ },
+ externalResourcesExecuted: {
+ type: "boolean",
+ const: false,
+ },
+ },
+ required: [
+ "staticIntegrity",
+ "renderedResolution",
+ "externalResourcesExecuted",
+ ],
+ },
+ summary: {
+ type: "object",
+ properties: {
+ bindingsChecked: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ findings: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["bindingsChecked", "findings"],
+ },
+ findings: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ code: {
+ type: "string",
+ enum: [
+ "invalid-expression",
+ "unknown-identifier",
+ "stale-data-source-id",
+ "out-of-scope-data-source",
+ "missing-resource",
+ "missing-parameter",
+ "out-of-scope-parameter",
+ ],
+ },
+ category: {
+ type: "string",
+ enum: ["validity", "scope", "reference"],
+ },
+ severity: {
+ type: "string",
+ enum: ["error", "warning"],
+ },
+ bindingKind: {
+ type: "string",
+ enum: [
+ "text-expression",
+ "prop-expression",
+ "prop-action",
+ "prop-resource",
+ "data-source-resource",
+ "prop-parameter",
+ "resource-expression",
+ "page-metadata",
+ ],
+ },
+ message: {
+ type: "string",
+ },
+ remediation: {
+ type: "string",
+ },
+ location: {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ pagePath: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ propId: {
+ type: "string",
+ },
+ propName: {
+ type: "string",
+ },
+ resourceId: {
+ type: "string",
+ },
+ dataSourceId: {
+ type: "string",
+ },
+ path: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ },
+ required: ["path"],
+ },
+ range: {
+ type: "object",
+ properties: {
+ from: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ to: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["from", "to"],
+ },
+ },
+ required: [
+ "id",
+ "code",
+ "category",
+ "severity",
+ "bindingKind",
+ "message",
+ "remediation",
+ "location",
+ ],
+ },
+ },
+ detail: {
+ type: "string",
+ enum: ["compact", "verbose"],
+ },
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ returnedCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ filters: {
+ type: "object",
+ properties: {},
+ additionalProperties: {},
+ required: [],
+ },
+ },
+ required: [
+ "contractVersion",
+ "analysis",
+ "summary",
+ "findings",
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ],
+ },
+ readNamespaces: ["pages", "instances", "props", "resources", "dataSources"],
+ writeNamespaces: [],
+ invalidatesNamespaces: [],
+ retryOnConflict: false,
+ },
+ {
+ id: "runtimeUi.integrate",
+ command: "integrate-runtime-ui",
+ client: "integrateRuntimeUi",
+ kind: "mutation",
+ inputSchema: {
+ type: "object",
+ properties: {
+ parentInstanceId: {
+ type: "string",
+ },
+ variables: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ minLength: 1,
+ },
+ value: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "number",
+ },
+ value: {
+ type: "number",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "string",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "boolean",
+ },
+ value: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "string[]",
+ },
+ value: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "json",
+ },
+ value: {},
+ },
+ required: ["type"],
+ },
+ ],
+ },
+ },
+ required: ["name", "value"],
+ },
+ },
+ resources: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ resource: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ control: {
+ type: "string",
+ enum: ["system", "graphql"],
+ },
+ method: {
+ anyOf: [
+ {
+ type: "string",
+ const: "get",
+ },
+ {
+ type: "string",
+ const: "post",
+ },
+ {
+ type: "string",
+ const: "put",
+ },
+ {
+ type: "string",
+ const: "delete",
+ },
+ ],
+ },
+ url: {
+ type: "string",
+ },
+ searchParams: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ value: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ '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"],
+ },
+ },
+ headers: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ value: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ '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"],
+ },
+ },
+ body: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ '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"],
+ },
+ 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"],
+ },
+ },
+ structure: {
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "fragment",
+ },
+ fragment: {
+ type: "object",
+ properties: {
+ children: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "id",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "text",
+ },
+ value: {
+ type: "string",
+ },
+ placeholder: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "expression",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ },
+ instances: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "instance",
+ },
+ id: {
+ type: "string",
+ },
+ component: {
+ type: "string",
+ minLength: 1,
+ },
+ tag: {
+ type: "string",
+ minLength: 1,
+ description:
+ "Optional HTML tag override for component rendering. Omit for component defaults; never pass an empty string.",
+ },
+ label: {
+ type: "string",
+ },
+ children: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "id",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "text",
+ },
+ value: {
+ type: "string",
+ },
+ placeholder: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "expression",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ },
+ },
+ required: ["type", "id", "component", "children"],
+ },
+ },
+ assets: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ size: {
+ type: "number",
+ },
+ name: {
+ type: "string",
+ },
+ filename: {
+ type: "string",
+ },
+ description: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ createdAt: {
+ type: "string",
+ },
+ format: {
+ anyOf: [
+ {
+ type: "string",
+ const: "ttf",
+ },
+ {
+ type: "string",
+ const: "woff",
+ },
+ {
+ type: "string",
+ const: "woff2",
+ },
+ ],
+ },
+ meta: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ family: {
+ type: "string",
+ },
+ style: {
+ type: "string",
+ enum: ["normal", "italic", "oblique"],
+ },
+ weight: {
+ type: "number",
+ },
+ },
+ required: ["family", "style", "weight"],
+ },
+ {
+ type: "object",
+ properties: {
+ family: {
+ type: "string",
+ },
+ variationAxes: {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ enum: [
+ "wght",
+ "wdth",
+ "slnt",
+ "opsz",
+ "ital",
+ "GRAD",
+ "XTRA",
+ "XOPQ",
+ "YOPQ",
+ "YTLC",
+ "YTUC",
+ "YTAS",
+ "YTDE",
+ "YTFI",
+ ],
+ },
+ additionalProperties: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ min: {
+ type: "number",
+ },
+ default: {
+ type: "number",
+ },
+ max: {
+ type: "number",
+ },
+ },
+ required: [
+ "name",
+ "min",
+ "default",
+ "max",
+ ],
+ },
+ },
+ },
+ required: ["family", "variationAxes"],
+ },
+ ],
+ },
+ type: {
+ type: "string",
+ const: "font",
+ },
+ },
+ required: [
+ "id",
+ "size",
+ "name",
+ "createdAt",
+ "format",
+ "meta",
+ "type",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ size: {
+ type: "number",
+ },
+ name: {
+ type: "string",
+ },
+ filename: {
+ type: "string",
+ },
+ description: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ createdAt: {
+ type: "string",
+ },
+ format: {
+ type: "string",
+ },
+ meta: {
+ type: "object",
+ properties: {
+ width: {
+ type: "number",
+ },
+ height: {
+ type: "number",
+ },
+ },
+ required: ["width", "height"],
+ },
+ type: {
+ type: "string",
+ const: "image",
+ },
+ },
+ required: [
+ "id",
+ "size",
+ "name",
+ "createdAt",
+ "format",
+ "meta",
+ "type",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ size: {
+ type: "number",
+ },
+ name: {
+ type: "string",
+ },
+ filename: {
+ type: "string",
+ },
+ description: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ createdAt: {
+ type: "string",
+ },
+ format: {
+ type: "string",
+ },
+ meta: {
+ type: "object",
+ properties: {},
+ required: [],
+ additionalProperties: true,
+ },
+ type: {
+ type: "string",
+ const: "file",
+ },
+ },
+ required: [
+ "id",
+ "size",
+ "name",
+ "createdAt",
+ "format",
+ "meta",
+ "type",
+ ],
+ },
+ ],
+ },
+ },
+ dataSources: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "variable",
+ },
+ id: {
+ type: "string",
+ },
+ scopeInstanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ value: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "number",
+ },
+ value: {
+ type: "number",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "string",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "boolean",
+ },
+ value: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "string[]",
+ },
+ value: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "json",
+ },
+ value: {},
+ },
+ required: ["type"],
+ },
+ ],
+ },
+ },
+ required: ["type", "id", "name", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "parameter",
+ },
+ id: {
+ type: "string",
+ },
+ scopeInstanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ },
+ required: ["type", "id", "name"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "resource",
+ },
+ id: {
+ type: "string",
+ },
+ scopeInstanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ resourceId: {
+ type: "string",
+ },
+ },
+ required: ["type", "id", "name", "resourceId"],
+ },
+ ],
+ },
+ },
+ resources: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ control: {
+ anyOf: [
+ {
+ type: "string",
+ const: "system",
+ },
+ {
+ type: "string",
+ const: "graphql",
+ },
+ ],
+ },
+ method: {
+ anyOf: [
+ {
+ type: "string",
+ const: "get",
+ },
+ {
+ type: "string",
+ const: "post",
+ },
+ {
+ type: "string",
+ const: "put",
+ },
+ {
+ type: "string",
+ const: "delete",
+ },
+ ],
+ },
+ url: {
+ type: "string",
+ },
+ searchParams: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["name", "value"],
+ },
+ },
+ headers: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["name", "value"],
+ },
+ },
+ body: {
+ type: "string",
+ },
+ },
+ required: ["id", "name", "method", "url", "headers"],
+ },
+ },
+ props: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "number",
+ },
+ value: {
+ type: "number",
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "string",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "boolean",
+ },
+ value: {
+ type: "boolean",
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "json",
+ },
+ value: {},
+ },
+ required: ["id", "instanceId", "name", "type"],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "asset",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "page",
+ },
+ value: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ },
+ required: ["pageId", "instanceId"],
+ },
+ ],
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "string[]",
+ },
+ value: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "parameter",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "resource",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "expression",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "action",
+ },
+ value: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "execute",
+ },
+ args: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ code: {
+ type: "string",
+ },
+ },
+ required: ["type", "args", "code"],
+ },
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "animationAction",
+ },
+ value: {
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "scroll",
+ },
+ source: {
+ anyOf: [
+ {
+ type: "string",
+ const: "closest",
+ },
+ {
+ type: "string",
+ const: "nearest",
+ },
+ {
+ type: "string",
+ const: "root",
+ },
+ ],
+ },
+ axis: {
+ anyOf: [
+ {
+ type: "string",
+ const: "block",
+ },
+ {
+ type: "string",
+ const: "inline",
+ },
+ {
+ type: "string",
+ const: "x",
+ },
+ {
+ type: "string",
+ const: "y",
+ },
+ ],
+ },
+ animations: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ description: {
+ type: "string",
+ },
+ enabled: {
+ type: "array",
+ items: {
+ type: "array",
+ prefixItems: [
+ {
+ type: "string",
+ description: "breakpointId",
+ },
+ {
+ type: "boolean",
+ },
+ ],
+ minItems: 2,
+ maxItems: 2,
+ },
+ },
+ keyframes: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ offset: {
+ type: "number",
+ },
+ styles: {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ },
+ additionalProperties: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ },
+ required: ["styles"],
+ },
+ },
+ timing: {
+ type: "object",
+ properties: {
+ easing: {
+ type: "string",
+ },
+ fill: {
+ anyOf: [
+ {
+ type: "string",
+ const: "none",
+ },
+ {
+ type: "string",
+ const: "forwards",
+ },
+ {
+ type: "string",
+ const: "backwards",
+ },
+ {
+ type: "string",
+ const: "both",
+ },
+ ],
+ },
+ duration: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "ms",
+ },
+ {
+ type: "string",
+ const: "s",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ delay: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "ms",
+ },
+ {
+ type: "string",
+ const: "s",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ iterations: {
+ anyOf: [
+ {
+ type: "number",
+ },
+ {
+ type: "string",
+ const: "infinite",
+ },
+ ],
+ },
+ rangeStart: {
+ type: "array",
+ prefixItems: [
+ {
+ anyOf: [
+ {
+ type: "string",
+ const: "start",
+ },
+ {
+ type: "string",
+ const: "end",
+ },
+ ],
+ },
+ {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "%",
+ },
+ {
+ type: "string",
+ const: "px",
+ },
+ {
+ type: "string",
+ const: "cm",
+ },
+ {
+ type: "string",
+ const: "mm",
+ },
+ {
+ type: "string",
+ const: "q",
+ },
+ {
+ type: "string",
+ const: "in",
+ },
+ {
+ type: "string",
+ const: "pt",
+ },
+ {
+ type: "string",
+ const: "pc",
+ },
+ {
+ type: "string",
+ const: "em",
+ },
+ {
+ type: "string",
+ const: "rem",
+ },
+ {
+ type: "string",
+ const: "ex",
+ },
+ {
+ type: "string",
+ const: "rex",
+ },
+ {
+ type: "string",
+ const: "cap",
+ },
+ {
+ type: "string",
+ const: "rcap",
+ },
+ {
+ type: "string",
+ const: "ch",
+ },
+ {
+ type: "string",
+ const: "rch",
+ },
+ {
+ type: "string",
+ const: "lh",
+ },
+ {
+ type: "string",
+ const: "rlh",
+ },
+ {
+ type: "string",
+ const: "vw",
+ },
+ {
+ type: "string",
+ const: "svw",
+ },
+ {
+ type: "string",
+ const: "lvw",
+ },
+ {
+ type: "string",
+ const: "dvw",
+ },
+ {
+ type: "string",
+ const: "vh",
+ },
+ {
+ type: "string",
+ const: "svh",
+ },
+ {
+ type: "string",
+ const: "lvh",
+ },
+ {
+ type: "string",
+ const: "dvh",
+ },
+ {
+ type: "string",
+ const: "vi",
+ },
+ {
+ type: "string",
+ const: "svi",
+ },
+ {
+ type: "string",
+ const: "lvi",
+ },
+ {
+ type: "string",
+ const: "dvi",
+ },
+ {
+ type: "string",
+ const: "vb",
+ },
+ {
+ type: "string",
+ const: "svb",
+ },
+ {
+ type: "string",
+ const: "lvb",
+ },
+ {
+ type: "string",
+ const: "dvb",
+ },
+ {
+ type: "string",
+ const: "vmin",
+ },
+ {
+ type: "string",
+ const:
+ "svmin",
+ },
+ {
+ type: "string",
+ const:
+ "lvmin",
+ },
+ {
+ type: "string",
+ const:
+ "dvmin",
+ },
+ {
+ type: "string",
+ const: "vmax",
+ },
+ {
+ type: "string",
+ const:
+ "svmax",
+ },
+ {
+ type: "string",
+ const:
+ "lvmax",
+ },
+ {
+ type: "string",
+ const:
+ "dvmax",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ ],
+ minItems: 2,
+ maxItems: 2,
+ },
+ rangeEnd: {
+ type: "array",
+ prefixItems: [
+ {
+ anyOf: [
+ {
+ type: "string",
+ const: "start",
+ },
+ {
+ type: "string",
+ const: "end",
+ },
+ ],
+ },
+ {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "%",
+ },
+ {
+ type: "string",
+ const: "px",
+ },
+ {
+ type: "string",
+ const: "cm",
+ },
+ {
+ type: "string",
+ const: "mm",
+ },
+ {
+ type: "string",
+ const: "q",
+ },
+ {
+ type: "string",
+ const: "in",
+ },
+ {
+ type: "string",
+ const: "pt",
+ },
+ {
+ type: "string",
+ const: "pc",
+ },
+ {
+ type: "string",
+ const: "em",
+ },
+ {
+ type: "string",
+ const: "rem",
+ },
+ {
+ type: "string",
+ const: "ex",
+ },
+ {
+ type: "string",
+ const: "rex",
+ },
+ {
+ type: "string",
+ const: "cap",
+ },
+ {
+ type: "string",
+ const: "rcap",
+ },
+ {
+ type: "string",
+ const: "ch",
+ },
+ {
+ type: "string",
+ const: "rch",
+ },
+ {
+ type: "string",
+ const: "lh",
+ },
+ {
+ type: "string",
+ const: "rlh",
+ },
+ {
+ type: "string",
+ const: "vw",
+ },
+ {
+ type: "string",
+ const: "svw",
+ },
+ {
+ type: "string",
+ const: "lvw",
+ },
+ {
+ type: "string",
+ const: "dvw",
+ },
+ {
+ type: "string",
+ const: "vh",
+ },
+ {
+ type: "string",
+ const: "svh",
+ },
+ {
+ type: "string",
+ const: "lvh",
+ },
+ {
+ type: "string",
+ const: "dvh",
+ },
+ {
+ type: "string",
+ const: "vi",
+ },
+ {
+ type: "string",
+ const: "svi",
+ },
+ {
+ type: "string",
+ const: "lvi",
+ },
+ {
+ type: "string",
+ const: "dvi",
+ },
+ {
+ type: "string",
+ const: "vb",
+ },
+ {
+ type: "string",
+ const: "svb",
+ },
+ {
+ type: "string",
+ const: "lvb",
+ },
+ {
+ type: "string",
+ const: "dvb",
+ },
+ {
+ type: "string",
+ const: "vmin",
+ },
+ {
+ type: "string",
+ const:
+ "svmin",
+ },
+ {
+ type: "string",
+ const:
+ "lvmin",
+ },
+ {
+ type: "string",
+ const:
+ "dvmin",
+ },
+ {
+ type: "string",
+ const: "vmax",
+ },
+ {
+ type: "string",
+ const:
+ "svmax",
+ },
+ {
+ type: "string",
+ const:
+ "lvmax",
+ },
+ {
+ type: "string",
+ const:
+ "dvmax",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ ],
+ minItems: 2,
+ maxItems: 2,
+ },
+ },
+ required: [],
+ },
+ },
+ required: ["keyframes", "timing"],
+ },
+ },
+ isPinned: {
+ type: "boolean",
+ },
+ debug: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "animations"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "view",
+ },
+ subject: {
+ type: "string",
+ },
+ axis: {
+ anyOf: [
+ {
+ type: "string",
+ const: "block",
+ },
+ {
+ type: "string",
+ const: "inline",
+ },
+ {
+ type: "string",
+ const: "x",
+ },
+ {
+ type: "string",
+ const: "y",
+ },
+ ],
+ },
+ animations: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ description: {
+ type: "string",
+ },
+ enabled: {
+ type: "array",
+ items: {
+ type: "array",
+ prefixItems: [
+ {
+ type: "string",
+ description: "breakpointId",
+ },
+ {
+ type: "boolean",
+ },
+ ],
+ minItems: 2,
+ maxItems: 2,
+ },
+ },
+ keyframes: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ offset: {
+ type: "number",
+ },
+ styles: {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ },
+ additionalProperties: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ },
+ required: ["styles"],
+ },
+ },
+ timing: {
+ type: "object",
+ properties: {
+ easing: {
+ type: "string",
+ },
+ fill: {
+ anyOf: [
+ {
+ type: "string",
+ const: "none",
+ },
+ {
+ type: "string",
+ const: "forwards",
+ },
+ {
+ type: "string",
+ const: "backwards",
+ },
+ {
+ type: "string",
+ const: "both",
+ },
+ ],
+ },
+ duration: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "ms",
+ },
+ {
+ type: "string",
+ const: "s",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ delay: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "ms",
+ },
+ {
+ type: "string",
+ const: "s",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ iterations: {
+ anyOf: [
+ {
+ type: "number",
+ },
+ {
+ type: "string",
+ const: "infinite",
+ },
+ ],
+ },
+ rangeStart: {
+ type: "array",
+ prefixItems: [
+ {
+ anyOf: [
+ {
+ type: "string",
+ const: "contain",
+ },
+ {
+ type: "string",
+ const: "cover",
+ },
+ {
+ type: "string",
+ const: "entry",
+ },
+ {
+ type: "string",
+ const: "exit",
+ },
+ {
+ type: "string",
+ const:
+ "entry-crossing",
+ },
+ {
+ type: "string",
+ const:
+ "exit-crossing",
+ },
+ ],
+ },
+ {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "%",
+ },
+ {
+ type: "string",
+ const: "px",
+ },
+ {
+ type: "string",
+ const: "cm",
+ },
+ {
+ type: "string",
+ const: "mm",
+ },
+ {
+ type: "string",
+ const: "q",
+ },
+ {
+ type: "string",
+ const: "in",
+ },
+ {
+ type: "string",
+ const: "pt",
+ },
+ {
+ type: "string",
+ const: "pc",
+ },
+ {
+ type: "string",
+ const: "em",
+ },
+ {
+ type: "string",
+ const: "rem",
+ },
+ {
+ type: "string",
+ const: "ex",
+ },
+ {
+ type: "string",
+ const: "rex",
+ },
+ {
+ type: "string",
+ const: "cap",
+ },
+ {
+ type: "string",
+ const: "rcap",
+ },
+ {
+ type: "string",
+ const: "ch",
+ },
+ {
+ type: "string",
+ const: "rch",
+ },
+ {
+ type: "string",
+ const: "lh",
+ },
+ {
+ type: "string",
+ const: "rlh",
+ },
+ {
+ type: "string",
+ const: "vw",
+ },
+ {
+ type: "string",
+ const: "svw",
+ },
+ {
+ type: "string",
+ const: "lvw",
+ },
+ {
+ type: "string",
+ const: "dvw",
+ },
+ {
+ type: "string",
+ const: "vh",
+ },
+ {
+ type: "string",
+ const: "svh",
+ },
+ {
+ type: "string",
+ const: "lvh",
+ },
+ {
+ type: "string",
+ const: "dvh",
+ },
+ {
+ type: "string",
+ const: "vi",
+ },
+ {
+ type: "string",
+ const: "svi",
+ },
+ {
+ type: "string",
+ const: "lvi",
+ },
+ {
+ type: "string",
+ const: "dvi",
+ },
+ {
+ type: "string",
+ const: "vb",
+ },
+ {
+ type: "string",
+ const: "svb",
+ },
+ {
+ type: "string",
+ const: "lvb",
+ },
+ {
+ type: "string",
+ const: "dvb",
+ },
+ {
+ type: "string",
+ const: "vmin",
+ },
+ {
+ type: "string",
+ const:
+ "svmin",
+ },
+ {
+ type: "string",
+ const:
+ "lvmin",
+ },
+ {
+ type: "string",
+ const:
+ "dvmin",
+ },
+ {
+ type: "string",
+ const: "vmax",
+ },
+ {
+ type: "string",
+ const:
+ "svmax",
+ },
+ {
+ type: "string",
+ const:
+ "lvmax",
+ },
+ {
+ type: "string",
+ const:
+ "dvmax",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ ],
+ minItems: 2,
+ maxItems: 2,
+ },
+ rangeEnd: {
+ type: "array",
+ prefixItems: [
+ {
+ anyOf: [
+ {
+ type: "string",
+ const: "contain",
+ },
+ {
+ type: "string",
+ const: "cover",
+ },
+ {
+ type: "string",
+ const: "entry",
+ },
+ {
+ type: "string",
+ const: "exit",
+ },
+ {
+ type: "string",
+ const:
+ "entry-crossing",
+ },
+ {
+ type: "string",
+ const:
+ "exit-crossing",
+ },
+ ],
+ },
+ {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "%",
+ },
+ {
+ type: "string",
+ const: "px",
+ },
+ {
+ type: "string",
+ const: "cm",
+ },
+ {
+ type: "string",
+ const: "mm",
+ },
+ {
+ type: "string",
+ const: "q",
+ },
+ {
+ type: "string",
+ const: "in",
+ },
+ {
+ type: "string",
+ const: "pt",
+ },
+ {
+ type: "string",
+ const: "pc",
+ },
+ {
+ type: "string",
+ const: "em",
+ },
+ {
+ type: "string",
+ const: "rem",
+ },
+ {
+ type: "string",
+ const: "ex",
+ },
+ {
+ type: "string",
+ const: "rex",
+ },
+ {
+ type: "string",
+ const: "cap",
+ },
+ {
+ type: "string",
+ const: "rcap",
+ },
+ {
+ type: "string",
+ const: "ch",
+ },
+ {
+ type: "string",
+ const: "rch",
+ },
+ {
+ type: "string",
+ const: "lh",
+ },
+ {
+ type: "string",
+ const: "rlh",
+ },
+ {
+ type: "string",
+ const: "vw",
+ },
+ {
+ type: "string",
+ const: "svw",
+ },
+ {
+ type: "string",
+ const: "lvw",
+ },
+ {
+ type: "string",
+ const: "dvw",
+ },
+ {
+ type: "string",
+ const: "vh",
+ },
+ {
+ type: "string",
+ const: "svh",
+ },
+ {
+ type: "string",
+ const: "lvh",
+ },
+ {
+ type: "string",
+ const: "dvh",
+ },
+ {
+ type: "string",
+ const: "vi",
+ },
+ {
+ type: "string",
+ const: "svi",
+ },
+ {
+ type: "string",
+ const: "lvi",
+ },
+ {
+ type: "string",
+ const: "dvi",
+ },
+ {
+ type: "string",
+ const: "vb",
+ },
+ {
+ type: "string",
+ const: "svb",
+ },
+ {
+ type: "string",
+ const: "lvb",
+ },
+ {
+ type: "string",
+ const: "dvb",
+ },
+ {
+ type: "string",
+ const: "vmin",
+ },
+ {
+ type: "string",
+ const:
+ "svmin",
+ },
+ {
+ type: "string",
+ const:
+ "lvmin",
+ },
+ {
+ type: "string",
+ const:
+ "dvmin",
+ },
+ {
+ type: "string",
+ const: "vmax",
+ },
+ {
+ type: "string",
+ const:
+ "svmax",
+ },
+ {
+ type: "string",
+ const:
+ "lvmax",
+ },
+ {
+ type: "string",
+ const:
+ "dvmax",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ ],
+ minItems: 2,
+ maxItems: 2,
+ },
+ },
+ required: [],
+ },
+ },
+ required: ["keyframes", "timing"],
+ },
+ },
+ insetStart: {
+ anyOf: [
+ {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "%",
+ },
+ {
+ type: "string",
+ const: "px",
+ },
+ {
+ type: "string",
+ const: "cm",
+ },
+ {
+ type: "string",
+ const: "mm",
+ },
+ {
+ type: "string",
+ const: "q",
+ },
+ {
+ type: "string",
+ const: "in",
+ },
+ {
+ type: "string",
+ const: "pt",
+ },
+ {
+ type: "string",
+ const: "pc",
+ },
+ {
+ type: "string",
+ const: "em",
+ },
+ {
+ type: "string",
+ const: "rem",
+ },
+ {
+ type: "string",
+ const: "ex",
+ },
+ {
+ type: "string",
+ const: "rex",
+ },
+ {
+ type: "string",
+ const: "cap",
+ },
+ {
+ type: "string",
+ const: "rcap",
+ },
+ {
+ type: "string",
+ const: "ch",
+ },
+ {
+ type: "string",
+ const: "rch",
+ },
+ {
+ type: "string",
+ const: "lh",
+ },
+ {
+ type: "string",
+ const: "rlh",
+ },
+ {
+ type: "string",
+ const: "vw",
+ },
+ {
+ type: "string",
+ const: "svw",
+ },
+ {
+ type: "string",
+ const: "lvw",
+ },
+ {
+ type: "string",
+ const: "dvw",
+ },
+ {
+ type: "string",
+ const: "vh",
+ },
+ {
+ type: "string",
+ const: "svh",
+ },
+ {
+ type: "string",
+ const: "lvh",
+ },
+ {
+ type: "string",
+ const: "dvh",
+ },
+ {
+ type: "string",
+ const: "vi",
+ },
+ {
+ type: "string",
+ const: "svi",
+ },
+ {
+ type: "string",
+ const: "lvi",
+ },
+ {
+ type: "string",
+ const: "dvi",
+ },
+ {
+ type: "string",
+ const: "vb",
+ },
+ {
+ type: "string",
+ const: "svb",
+ },
+ {
+ type: "string",
+ const: "lvb",
+ },
+ {
+ type: "string",
+ const: "dvb",
+ },
+ {
+ type: "string",
+ const: "vmin",
+ },
+ {
+ type: "string",
+ const: "svmin",
+ },
+ {
+ type: "string",
+ const: "lvmin",
+ },
+ {
+ type: "string",
+ const: "dvmin",
+ },
+ {
+ type: "string",
+ const: "vmax",
+ },
+ {
+ type: "string",
+ const: "svmax",
+ },
+ {
+ type: "string",
+ const: "lvmax",
+ },
+ {
+ type: "string",
+ const: "dvmax",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ const: "auto",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ insetEnd: {
+ anyOf: [
+ {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "%",
+ },
+ {
+ type: "string",
+ const: "px",
+ },
+ {
+ type: "string",
+ const: "cm",
+ },
+ {
+ type: "string",
+ const: "mm",
+ },
+ {
+ type: "string",
+ const: "q",
+ },
+ {
+ type: "string",
+ const: "in",
+ },
+ {
+ type: "string",
+ const: "pt",
+ },
+ {
+ type: "string",
+ const: "pc",
+ },
+ {
+ type: "string",
+ const: "em",
+ },
+ {
+ type: "string",
+ const: "rem",
+ },
+ {
+ type: "string",
+ const: "ex",
+ },
+ {
+ type: "string",
+ const: "rex",
+ },
+ {
+ type: "string",
+ const: "cap",
+ },
+ {
+ type: "string",
+ const: "rcap",
+ },
+ {
+ type: "string",
+ const: "ch",
+ },
+ {
+ type: "string",
+ const: "rch",
+ },
+ {
+ type: "string",
+ const: "lh",
+ },
+ {
+ type: "string",
+ const: "rlh",
+ },
+ {
+ type: "string",
+ const: "vw",
+ },
+ {
+ type: "string",
+ const: "svw",
+ },
+ {
+ type: "string",
+ const: "lvw",
+ },
+ {
+ type: "string",
+ const: "dvw",
+ },
+ {
+ type: "string",
+ const: "vh",
+ },
+ {
+ type: "string",
+ const: "svh",
+ },
+ {
+ type: "string",
+ const: "lvh",
+ },
+ {
+ type: "string",
+ const: "dvh",
+ },
+ {
+ type: "string",
+ const: "vi",
+ },
+ {
+ type: "string",
+ const: "svi",
+ },
+ {
+ type: "string",
+ const: "lvi",
+ },
+ {
+ type: "string",
+ const: "dvi",
+ },
+ {
+ type: "string",
+ const: "vb",
+ },
+ {
+ type: "string",
+ const: "svb",
+ },
+ {
+ type: "string",
+ const: "lvb",
+ },
+ {
+ type: "string",
+ const: "dvb",
+ },
+ {
+ type: "string",
+ const: "vmin",
+ },
+ {
+ type: "string",
+ const: "svmin",
+ },
+ {
+ type: "string",
+ const: "lvmin",
+ },
+ {
+ type: "string",
+ const: "dvmin",
+ },
+ {
+ type: "string",
+ const: "vmax",
+ },
+ {
+ type: "string",
+ const: "svmax",
+ },
+ {
+ type: "string",
+ const: "lvmax",
+ },
+ {
+ type: "string",
+ const: "dvmax",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ const: "auto",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ isPinned: {
+ type: "boolean",
+ },
+ debug: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "animations"],
+ },
+ ],
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ },
+ breakpoints: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ label: {
+ type: "string",
+ },
+ minWidth: {
+ type: "number",
+ },
+ maxWidth: {
+ type: "number",
+ },
+ condition: {
+ type: "string",
+ },
+ },
+ required: ["id", "label"],
+ },
+ },
+ styleSourceSelections: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ instanceId: {
+ type: "string",
+ },
+ values: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ },
+ required: ["instanceId", "values"],
+ },
+ },
+ styleSources: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "token",
+ },
+ id: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ locked: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "id", "name"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "local",
+ },
+ id: {
+ type: "string",
+ },
+ },
+ required: ["type", "id"],
+ },
+ ],
+ },
+ },
+ styles: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ styleSourceId: {
+ type: "string",
+ },
+ breakpointId: {
+ type: "string",
+ },
+ state: {
+ type: "string",
+ },
+ property: {
+ type: "string",
+ },
+ value: {
+ $ref: "#/$defs/__schema0",
+ },
+ listed: {
+ description:
+ "Whether the style is from the Advanced panel",
+ type: "boolean",
+ },
+ },
+ required: [
+ "styleSourceId",
+ "breakpointId",
+ "property",
+ "value",
+ ],
+ },
+ },
+ },
+ required: [
+ "children",
+ "instances",
+ "assets",
+ "dataSources",
+ "resources",
+ "props",
+ "breakpoints",
+ "styleSourceSelections",
+ "styleSources",
+ "styles",
+ ],
+ description:
+ "Structured Webstudio fragment produced by Webstudio JSX/template helpers. Runtime remaps fragment ids to generated project ids.",
+ },
+ conflictResolution: {
+ type: "string",
+ enum: ["ours", "theirs", "merge"],
+ },
+ contentMode: {
+ type: "boolean",
+ },
+ mode: {
+ type: "string",
+ enum: ["append", "prepend", "replace"],
+ },
+ insertIndex: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["type", "fragment"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "collection",
+ },
+ data: {
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "json",
+ },
+ value: {
+ anyOf: [
+ {
+ type: "array",
+ items: {},
+ },
+ {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ },
+ additionalProperties: {},
+ },
+ ],
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "expression",
+ },
+ value: {
+ type: "string",
+ minLength: 1,
+ description:
+ 'Expression resolving to the complete array or object, for example "Posts.data.items".',
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ "Complete iterable for the Collection. Do not pass one indexed item.",
+ },
+ itemFragment: {
+ type: "object",
+ properties: {
+ children: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "id",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "text",
+ },
+ value: {
+ type: "string",
+ },
+ placeholder: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "expression",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ },
+ instances: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "instance",
+ },
+ id: {
+ type: "string",
+ },
+ component: {
+ type: "string",
+ minLength: 1,
+ },
+ tag: {
+ type: "string",
+ minLength: 1,
+ description:
+ "Optional HTML tag override for component rendering. Omit for component defaults; never pass an empty string.",
+ },
+ label: {
+ type: "string",
+ },
+ children: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "id",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "text",
+ },
+ value: {
+ type: "string",
+ },
+ placeholder: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "expression",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ },
+ },
+ required: ["type", "id", "component", "children"],
+ },
+ },
+ assets: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ size: {
+ type: "number",
+ },
+ name: {
+ type: "string",
+ },
+ filename: {
+ type: "string",
+ },
+ description: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ createdAt: {
+ type: "string",
+ },
+ format: {
+ anyOf: [
+ {
+ type: "string",
+ const: "ttf",
+ },
+ {
+ type: "string",
+ const: "woff",
+ },
+ {
+ type: "string",
+ const: "woff2",
+ },
+ ],
+ },
+ meta: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ family: {
+ type: "string",
+ },
+ style: {
+ type: "string",
+ enum: ["normal", "italic", "oblique"],
+ },
+ weight: {
+ type: "number",
+ },
+ },
+ required: ["family", "style", "weight"],
+ },
+ {
+ type: "object",
+ properties: {
+ family: {
+ type: "string",
+ },
+ variationAxes: {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ enum: [
+ "wght",
+ "wdth",
+ "slnt",
+ "opsz",
+ "ital",
+ "GRAD",
+ "XTRA",
+ "XOPQ",
+ "YOPQ",
+ "YTLC",
+ "YTUC",
+ "YTAS",
+ "YTDE",
+ "YTFI",
+ ],
+ },
+ additionalProperties: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ min: {
+ type: "number",
+ },
+ default: {
+ type: "number",
+ },
+ max: {
+ type: "number",
+ },
+ },
+ required: [
+ "name",
+ "min",
+ "default",
+ "max",
+ ],
+ },
+ },
+ },
+ required: ["family", "variationAxes"],
+ },
+ ],
+ },
+ type: {
+ type: "string",
+ const: "font",
+ },
+ },
+ required: [
+ "id",
+ "size",
+ "name",
+ "createdAt",
+ "format",
+ "meta",
+ "type",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ size: {
+ type: "number",
+ },
+ name: {
+ type: "string",
+ },
+ filename: {
+ type: "string",
+ },
+ description: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ createdAt: {
+ type: "string",
+ },
+ format: {
+ type: "string",
+ },
+ meta: {
+ type: "object",
+ properties: {
+ width: {
+ type: "number",
+ },
+ height: {
+ type: "number",
+ },
+ },
+ required: ["width", "height"],
+ },
+ type: {
+ type: "string",
+ const: "image",
+ },
+ },
+ required: [
+ "id",
+ "size",
+ "name",
+ "createdAt",
+ "format",
+ "meta",
+ "type",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ size: {
+ type: "number",
+ },
+ name: {
+ type: "string",
+ },
+ filename: {
+ type: "string",
+ },
+ description: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ createdAt: {
+ type: "string",
+ },
+ format: {
+ type: "string",
+ },
+ meta: {
+ type: "object",
+ properties: {},
+ required: [],
+ additionalProperties: true,
+ },
+ type: {
+ type: "string",
+ const: "file",
+ },
+ },
+ required: [
+ "id",
+ "size",
+ "name",
+ "createdAt",
+ "format",
+ "meta",
+ "type",
+ ],
+ },
+ ],
+ },
+ },
+ dataSources: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "variable",
+ },
+ id: {
+ type: "string",
+ },
+ scopeInstanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ value: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "number",
+ },
+ value: {
+ type: "number",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "string",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "boolean",
+ },
+ value: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "string[]",
+ },
+ value: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "json",
+ },
+ value: {},
+ },
+ required: ["type"],
+ },
+ ],
+ },
+ },
+ required: ["type", "id", "name", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "parameter",
+ },
+ id: {
+ type: "string",
+ },
+ scopeInstanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ },
+ required: ["type", "id", "name"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "resource",
+ },
+ id: {
+ type: "string",
+ },
+ scopeInstanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ resourceId: {
+ type: "string",
+ },
+ },
+ required: ["type", "id", "name", "resourceId"],
+ },
+ ],
+ },
+ },
+ resources: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ control: {
+ anyOf: [
+ {
+ type: "string",
+ const: "system",
+ },
+ {
+ type: "string",
+ const: "graphql",
+ },
+ ],
+ },
+ method: {
+ anyOf: [
+ {
+ type: "string",
+ const: "get",
+ },
+ {
+ type: "string",
+ const: "post",
+ },
+ {
+ type: "string",
+ const: "put",
+ },
+ {
+ type: "string",
+ const: "delete",
+ },
+ ],
+ },
+ url: {
+ type: "string",
+ },
+ searchParams: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["name", "value"],
+ },
+ },
+ headers: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["name", "value"],
+ },
+ },
+ body: {
+ type: "string",
+ },
+ },
+ required: ["id", "name", "method", "url", "headers"],
+ },
+ },
+ props: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "number",
+ },
+ value: {
+ type: "number",
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "string",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "boolean",
+ },
+ value: {
+ type: "boolean",
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "json",
+ },
+ value: {},
+ },
+ required: ["id", "instanceId", "name", "type"],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "asset",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "page",
+ },
+ value: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ },
+ required: ["pageId", "instanceId"],
+ },
+ ],
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "string[]",
+ },
+ value: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "parameter",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "resource",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "expression",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "action",
+ },
+ value: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "execute",
+ },
+ args: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ code: {
+ type: "string",
+ },
+ },
+ required: ["type", "args", "code"],
+ },
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ required: {
+ type: "boolean",
+ },
+ type: {
+ type: "string",
+ const: "animationAction",
+ },
+ value: {
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "scroll",
+ },
+ source: {
+ anyOf: [
+ {
+ type: "string",
+ const: "closest",
+ },
+ {
+ type: "string",
+ const: "nearest",
+ },
+ {
+ type: "string",
+ const: "root",
+ },
+ ],
+ },
+ axis: {
+ anyOf: [
+ {
+ type: "string",
+ const: "block",
+ },
+ {
+ type: "string",
+ const: "inline",
+ },
+ {
+ type: "string",
+ const: "x",
+ },
+ {
+ type: "string",
+ const: "y",
+ },
+ ],
+ },
+ animations: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ description: {
+ type: "string",
+ },
+ enabled: {
+ type: "array",
+ items: {
+ type: "array",
+ prefixItems: [
+ {
+ type: "string",
+ description: "breakpointId",
+ },
+ {
+ type: "boolean",
+ },
+ ],
+ minItems: 2,
+ maxItems: 2,
+ },
+ },
+ keyframes: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ offset: {
+ type: "number",
+ },
+ styles: {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ },
+ additionalProperties: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ },
+ required: ["styles"],
+ },
+ },
+ timing: {
+ type: "object",
+ properties: {
+ easing: {
+ type: "string",
+ },
+ fill: {
+ anyOf: [
+ {
+ type: "string",
+ const: "none",
+ },
+ {
+ type: "string",
+ const: "forwards",
+ },
+ {
+ type: "string",
+ const: "backwards",
+ },
+ {
+ type: "string",
+ const: "both",
+ },
+ ],
+ },
+ duration: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "ms",
+ },
+ {
+ type: "string",
+ const: "s",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ delay: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "ms",
+ },
+ {
+ type: "string",
+ const: "s",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ iterations: {
+ anyOf: [
+ {
+ type: "number",
+ },
+ {
+ type: "string",
+ const: "infinite",
+ },
+ ],
+ },
+ rangeStart: {
+ type: "array",
+ prefixItems: [
+ {
+ anyOf: [
+ {
+ type: "string",
+ const: "start",
+ },
+ {
+ type: "string",
+ const: "end",
+ },
+ ],
+ },
+ {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "%",
+ },
+ {
+ type: "string",
+ const: "px",
+ },
+ {
+ type: "string",
+ const: "cm",
+ },
+ {
+ type: "string",
+ const: "mm",
+ },
+ {
+ type: "string",
+ const: "q",
+ },
+ {
+ type: "string",
+ const: "in",
+ },
+ {
+ type: "string",
+ const: "pt",
+ },
+ {
+ type: "string",
+ const: "pc",
+ },
+ {
+ type: "string",
+ const: "em",
+ },
+ {
+ type: "string",
+ const: "rem",
+ },
+ {
+ type: "string",
+ const: "ex",
+ },
+ {
+ type: "string",
+ const: "rex",
+ },
+ {
+ type: "string",
+ const: "cap",
+ },
+ {
+ type: "string",
+ const: "rcap",
+ },
+ {
+ type: "string",
+ const: "ch",
+ },
+ {
+ type: "string",
+ const: "rch",
+ },
+ {
+ type: "string",
+ const: "lh",
+ },
+ {
+ type: "string",
+ const: "rlh",
+ },
+ {
+ type: "string",
+ const: "vw",
+ },
+ {
+ type: "string",
+ const: "svw",
+ },
+ {
+ type: "string",
+ const: "lvw",
+ },
+ {
+ type: "string",
+ const: "dvw",
+ },
+ {
+ type: "string",
+ const: "vh",
+ },
+ {
+ type: "string",
+ const: "svh",
+ },
+ {
+ type: "string",
+ const: "lvh",
+ },
+ {
+ type: "string",
+ const: "dvh",
+ },
+ {
+ type: "string",
+ const: "vi",
+ },
+ {
+ type: "string",
+ const: "svi",
+ },
+ {
+ type: "string",
+ const: "lvi",
+ },
+ {
+ type: "string",
+ const: "dvi",
+ },
+ {
+ type: "string",
+ const: "vb",
+ },
+ {
+ type: "string",
+ const: "svb",
+ },
+ {
+ type: "string",
+ const: "lvb",
+ },
+ {
+ type: "string",
+ const: "dvb",
+ },
+ {
+ type: "string",
+ const: "vmin",
+ },
+ {
+ type: "string",
+ const:
+ "svmin",
+ },
+ {
+ type: "string",
+ const:
+ "lvmin",
+ },
+ {
+ type: "string",
+ const:
+ "dvmin",
+ },
+ {
+ type: "string",
+ const: "vmax",
+ },
+ {
+ type: "string",
+ const:
+ "svmax",
+ },
+ {
+ type: "string",
+ const:
+ "lvmax",
+ },
+ {
+ type: "string",
+ const:
+ "dvmax",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ ],
+ minItems: 2,
+ maxItems: 2,
+ },
+ rangeEnd: {
+ type: "array",
+ prefixItems: [
+ {
+ anyOf: [
+ {
+ type: "string",
+ const: "start",
+ },
+ {
+ type: "string",
+ const: "end",
+ },
+ ],
+ },
+ {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "%",
+ },
+ {
+ type: "string",
+ const: "px",
+ },
+ {
+ type: "string",
+ const: "cm",
+ },
+ {
+ type: "string",
+ const: "mm",
+ },
+ {
+ type: "string",
+ const: "q",
+ },
+ {
+ type: "string",
+ const: "in",
+ },
+ {
+ type: "string",
+ const: "pt",
+ },
+ {
+ type: "string",
+ const: "pc",
+ },
+ {
+ type: "string",
+ const: "em",
+ },
+ {
+ type: "string",
+ const: "rem",
+ },
+ {
+ type: "string",
+ const: "ex",
+ },
+ {
+ type: "string",
+ const: "rex",
+ },
+ {
+ type: "string",
+ const: "cap",
+ },
+ {
+ type: "string",
+ const: "rcap",
+ },
+ {
+ type: "string",
+ const: "ch",
+ },
+ {
+ type: "string",
+ const: "rch",
+ },
+ {
+ type: "string",
+ const: "lh",
+ },
+ {
+ type: "string",
+ const: "rlh",
+ },
+ {
+ type: "string",
+ const: "vw",
+ },
+ {
+ type: "string",
+ const: "svw",
+ },
+ {
+ type: "string",
+ const: "lvw",
+ },
+ {
+ type: "string",
+ const: "dvw",
+ },
+ {
+ type: "string",
+ const: "vh",
+ },
+ {
+ type: "string",
+ const: "svh",
+ },
+ {
+ type: "string",
+ const: "lvh",
+ },
+ {
+ type: "string",
+ const: "dvh",
+ },
+ {
+ type: "string",
+ const: "vi",
+ },
+ {
+ type: "string",
+ const: "svi",
+ },
+ {
+ type: "string",
+ const: "lvi",
+ },
+ {
+ type: "string",
+ const: "dvi",
+ },
+ {
+ type: "string",
+ const: "vb",
+ },
+ {
+ type: "string",
+ const: "svb",
+ },
+ {
+ type: "string",
+ const: "lvb",
+ },
+ {
+ type: "string",
+ const: "dvb",
+ },
+ {
+ type: "string",
+ const: "vmin",
+ },
+ {
+ type: "string",
+ const:
+ "svmin",
+ },
+ {
+ type: "string",
+ const:
+ "lvmin",
+ },
+ {
+ type: "string",
+ const:
+ "dvmin",
+ },
+ {
+ type: "string",
+ const: "vmax",
+ },
+ {
+ type: "string",
+ const:
+ "svmax",
+ },
+ {
+ type: "string",
+ const:
+ "lvmax",
+ },
+ {
+ type: "string",
+ const:
+ "dvmax",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ ],
+ minItems: 2,
+ maxItems: 2,
+ },
+ },
+ required: [],
+ },
+ },
+ required: ["keyframes", "timing"],
+ },
+ },
+ isPinned: {
+ type: "boolean",
+ },
+ debug: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "animations"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "view",
+ },
+ subject: {
+ type: "string",
+ },
+ axis: {
+ anyOf: [
+ {
+ type: "string",
+ const: "block",
+ },
+ {
+ type: "string",
+ const: "inline",
+ },
+ {
+ type: "string",
+ const: "x",
+ },
+ {
+ type: "string",
+ const: "y",
+ },
+ ],
+ },
+ animations: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: {
+ type: "string",
+ },
+ description: {
+ type: "string",
+ },
+ enabled: {
+ type: "array",
+ items: {
+ type: "array",
+ prefixItems: [
+ {
+ type: "string",
+ description: "breakpointId",
+ },
+ {
+ type: "boolean",
+ },
+ ],
+ minItems: 2,
+ maxItems: 2,
+ },
+ },
+ keyframes: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ offset: {
+ type: "number",
+ },
+ styles: {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ },
+ additionalProperties: {
+ $ref: "#/$defs/__schema0",
+ },
+ },
+ },
+ required: ["styles"],
+ },
+ },
+ timing: {
+ type: "object",
+ properties: {
+ easing: {
+ type: "string",
+ },
+ fill: {
+ anyOf: [
+ {
+ type: "string",
+ const: "none",
+ },
+ {
+ type: "string",
+ const: "forwards",
+ },
+ {
+ type: "string",
+ const: "backwards",
+ },
+ {
+ type: "string",
+ const: "both",
+ },
+ ],
+ },
+ duration: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "ms",
+ },
+ {
+ type: "string",
+ const: "s",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ delay: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "ms",
+ },
+ {
+ type: "string",
+ const: "s",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ iterations: {
+ anyOf: [
+ {
+ type: "number",
+ },
+ {
+ type: "string",
+ const: "infinite",
+ },
+ ],
+ },
+ rangeStart: {
+ type: "array",
+ prefixItems: [
+ {
+ anyOf: [
+ {
+ type: "string",
+ const: "contain",
+ },
+ {
+ type: "string",
+ const: "cover",
+ },
+ {
+ type: "string",
+ const: "entry",
+ },
+ {
+ type: "string",
+ const: "exit",
+ },
+ {
+ type: "string",
+ const:
+ "entry-crossing",
+ },
+ {
+ type: "string",
+ const:
+ "exit-crossing",
+ },
+ ],
+ },
+ {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "%",
+ },
+ {
+ type: "string",
+ const: "px",
+ },
+ {
+ type: "string",
+ const: "cm",
+ },
+ {
+ type: "string",
+ const: "mm",
+ },
+ {
+ type: "string",
+ const: "q",
+ },
+ {
+ type: "string",
+ const: "in",
+ },
+ {
+ type: "string",
+ const: "pt",
+ },
+ {
+ type: "string",
+ const: "pc",
+ },
+ {
+ type: "string",
+ const: "em",
+ },
+ {
+ type: "string",
+ const: "rem",
+ },
+ {
+ type: "string",
+ const: "ex",
+ },
+ {
+ type: "string",
+ const: "rex",
+ },
+ {
+ type: "string",
+ const: "cap",
+ },
+ {
+ type: "string",
+ const: "rcap",
+ },
+ {
+ type: "string",
+ const: "ch",
+ },
+ {
+ type: "string",
+ const: "rch",
+ },
+ {
+ type: "string",
+ const: "lh",
+ },
+ {
+ type: "string",
+ const: "rlh",
+ },
+ {
+ type: "string",
+ const: "vw",
+ },
+ {
+ type: "string",
+ const: "svw",
+ },
+ {
+ type: "string",
+ const: "lvw",
+ },
+ {
+ type: "string",
+ const: "dvw",
+ },
+ {
+ type: "string",
+ const: "vh",
+ },
+ {
+ type: "string",
+ const: "svh",
+ },
+ {
+ type: "string",
+ const: "lvh",
+ },
+ {
+ type: "string",
+ const: "dvh",
+ },
+ {
+ type: "string",
+ const: "vi",
+ },
+ {
+ type: "string",
+ const: "svi",
+ },
+ {
+ type: "string",
+ const: "lvi",
+ },
+ {
+ type: "string",
+ const: "dvi",
+ },
+ {
+ type: "string",
+ const: "vb",
+ },
+ {
+ type: "string",
+ const: "svb",
+ },
+ {
+ type: "string",
+ const: "lvb",
+ },
+ {
+ type: "string",
+ const: "dvb",
+ },
+ {
+ type: "string",
+ const: "vmin",
+ },
+ {
+ type: "string",
+ const:
+ "svmin",
+ },
+ {
+ type: "string",
+ const:
+ "lvmin",
+ },
+ {
+ type: "string",
+ const:
+ "dvmin",
+ },
+ {
+ type: "string",
+ const: "vmax",
+ },
+ {
+ type: "string",
+ const:
+ "svmax",
+ },
+ {
+ type: "string",
+ const:
+ "lvmax",
+ },
+ {
+ type: "string",
+ const:
+ "dvmax",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ ],
+ minItems: 2,
+ maxItems: 2,
+ },
+ rangeEnd: {
+ type: "array",
+ prefixItems: [
+ {
+ anyOf: [
+ {
+ type: "string",
+ const: "contain",
+ },
+ {
+ type: "string",
+ const: "cover",
+ },
+ {
+ type: "string",
+ const: "entry",
+ },
+ {
+ type: "string",
+ const: "exit",
+ },
+ {
+ type: "string",
+ const:
+ "entry-crossing",
+ },
+ {
+ type: "string",
+ const:
+ "exit-crossing",
+ },
+ ],
+ },
+ {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "%",
+ },
+ {
+ type: "string",
+ const: "px",
+ },
+ {
+ type: "string",
+ const: "cm",
+ },
+ {
+ type: "string",
+ const: "mm",
+ },
+ {
+ type: "string",
+ const: "q",
+ },
+ {
+ type: "string",
+ const: "in",
+ },
+ {
+ type: "string",
+ const: "pt",
+ },
+ {
+ type: "string",
+ const: "pc",
+ },
+ {
+ type: "string",
+ const: "em",
+ },
+ {
+ type: "string",
+ const: "rem",
+ },
+ {
+ type: "string",
+ const: "ex",
+ },
+ {
+ type: "string",
+ const: "rex",
+ },
+ {
+ type: "string",
+ const: "cap",
+ },
+ {
+ type: "string",
+ const: "rcap",
+ },
+ {
+ type: "string",
+ const: "ch",
+ },
+ {
+ type: "string",
+ const: "rch",
+ },
+ {
+ type: "string",
+ const: "lh",
+ },
+ {
+ type: "string",
+ const: "rlh",
+ },
+ {
+ type: "string",
+ const: "vw",
+ },
+ {
+ type: "string",
+ const: "svw",
+ },
+ {
+ type: "string",
+ const: "lvw",
+ },
+ {
+ type: "string",
+ const: "dvw",
+ },
+ {
+ type: "string",
+ const: "vh",
+ },
+ {
+ type: "string",
+ const: "svh",
+ },
+ {
+ type: "string",
+ const: "lvh",
+ },
+ {
+ type: "string",
+ const: "dvh",
+ },
+ {
+ type: "string",
+ const: "vi",
+ },
+ {
+ type: "string",
+ const: "svi",
+ },
+ {
+ type: "string",
+ const: "lvi",
+ },
+ {
+ type: "string",
+ const: "dvi",
+ },
+ {
+ type: "string",
+ const: "vb",
+ },
+ {
+ type: "string",
+ const: "svb",
+ },
+ {
+ type: "string",
+ const: "lvb",
+ },
+ {
+ type: "string",
+ const: "dvb",
+ },
+ {
+ type: "string",
+ const: "vmin",
+ },
+ {
+ type: "string",
+ const:
+ "svmin",
+ },
+ {
+ type: "string",
+ const:
+ "lvmin",
+ },
+ {
+ type: "string",
+ const:
+ "dvmin",
+ },
+ {
+ type: "string",
+ const: "vmax",
+ },
+ {
+ type: "string",
+ const:
+ "svmax",
+ },
+ {
+ type: "string",
+ const:
+ "lvmax",
+ },
+ {
+ type: "string",
+ const:
+ "dvmax",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: [
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ ],
+ minItems: 2,
+ maxItems: 2,
+ },
+ },
+ required: [],
+ },
+ },
+ required: ["keyframes", "timing"],
+ },
+ },
+ insetStart: {
+ anyOf: [
+ {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "%",
+ },
+ {
+ type: "string",
+ const: "px",
+ },
+ {
+ type: "string",
+ const: "cm",
+ },
+ {
+ type: "string",
+ const: "mm",
+ },
+ {
+ type: "string",
+ const: "q",
+ },
+ {
+ type: "string",
+ const: "in",
+ },
+ {
+ type: "string",
+ const: "pt",
+ },
+ {
+ type: "string",
+ const: "pc",
+ },
+ {
+ type: "string",
+ const: "em",
+ },
+ {
+ type: "string",
+ const: "rem",
+ },
+ {
+ type: "string",
+ const: "ex",
+ },
+ {
+ type: "string",
+ const: "rex",
+ },
+ {
+ type: "string",
+ const: "cap",
+ },
+ {
+ type: "string",
+ const: "rcap",
+ },
+ {
+ type: "string",
+ const: "ch",
+ },
+ {
+ type: "string",
+ const: "rch",
+ },
+ {
+ type: "string",
+ const: "lh",
+ },
+ {
+ type: "string",
+ const: "rlh",
+ },
+ {
+ type: "string",
+ const: "vw",
+ },
+ {
+ type: "string",
+ const: "svw",
+ },
+ {
+ type: "string",
+ const: "lvw",
+ },
+ {
+ type: "string",
+ const: "dvw",
+ },
+ {
+ type: "string",
+ const: "vh",
+ },
+ {
+ type: "string",
+ const: "svh",
+ },
+ {
+ type: "string",
+ const: "lvh",
+ },
+ {
+ type: "string",
+ const: "dvh",
+ },
+ {
+ type: "string",
+ const: "vi",
+ },
+ {
+ type: "string",
+ const: "svi",
+ },
+ {
+ type: "string",
+ const: "lvi",
+ },
+ {
+ type: "string",
+ const: "dvi",
+ },
+ {
+ type: "string",
+ const: "vb",
+ },
+ {
+ type: "string",
+ const: "svb",
+ },
+ {
+ type: "string",
+ const: "lvb",
+ },
+ {
+ type: "string",
+ const: "dvb",
+ },
+ {
+ type: "string",
+ const: "vmin",
+ },
+ {
+ type: "string",
+ const: "svmin",
+ },
+ {
+ type: "string",
+ const: "lvmin",
+ },
+ {
+ type: "string",
+ const: "dvmin",
+ },
+ {
+ type: "string",
+ const: "vmax",
+ },
+ {
+ type: "string",
+ const: "svmax",
+ },
+ {
+ type: "string",
+ const: "lvmax",
+ },
+ {
+ type: "string",
+ const: "dvmax",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ const: "auto",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ insetEnd: {
+ anyOf: [
+ {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ value: {
+ type: "number",
+ },
+ unit: {
+ anyOf: [
+ {
+ type: "string",
+ const: "%",
+ },
+ {
+ type: "string",
+ const: "px",
+ },
+ {
+ type: "string",
+ const: "cm",
+ },
+ {
+ type: "string",
+ const: "mm",
+ },
+ {
+ type: "string",
+ const: "q",
+ },
+ {
+ type: "string",
+ const: "in",
+ },
+ {
+ type: "string",
+ const: "pt",
+ },
+ {
+ type: "string",
+ const: "pc",
+ },
+ {
+ type: "string",
+ const: "em",
+ },
+ {
+ type: "string",
+ const: "rem",
+ },
+ {
+ type: "string",
+ const: "ex",
+ },
+ {
+ type: "string",
+ const: "rex",
+ },
+ {
+ type: "string",
+ const: "cap",
+ },
+ {
+ type: "string",
+ const: "rcap",
+ },
+ {
+ type: "string",
+ const: "ch",
+ },
+ {
+ type: "string",
+ const: "rch",
+ },
+ {
+ type: "string",
+ const: "lh",
+ },
+ {
+ type: "string",
+ const: "rlh",
+ },
+ {
+ type: "string",
+ const: "vw",
+ },
+ {
+ type: "string",
+ const: "svw",
+ },
+ {
+ type: "string",
+ const: "lvw",
+ },
+ {
+ type: "string",
+ const: "dvw",
+ },
+ {
+ type: "string",
+ const: "vh",
+ },
+ {
+ type: "string",
+ const: "svh",
+ },
+ {
+ type: "string",
+ const: "lvh",
+ },
+ {
+ type: "string",
+ const: "dvh",
+ },
+ {
+ type: "string",
+ const: "vi",
+ },
+ {
+ type: "string",
+ const: "svi",
+ },
+ {
+ type: "string",
+ const: "lvi",
+ },
+ {
+ type: "string",
+ const: "dvi",
+ },
+ {
+ type: "string",
+ const: "vb",
+ },
+ {
+ type: "string",
+ const: "svb",
+ },
+ {
+ type: "string",
+ const: "lvb",
+ },
+ {
+ type: "string",
+ const: "dvb",
+ },
+ {
+ type: "string",
+ const: "vmin",
+ },
+ {
+ type: "string",
+ const: "svmin",
+ },
+ {
+ type: "string",
+ const: "lvmin",
+ },
+ {
+ type: "string",
+ const: "dvmin",
+ },
+ {
+ type: "string",
+ const: "vmax",
+ },
+ {
+ type: "string",
+ const: "svmax",
+ },
+ {
+ type: "string",
+ const: "lvmax",
+ },
+ {
+ type: "string",
+ const: "dvmax",
+ },
+ ],
+ },
+ },
+ required: [
+ "type",
+ "value",
+ "unit",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ const: "auto",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ isPinned: {
+ type: "boolean",
+ },
+ debug: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "animations"],
+ },
+ ],
+ },
+ },
+ required: [
+ "id",
+ "instanceId",
+ "name",
+ "type",
+ "value",
+ ],
+ },
+ ],
+ },
+ },
+ breakpoints: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ label: {
+ type: "string",
+ },
+ minWidth: {
+ type: "number",
+ },
+ maxWidth: {
+ type: "number",
+ },
+ condition: {
+ type: "string",
+ },
+ },
+ required: ["id", "label"],
+ },
+ },
+ styleSourceSelections: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ instanceId: {
+ type: "string",
+ },
+ values: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ },
+ required: ["instanceId", "values"],
+ },
+ },
+ styleSources: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "token",
+ },
+ id: {
+ type: "string",
+ },
+ name: {
+ type: "string",
+ },
+ locked: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "id", "name"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "local",
+ },
+ id: {
+ type: "string",
+ },
+ },
+ required: ["type", "id"],
+ },
+ ],
+ },
+ },
+ styles: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ styleSourceId: {
+ type: "string",
+ },
+ breakpointId: {
+ type: "string",
+ },
+ state: {
+ type: "string",
+ },
+ property: {
+ type: "string",
+ },
+ value: {
+ $ref: "#/$defs/__schema0",
+ },
+ listed: {
+ description:
+ "Whether the style is from the Advanced panel",
+ type: "boolean",
+ },
+ },
+ required: [
+ "styleSourceId",
+ "breakpointId",
+ "property",
+ "value",
+ ],
+ },
+ },
+ },
+ required: [
+ "children",
+ "instances",
+ "assets",
+ "dataSources",
+ "resources",
+ "props",
+ "breakpoints",
+ "styleSourceSelections",
+ "styleSources",
+ "styles",
+ ],
+ description:
+ "One structured repeated-item fragment. Descendant expressions may reference collectionItem and collectionItemKey.",
+ },
+ mode: {
+ type: "string",
+ enum: ["append", "prepend", "replace"],
+ },
+ insertIndex: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["type", "data", "itemFragment"],
+ },
+ ],
+ },
+ bindings: {
+ default: [],
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ target: {
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "existing",
+ },
+ instanceId: {
+ type: "string",
+ },
+ },
+ required: ["type", "instanceId"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "insertedRoot",
+ },
+ index: {
+ default: 0,
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["type"],
+ },
+ ],
+ },
+ name: {
+ type: "string",
+ },
+ binding: {
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "expression",
+ },
+ value: {
+ type: "string",
+ description:
+ "One Webstudio JavaScript expression. Read webstudio://project/expressions before using unfamiliar scope or syntax.",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "parameter",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "resource",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ "Data binding only. Script actions are intentionally unsupported by runtime-ui integration.",
+ },
+ },
+ required: ["target", "name", "binding"],
+ },
+ },
+ retainedBehavior: {
+ default: [],
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ instanceId: {
+ type: "string",
+ description:
+ "Existing script-owning instance that remains unchanged.",
+ },
+ responsibility: {
+ type: "string",
+ minLength: 1,
+ description:
+ "Runtime behavior retained by the existing instance.",
+ },
+ },
+ required: ["instanceId", "responsibility"],
+ },
+ },
+ unsupportedConversions: {
+ default: [],
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ behavior: {
+ type: "string",
+ minLength: 1,
+ },
+ reason: {
+ type: "string",
+ minLength: 1,
+ description:
+ "Why this behavior cannot be represented safely in editable UI.",
+ },
+ },
+ required: ["behavior", "reason"],
+ },
+ },
+ },
+ required: ["parentInstanceId", "structure"],
+ description:
+ "Atomically integrate data-backed editable UI while retaining existing script-owned behavior. This operation stores declarative Webstudio data and never evaluates scripts.",
+ $defs: {
+ __schema0: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "image",
+ },
+ value: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "asset",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "url",
+ },
+ url: {
+ type: "string",
+ },
+ },
+ required: ["type", "url"],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "layers",
+ },
+ value: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "image",
+ },
+ value: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "asset",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "url",
+ },
+ url: {
+ type: "string",
+ },
+ },
+ required: ["type", "url"],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "tuple",
+ },
+ value: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "image",
+ },
+ value: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "asset",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "url",
+ },
+ url: {
+ type: "string",
+ },
+ },
+ required: ["type", "url"],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "r", "g", "b", "alpha"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "function",
+ },
+ name: {
+ type: "string",
+ },
+ args: {
+ $ref: "#/$defs/__schema0",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "name", "args"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ fallback: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: [
+ "type",
+ "r",
+ "g",
+ "b",
+ "alpha",
+ ],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "shadow",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ position: {
+ anyOf: [
+ {
+ type: "string",
+ const: "inset",
+ },
+ {
+ type: "string",
+ const: "outset",
+ },
+ ],
+ },
+ offsetX: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ fallback: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: [
+ "type",
+ "r",
+ "g",
+ "b",
+ "alpha",
+ ],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ offsetY: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ fallback: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: [
+ "type",
+ "r",
+ "g",
+ "b",
+ "alpha",
+ ],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ blur: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ fallback: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: [
+ "type",
+ "r",
+ "g",
+ "b",
+ "alpha",
+ ],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ spread: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ fallback: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: [
+ "type",
+ "r",
+ "g",
+ "b",
+ "alpha",
+ ],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ color: {
+ anyOf: [
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "r", "g", "b", "alpha"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ fallback: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: [
+ "type",
+ "r",
+ "g",
+ "b",
+ "alpha",
+ ],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ },
+ required: ["type", "position", "offsetX", "offsetY"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "r", "g", "b", "alpha"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "invalid",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "function",
+ },
+ name: {
+ type: "string",
+ },
+ args: {
+ $ref: "#/$defs/__schema0",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "name", "args"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ fallback: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "r", "g", "b", "alpha"],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "fontFamily",
+ },
+ value: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "r", "g", "b", "alpha"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "tuple",
+ },
+ value: {
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "image",
+ },
+ value: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "asset",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "url",
+ },
+ url: {
+ type: "string",
+ },
+ },
+ required: ["type", "url"],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "r", "g", "b", "alpha"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "function",
+ },
+ name: {
+ type: "string",
+ },
+ args: {
+ $ref: "#/$defs/__schema0",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "name", "args"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ fallback: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "r", "g", "b", "alpha"],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "function",
+ },
+ name: {
+ type: "string",
+ },
+ args: {
+ $ref: "#/$defs/__schema0",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "name", "args"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "guaranteedInvalid",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "invalid",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unset",
+ },
+ value: {
+ type: "string",
+ const: "",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ fallback: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "r", "g", "b", "alpha"],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "shadow",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ position: {
+ anyOf: [
+ {
+ type: "string",
+ const: "inset",
+ },
+ {
+ type: "string",
+ const: "outset",
+ },
+ ],
+ },
+ offsetX: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ fallback: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "r", "g", "b", "alpha"],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ offsetY: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ fallback: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "r", "g", "b", "alpha"],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ blur: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ fallback: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "r", "g", "b", "alpha"],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ spread: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ fallback: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "r", "g", "b", "alpha"],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ color: {
+ anyOf: [
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "r", "g", "b", "alpha"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ fallback: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "r", "g", "b", "alpha"],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ },
+ required: ["type", "position", "offsetX", "offsetY"],
+ },
+ ],
+ },
+ __schema1: {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "color",
+ },
+ colorSpace: {
+ anyOf: [
+ {
+ type: "string",
+ const: "hex",
+ },
+ {
+ type: "string",
+ const: "srgb",
+ },
+ {
+ type: "string",
+ const: "p3",
+ },
+ {
+ type: "string",
+ const: "srgb-linear",
+ },
+ {
+ type: "string",
+ const: "hsl",
+ },
+ {
+ type: "string",
+ const: "hwb",
+ },
+ {
+ type: "string",
+ const: "lab",
+ },
+ {
+ type: "string",
+ const: "lch",
+ },
+ {
+ type: "string",
+ const: "oklab",
+ },
+ {
+ type: "string",
+ const: "oklch",
+ },
+ {
+ type: "string",
+ const: "a98rgb",
+ },
+ {
+ type: "string",
+ const: "prophoto",
+ },
+ {
+ type: "string",
+ const: "rec2020",
+ },
+ {
+ type: "string",
+ const: "xyz-d65",
+ },
+ {
+ type: "string",
+ const: "xyz-d50",
+ },
+ ],
+ },
+ components: {
+ type: "array",
+ prefixItems: [
+ {
+ type: "number",
+ },
+ {
+ type: "number",
+ },
+ {
+ type: "number",
+ },
+ ],
+ minItems: 3,
+ maxItems: 3,
+ },
+ alpha: {
+ anyOf: [
+ {
+ type: "number",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "var",
+ },
+ value: {
+ type: "string",
+ },
+ fallback: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unparsed",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "keyword",
+ },
+ value: {
+ type: "string",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "unit",
+ },
+ unit: {
+ type: "string",
+ },
+ value: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "unit", "value"],
+ },
+ {
+ $ref: "#/$defs/__schema1",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "rgb",
+ },
+ r: {
+ type: "number",
+ },
+ g: {
+ type: "number",
+ },
+ b: {
+ type: "number",
+ },
+ alpha: {
+ type: "number",
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "r", "g", "b", "alpha"],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ },
+ hidden: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "colorSpace", "components", "alpha"],
+ },
+ },
+ },
+ outputSchema: {
+ type: "object",
+ properties: {
+ created: {
+ type: "object",
+ properties: {
+ variableIds: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ resources: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ resourceId: {
+ type: "string",
+ },
+ dataSourceId: {
+ type: "string",
+ },
+ },
+ required: ["resourceId"],
+ additionalProperties: {},
+ },
+ },
+ instanceIds: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ rootInstanceIds: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ propIds: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
},
required: [
- "contractVersion",
- "projectVersion",
- "scopes",
- "pageFilter",
- "summary",
- "skippedCheckCount",
- "manualCheckCount",
- "renderedCheckCount",
- "renderedIssueCount",
- "renderedFailureCount",
- "renderedState",
- "renderedPlan",
- "renderedCaptureSummary",
- "renderedCaptureStatuses",
- "renderedArtifactManifest",
- "nextCursor",
- "verbose",
- "findings",
- "skippedChecks",
- "manualChecks",
- "renderedChecks",
- "renderedFailures",
+ "variableIds",
+ "resources",
+ "instanceIds",
+ "rootInstanceIds",
+ "propIds",
],
+ additionalProperties: {},
+ },
+ editableStructure: {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ enum: ["fragment", "collection"],
+ },
+ usesCollection: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "usesCollection"],
+ additionalProperties: {},
+ },
+ retainedBehavior: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ instanceId: {
+ type: "string",
+ },
+ responsibility: {
+ type: "string",
+ },
+ },
+ required: ["instanceId", "responsibility"],
+ additionalProperties: {},
+ },
+ },
+ unsupportedConversions: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ behavior: {
+ type: "string",
+ },
+ reason: {
+ type: "string",
+ },
+ },
+ required: ["behavior", "reason"],
+ additionalProperties: {},
+ },
+ },
+ warnings: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ severity: {
+ type: "string",
+ const: "warning",
+ },
+ code: {
+ type: "string",
+ },
+ path: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ message: {
+ type: "string",
+ },
+ range: {
+ type: "object",
+ properties: {
+ from: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ to: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["from", "to"],
+ },
+ remediation: {
+ type: "string",
+ },
+ instanceId: {
+ type: "string",
+ },
+ resourceId: {
+ type: "string",
+ },
+ },
+ required: [
+ "severity",
+ "code",
+ "path",
+ "message",
+ "range",
+ "remediation",
+ ],
+ },
},
+ },
+ required: [
+ "created",
+ "editableStructure",
+ "retainedBehavior",
+ "unsupportedConversions",
+ "warnings",
],
+ additionalProperties: {},
},
readNamespaces: [
"pages",
- "projectSettings",
"instances",
"props",
- "styles",
+ "dataSources",
+ "resources",
"styleSources",
"styleSourceSelections",
- "resources",
+ "styles",
+ "breakpoints",
+ "assets",
+ ],
+ writeNamespaces: [
+ "pages",
+ "instances",
+ "props",
"dataSources",
+ "resources",
+ "styleSources",
+ "styleSourceSelections",
+ "styles",
+ "breakpoints",
"assets",
+ ],
+ invalidatesNamespaces: [
+ "pages",
+ "instances",
+ "props",
+ "dataSources",
+ "resources",
+ "styleSources",
+ "styleSourceSelections",
+ "styles",
"breakpoints",
+ "assets",
],
- writeNamespaces: [],
- invalidatesNamespaces: [],
retryOnConflict: false,
requiresAssets: true,
},
@@ -47889,10 +58819,18 @@ export const runtimeOperationContractData = [
contains: {
type: "string",
},
- maxValueLength: {
+ cursor: {
+ type: "string",
+ },
+ limit: {
type: "integer",
- minimum: 0,
- maximum: 9007199254740991,
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
},
},
required: [],
@@ -47923,22 +58861,72 @@ export const runtimeOperationContractData = [
type: "string",
enum: ["text", "expression"],
},
+ valuePreview: {
+ type: "string",
+ },
value: {
type: "string",
},
+ valueLength: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ truncated: {
+ type: "boolean",
+ },
},
required: [
"instanceId",
"childIndex",
"component",
"mode",
- "value",
+ "valuePreview",
+ "valueLength",
+ "truncated",
],
additionalProperties: {},
},
},
+ detail: {
+ type: "string",
+ enum: ["compact", "verbose"],
+ },
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ returnedCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ filters: {
+ type: "object",
+ properties: {},
+ additionalProperties: {},
+ required: [],
+ },
},
- required: ["texts"],
+ required: [
+ "texts",
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ],
additionalProperties: {},
},
readNamespaces: ["pages", "instances"],
@@ -49775,6 +60763,19 @@ export const runtimeOperationContractData = [
withUsage: {
type: "boolean",
},
+ cursor: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
+ },
},
required: [],
},
@@ -49792,6 +60793,11 @@ export const runtimeOperationContractData = [
value: {
type: "string",
},
+ valueLength: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
scope: {
type: "string",
},
@@ -49801,12 +60807,49 @@ export const runtimeOperationContractData = [
maximum: 9007199254740991,
},
},
- required: ["name", "value", "scope"],
+ required: ["name", "valueLength", "scope"],
additionalProperties: {},
},
},
+ detail: {
+ type: "string",
+ enum: ["compact", "verbose"],
+ },
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ returnedCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ filters: {
+ type: "object",
+ properties: {},
+ additionalProperties: {},
+ required: [],
+ },
},
- required: ["vars"],
+ required: [
+ "vars",
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ],
additionalProperties: {},
},
readNamespaces: [
@@ -52701,6 +63744,19 @@ export const runtimeOperationContractData = [
scopeInstanceId: {
type: "string",
},
+ cursor: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
+ },
},
required: [],
},
@@ -52721,6 +63777,9 @@ export const runtimeOperationContractData = [
scopeInstanceId: {
type: "string",
},
+ valueType: {
+ type: "string",
+ },
value: {
anyOf: [
{
@@ -52792,12 +63851,49 @@ export const runtimeOperationContractData = [
],
},
},
- required: ["id", "name", "value"],
+ required: ["id", "name", "valueType"],
additionalProperties: {},
},
},
+ detail: {
+ type: "string",
+ enum: ["compact", "verbose"],
+ },
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ returnedCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ filters: {
+ type: "object",
+ properties: {},
+ additionalProperties: {},
+ required: [],
+ },
},
- required: ["variables"],
+ required: [
+ "variables",
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ],
additionalProperties: {},
},
readNamespaces: ["dataSources"],
@@ -53142,6 +64238,19 @@ export const runtimeOperationContractData = [
scopeInstanceId: {
type: "string",
},
+ cursor: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
+ },
},
required: [],
},
@@ -53180,8 +64289,45 @@ export const runtimeOperationContractData = [
additionalProperties: {},
},
},
+ detail: {
+ type: "string",
+ enum: ["compact", "verbose"],
+ },
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ returnedCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ filters: {
+ type: "object",
+ properties: {},
+ additionalProperties: {},
+ required: [],
+ },
},
- required: ["resources"],
+ required: [
+ "resources",
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ],
additionalProperties: {},
},
readNamespaces: ["dataSources", "resources"],
@@ -54442,6 +65588,19 @@ export const runtimeOperationContractData = [
description: "Include built-in system font stacks.",
type: "boolean",
},
+ cursor: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
+ },
},
required: [],
},
@@ -54460,6 +65619,11 @@ export const runtimeOperationContractData = [
type: "string",
const: "uploaded",
},
+ assetCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
assets: {
type: "array",
items: {
@@ -54493,7 +65657,7 @@ export const runtimeOperationContractData = [
},
},
},
- required: ["family", "source", "assets"],
+ required: ["family", "source", "assetCount"],
additionalProperties: {},
},
},
@@ -54519,12 +65683,50 @@ export const runtimeOperationContractData = [
type: "string",
},
},
- required: ["family", "source", "stack", "description"],
+ required: ["family", "source"],
additionalProperties: {},
},
},
+ detail: {
+ type: "string",
+ enum: ["compact", "verbose"],
+ },
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ returnedCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ filters: {
+ type: "object",
+ properties: {},
+ additionalProperties: {},
+ required: [],
+ },
},
- required: ["uploaded", "system"],
+ required: [
+ "uploaded",
+ "system",
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ],
additionalProperties: {},
},
readNamespaces: ["assets"],
@@ -54544,6 +65746,19 @@ export const runtimeOperationContractData = [
assetId: {
type: "string",
},
+ cursor: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
+ },
},
required: ["assetId"],
},
@@ -54590,8 +65805,45 @@ export const runtimeOperationContractData = [
additionalProperties: {},
},
},
+ detail: {
+ type: "string",
+ enum: ["compact", "verbose"],
+ },
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ returnedCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ filters: {
+ type: "object",
+ properties: {},
+ additionalProperties: {},
+ required: [],
+ },
},
- required: ["usages"],
+ required: [
+ "usages",
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ],
additionalProperties: {},
},
readNamespaces: [
diff --git a/packages/project-build/src/docs.generated.ts b/packages/project-build/src/docs.generated.ts
index ad0fb2d2ca..1c9e44ce9e 100644
--- a/packages/project-build/src/docs.generated.ts
+++ b/packages/project-build/src/docs.generated.ts
@@ -4,7 +4,7 @@ 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. A valid expression that references an\nidentifier unavailable in that scope is accepted with a structured warning\ncontaining the field path, source range, affected record, and remediation.\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, call `insert-collection`\nwith the complete iterable and one repeated-item JSX root. Do not pass the\nresponse wrapper or one indexed item. The command creates the Collection and\nits private item parameters atomically, then renders the item root once per\nentry. Bind descendants with expressions such as `collectionItem.name`; for\nobject iteration, `collectionItemKey` contains the current key. Wrap multiple\nrepeated siblings in one `ws.element` root.\n\n## Verification\n\nInspect every returned expression warning. Correct warnings that indicate a\nmisspelled or unavailable variable, then read the affected record and preview\nthe page. A warning does not roll back the mutation, and a successful syntax\nparse does not prove runtime data has the expected shape. Verify representative\ndata, empty/null data, and Collection item counts; use `audit` for relevant\nstructural findings.\n',
+ '# 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. A valid expression that references an\nidentifier unavailable in that scope is accepted with a structured warning\ncontaining the field path, source range, affected record, and remediation.\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, call `insert-collection`\nwith the complete iterable and one repeated-item JSX root. Do not pass the\nresponse wrapper or one indexed item. The command creates the Collection and\nits private item parameters atomically, then renders the item root once per\nentry. Bind descendants with expressions such as `collectionItem.name`; for\nobject iteration, `collectionItemKey` contains the current key. Wrap multiple\nrepeated siblings in one `ws.element` root.\n\n## Verification\n\nInspect every returned expression warning. Correct warnings that indicate a\nmisspelled or unavailable variable, then run `verify-bindings` for persisted\nsyntax, scope, and reference integrity. A warning does not roll back the\nmutation, and successful static verification does not prove runtime data has\nthe expected shape. `verify-bindings` never executes external resources or\nresolves rendered values. Preview representative data, empty/null data, and\nCollection item counts; use `audit` for relevant structural findings.\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
index b5905c1cf9..2c1e517b11 100644
--- a/packages/project-build/src/docs/expressions.md
+++ b/packages/project-build/src/docs/expressions.md
@@ -93,8 +93,9 @@ repeated siblings in one `ws.element` root.
## Verification
Inspect every returned expression warning. Correct warnings that indicate a
-misspelled or unavailable variable, then read the affected record and preview
-the page. A warning does not roll back the mutation, and a successful syntax
-parse does not prove runtime data has the expected shape. Verify representative
-data, empty/null data, and Collection item counts; use `audit` for relevant
-structural findings.
+misspelled or unavailable variable, then run `verify-bindings` for persisted
+syntax, scope, and reference integrity. A warning does not roll back the
+mutation, and successful static verification does not prove runtime data has
+the expected shape. `verify-bindings` never executes external resources or
+resolves rendered values. Preview representative data, empty/null data, and
+Collection item counts; use `audit` for relevant structural findings.
diff --git a/packages/project-build/src/mcp-rendered-audit.test.ts b/packages/project-build/src/mcp-rendered-audit.test.ts
index 306b471298..1700101998 100644
--- a/packages/project-build/src/mcp-rendered-audit.test.ts
+++ b/packages/project-build/src/mcp-rendered-audit.test.ts
@@ -5,11 +5,15 @@ import {
augmentAuditWithRenderedChecks,
getRenderedAuditOverallTimeout,
getRenderedAuditViewports,
+ getRenderedContrastIssues,
+ getRenderedGeometryIssues,
getRenderedImageIssues,
getRenderedResourceIssues,
} from "./mcp-rendered-audit";
-const { mergeRenderedAudit } = __testing__;
+const { addCrossBreakpointGeometryIssues, mergeRenderedAudit } = __testing__;
+const previewUrl = "http://127.0.0.1:5177";
+const createStartPreview = () => vi.fn(async () => ({ url: previewUrl }));
const layout = {
documentType: "text/html",
@@ -20,6 +24,7 @@ const layout = {
horizontalOverflow: false,
images: [],
resources: [],
+ contrasts: [],
};
const getNavigation = (path: string) => ({
@@ -35,6 +40,200 @@ const getNavigation = (path: string) => ({
});
describe("rendered audit evidence", () => {
+ test("reports only measured contrast ratios below their exact threshold", () => {
+ expect(
+ getRenderedContrastIssues({
+ ...layout,
+ contrasts: [
+ {
+ instanceId: "muted-copy",
+ tagName: "p",
+ foreground: "rgb(120, 120, 120)",
+ background: "rgb(255, 255, 255)",
+ ratio: 4.2,
+ requiredRatio: 4.5,
+ fontSize: 16,
+ fontWeight: 400,
+ },
+ {
+ instanceId: "heading",
+ tagName: "h1",
+ foreground: "rgb(0, 0, 0)",
+ background: "rgb(255, 255, 255)",
+ ratio: 21,
+ requiredRatio: 3,
+ fontSize: 32,
+ fontWeight: 700,
+ },
+ ],
+ })
+ ).toEqual([
+ {
+ kind: "low-text-contrast",
+ confidence: "exact",
+ instanceId: "muted-copy",
+ tagName: "p",
+ foreground: "rgb(120, 120, 120)",
+ background: "rgb(255, 255, 255)",
+ ratio: 4.2,
+ requiredRatio: 4.5,
+ fontSize: 16,
+ fontWeight: 400,
+ },
+ ]);
+ });
+
+ test("reports exact clipping and advisory overlap from bounded geometry", () => {
+ expect(
+ getRenderedGeometryIssues({
+ ...layout,
+ elementGeometry: {
+ total: 2,
+ sampled: 2,
+ truncated: false,
+ elements: [
+ {
+ instanceId: "card",
+ tagName: "article",
+ x: 0,
+ y: 0,
+ width: 300,
+ height: 200,
+ visible: true,
+ clippedX: true,
+ clippedY: false,
+ overlapsWith: ["badge"],
+ },
+ {
+ instanceId: "badge",
+ tagName: "div",
+ x: 250,
+ y: 0,
+ width: 100,
+ height: 40,
+ visible: true,
+ clippedX: false,
+ clippedY: false,
+ overlapsWith: ["card"],
+ },
+ ],
+ },
+ })
+ ).toEqual([
+ {
+ kind: "clipped-content",
+ confidence: "exact",
+ instanceId: "card",
+ message: "Rendered content exceeds a clipping boundary.",
+ evidence: { clippedX: true, clippedY: false },
+ },
+ {
+ kind: "overlapping-elements",
+ confidence: "advisory",
+ instanceId: "badge",
+ relatedInstanceId: "card",
+ message:
+ "Rendered element bounds overlap; inspect the screenshot to determine whether this is intentional.",
+ evidence: {},
+ },
+ ]);
+ });
+
+ test("reports persistent hidden content and advisory breakpoint changes once", () => {
+ const makeCheck = (
+ width: number,
+ elements: Array<{
+ instanceId: string;
+ visible: boolean;
+ x: number;
+ width: number;
+ hiddenReason?: "display";
+ }>
+ ) => ({
+ pageId: "home",
+ pagePath: "/",
+ viewport: { width, height: 800 },
+ screenshotPath: `/tmp/${width}.webp`,
+ layout: {
+ ...layout,
+ viewportWidth: width,
+ elementGeometry: {
+ total: elements.length,
+ sampled: elements.length,
+ truncated: false,
+ elements: elements.map((element) => ({
+ ...element,
+ tagName: "div",
+ y: 0,
+ height: 100,
+ clippedX: false,
+ clippedY: false,
+ overlapsWith: [],
+ })),
+ },
+ },
+ issues: [],
+ geometryIssues: [],
+ imageIssues: [],
+ resourceIssues: [],
+ });
+ const [mobile, desktop] = addCrossBreakpointGeometryIssues([
+ makeCheck(375, [
+ {
+ instanceId: "always-hidden",
+ visible: false,
+ hiddenReason: "display",
+ x: 0,
+ width: 0,
+ },
+ {
+ instanceId: "responsive-nav",
+ visible: false,
+ hiddenReason: "display",
+ x: 0,
+ width: 0,
+ },
+ ]),
+ makeCheck(1440, [
+ {
+ instanceId: "always-hidden",
+ visible: false,
+ hiddenReason: "display",
+ x: 0,
+ width: 0,
+ },
+ {
+ instanceId: "responsive-nav",
+ visible: true,
+ x: 900,
+ width: 400,
+ },
+ ]),
+ ] as never);
+
+ expect(mobile?.geometryIssues).toMatchObject([
+ {
+ kind: "hidden-content",
+ confidence: "advisory",
+ instanceId: "always-hidden",
+ },
+ ]);
+ expect(desktop?.geometryIssues).toMatchObject([
+ {
+ kind: "cross-breakpoint-layout-change",
+ confidence: "advisory",
+ instanceId: "responsive-nav",
+ evidence: {
+ sourceViewportWidth: 375,
+ targetViewportWidth: 1440,
+ sourceVisible: false,
+ targetVisible: true,
+ },
+ },
+ ]);
+ expect(desktop?.issues).toEqual(["cross-breakpoint-layout-change"]);
+ });
+
test("budgets five minutes for each confirmed capture batch", () => {
expect(getRenderedAuditOverallTimeout(1)).toBe(5 * 60_000);
expect(getRenderedAuditOverallTimeout(120)).toBe(5 * 60_000);
@@ -44,6 +243,7 @@ describe("rendered audit evidence", () => {
});
test("matches the public root path to the stored empty home path", async () => {
+ const storeRenderedAuditArtifacts = vi.fn(async () => "/manifest.json");
const captureScreenshot = vi.fn(async (input) => ({
output: `/tmp/home-${input.viewport.width}.png`,
browserPath: "/usr/bin/chromium",
@@ -77,9 +277,28 @@ describe("rendered audit evidence", () => {
? { pages: [{ id: "home", path: "" }] }
: { breakpoints: [] },
}) as never,
- startPreview: vi.fn(),
+ startPreview: vi.fn(async () => ({
+ url: previewUrl,
+ generatedBuildMetrics: {
+ version: 1,
+ fileCount: 3,
+ bytes: 4_000,
+ gzipBytes: 1_200,
+ client: { fileCount: 2, bytes: 3_000, gzipBytes: 900 },
+ server: { fileCount: 1, bytes: 1_000, gzipBytes: 300 },
+ largestFiles: [
+ {
+ path: "client/assets/index.js",
+ bytes: 2_000,
+ gzipBytes: 600,
+ kind: "script",
+ },
+ ],
+ },
+ })),
stopPreview: vi.fn(),
captureScreenshot,
+ storeRenderedAuditArtifacts,
});
expect(captureScreenshot).toHaveBeenCalledOnce();
@@ -89,7 +308,23 @@ describe("rendered audit evidence", () => {
captureCount: 1,
},
renderedFailureCount: 0,
+ generatedBuildSummary: {
+ version: 1,
+ fileCount: 3,
+ bytes: 4_000,
+ gzipBytes: 1_200,
+ },
+ generatedBuildMetrics: {
+ largestFiles: [
+ expect.objectContaining({ path: "client/assets/index.js" }),
+ ],
+ },
});
+ expect(storeRenderedAuditArtifacts).toHaveBeenCalledWith(
+ expect.objectContaining({
+ performance: expect.objectContaining({ captureCount: 1 }),
+ })
+ );
});
test("loads pages and breakpoints concurrently", async () => {
@@ -124,7 +359,7 @@ describe("rendered audit evidence", () => {
} as never,
input: { rendered: true, verbose: true },
executeRead,
- startPreview: vi.fn(),
+ startPreview: createStartPreview(),
stopPreview: vi.fn(),
captureScreenshot: vi.fn(async (input) => ({
output: "/tmp/home.png",
@@ -142,6 +377,63 @@ describe("rendered audit evidence", () => {
expect(maximumActiveReads).toBe(2);
});
+ test("reports sparse structured capture progress for larger audits", async () => {
+ const progress: string[] = [];
+ const pages = Array.from({ length: 12 }, (_, index) => ({
+ id: `page-${index}`,
+ path: `/page-${index}`,
+ }));
+
+ await augmentAuditWithRenderedChecks({
+ envelope: {
+ operationId: "project.audit",
+ source: "remote",
+ projectId: "project",
+ buildId: "build",
+ version: 1,
+ committed: false,
+ result: { scopes: ["accessibility"], manualCheckCount: 0 },
+ } as never,
+ input: { rendered: true },
+ executeRead: async (command) =>
+ ({
+ result: command === "list-pages" ? { pages } : { breakpoints: [] },
+ }) as never,
+ startPreview: createStartPreview(),
+ stopPreview: vi.fn(),
+ captureScreenshot: vi.fn(async (input) => ({
+ output: `/tmp${input.path}.webp`,
+ browserPath: "/usr/bin/chromium",
+ browser: "chromium" as const,
+ viewport: input.viewport,
+ fullPage: true,
+ elapsedMs: 10,
+ warnings: [],
+ navigation: getNavigation(input.path ?? "/"),
+ layout,
+ })),
+ reportProgress: (message) => progress.push(message),
+ });
+
+ const structured = progress.filter((message) =>
+ message.startsWith("tool audit progress ")
+ );
+ expect(structured.length).toBeLessThanOrEqual(12);
+ expect(
+ structured.map((message) =>
+ JSON.parse(message.slice("tool audit progress ".length))
+ )
+ ).toEqual(
+ expect.arrayContaining([
+ { phase: "planned", pages: 12, viewports: 1, captures: 12 },
+ { phase: "capture", completed: 12, total: 12 },
+ ])
+ );
+ expect(progress.some((message) => message.includes("capturing /"))).toBe(
+ false
+ );
+ });
+
test("captures each page once and resizes through its viewport plan", async () => {
const captureScreenshot = vi.fn();
const capturePageScreenshots = vi.fn(
@@ -174,6 +466,7 @@ describe("rendered audit evidence", () => {
}))
);
const storeRenderedAuditArtifacts = vi.fn(async () => "/manifest.json");
+ const startPreview = createStartPreview();
const result = await augmentAuditWithRenderedChecks({
envelope: {
@@ -197,13 +490,17 @@ describe("rendered audit evidence", () => {
? { pages: [{ id: "page", path: "/page" }] }
: { breakpoints: [] },
}) as never,
- startPreview: vi.fn(),
+ startPreview,
stopPreview: vi.fn(),
captureScreenshot,
capturePageScreenshots,
storeRenderedAuditArtifacts,
});
+ expect(startPreview).toHaveBeenCalledWith(
+ expect.objectContaining({ port: 0, source: "session" }),
+ expect.any(Object)
+ );
expect(capturePageScreenshots).toHaveBeenCalledOnce();
expect(capturePageScreenshots).toHaveBeenCalledWith([
expect.objectContaining({
@@ -281,7 +578,7 @@ describe("rendered audit evidence", () => {
? { pages: [{ id: "page", path: "/page" }] }
: { breakpoints: [] },
}) as never,
- startPreview: vi.fn(),
+ startPreview: createStartPreview(),
stopPreview: vi.fn(),
captureScreenshot,
capturePageScreenshots,
@@ -352,7 +649,7 @@ describe("rendered audit evidence", () => {
({
result: command === "list-pages" ? { pages } : { breakpoints: [] },
}) as never,
- startPreview: vi.fn(),
+ startPreview: createStartPreview(),
stopPreview: vi.fn(),
captureScreenshot,
capturePageScreenshots,
@@ -472,7 +769,7 @@ describe("rendered audit evidence", () => {
purposes: ["base breakpoint: desktop"],
},
],
- checks: ["horizontal-overflow"],
+ checks: ["horizontal-overflow", "low-text-contrast"],
captureCount: 2,
},
});
@@ -565,12 +862,14 @@ describe("rendered audit evidence", () => {
renderedIssueSummaries: [
{
kind: "oversized-image",
+ confidence: "advisory",
count: 3,
captureCount: 2,
pagePaths: ["/"],
},
{
kind: "broken-image",
+ confidence: "exact",
count: 1,
captureCount: 1,
pagePaths: ["/"],
@@ -745,7 +1044,7 @@ describe("rendered audit evidence", () => {
? { pages: [{ id: "missing", path: "/missing" }] }
: { breakpoints: [] },
}) as never,
- startPreview: vi.fn(),
+ startPreview: createStartPreview(),
stopPreview: vi.fn(),
captureScreenshot: vi.fn(async () => ({
output: "/tmp/missing.png",
@@ -835,7 +1134,7 @@ describe("rendered audit evidence", () => {
? { pages: [{ id: "old", path: "/old" }] }
: { breakpoints: [] },
}) as never,
- startPreview: vi.fn(),
+ startPreview: createStartPreview(),
stopPreview: vi.fn(),
captureScreenshot: vi.fn(async (input) => ({
output: `/tmp/redirect-${input.viewport.width}.png`,
@@ -897,7 +1196,7 @@ describe("rendered audit evidence", () => {
}
: { breakpoints: [] },
}) as never,
- startPreview: vi.fn(),
+ startPreview: createStartPreview(),
stopPreview,
captureScreenshot: vi.fn(async (input) => {
if (input.path === "/bad") {
@@ -959,7 +1258,7 @@ describe("rendered audit evidence", () => {
? { pages: [{ id: "sitemap", path: "/sitemap.xml" }] }
: { breakpoints: [] },
}) as never,
- startPreview: vi.fn(),
+ startPreview: createStartPreview(),
stopPreview: vi.fn(),
captureScreenshot: vi.fn(async (input) => ({
output: `/tmp/sitemap-${input.viewport.width}.png`,
@@ -1015,7 +1314,7 @@ describe("rendered audit evidence", () => {
? { pages: [{ id: "slow", path: "/slow" }] }
: { breakpoints: [] },
}) as never,
- startPreview: vi.fn(),
+ startPreview: createStartPreview(),
stopPreview: vi.fn(),
captureScreenshot: vi.fn(
async (): Promise<never> => await new Promise<never>(() => {})
@@ -1060,7 +1359,7 @@ describe("rendered audit evidence", () => {
? { pages: [{ id: "slow", path: "/slow" }] }
: { breakpoints: [] },
}) as never,
- startPreview: vi.fn(),
+ startPreview: createStartPreview(),
stopPreview: vi.fn(),
captureScreenshot,
capturePageScreenshots: vi.fn(
@@ -1080,8 +1379,67 @@ describe("rendered audit evidence", () => {
});
});
+ test("reads every page of paginated audit planning data", async () => {
+ const pages = Array.from({ length: 205 }, (_, index) => ({
+ id: `page-${index}`,
+ path: `/page-${index}`,
+ }));
+ const executeRead = vi.fn(
+ async (command: "list-pages" | "list-breakpoints", input: unknown) => {
+ if (command === "list-breakpoints") {
+ return { result: { breakpoints: [], nextCursor: null } } as never;
+ }
+ const { cursor, limit } = input as {
+ cursor?: string;
+ limit: number;
+ };
+ const offset = Number(cursor ?? 0);
+ const items = pages.slice(offset, offset + limit);
+ return {
+ result: {
+ pages: items,
+ nextCursor:
+ offset + items.length < pages.length
+ ? String(offset + items.length)
+ : null,
+ },
+ } as never;
+ }
+ );
+
+ 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 },
+ executeRead,
+ startPreview: createStartPreview(),
+ stopPreview: vi.fn(),
+ captureScreenshot: vi.fn(),
+ });
+
+ expect(executeRead).toHaveBeenCalledWith("list-pages", {
+ cursor: undefined,
+ limit: 200,
+ });
+ expect(executeRead).toHaveBeenCalledWith("list-pages", {
+ cursor: "200",
+ limit: 200,
+ });
+ expect(result.result).toMatchObject({
+ renderedState: "confirmation-required",
+ renderedPlan: { captureCount: 205 },
+ });
+ });
+
test("requires and consumes confirmation for a large unchanged plan", async () => {
- const startPreview = vi.fn();
+ const startPreview = createStartPreview();
const stopPreview = vi.fn();
const captureScreenshot = vi.fn(async (input) => ({
output: `/tmp/${input.path}-${input.viewport.width}.png`,
@@ -1152,7 +1510,7 @@ describe("rendered audit evidence", () => {
purposes: ["base breakpoint: desktop"],
}),
],
- checks: ["horizontal-overflow"],
+ checks: ["horizontal-overflow", "low-text-contrast"],
captureCount: 122,
confirmationToken: expect.any(String),
confirmationExpiresAt: expect.any(String),
@@ -1265,7 +1623,7 @@ describe("rendered audit evidence", () => {
});
test("explains excluded dynamic routes without starting preview", async () => {
- const startPreview = vi.fn();
+ const startPreview = createStartPreview();
const result = await augmentAuditWithRenderedChecks({
envelope: {
operationId: "project.audit",
@@ -1337,7 +1695,7 @@ describe("rendered audit evidence", () => {
test("stops scheduling captures and cleans up when the caller cancels", async () => {
const controller = new AbortController();
- const startPreview = vi.fn();
+ const startPreview = createStartPreview();
const stopPreview = vi.fn();
const captureScreenshot = vi.fn(() => {
controller.abort();
@@ -1434,7 +1792,7 @@ describe("rendered audit evidence", () => {
? { pages: [{ id: "post", path: "/blog/:slug" }] }
: { breakpoints: [] },
}) as never,
- startPreview: vi.fn(),
+ startPreview: createStartPreview(),
stopPreview: vi.fn(),
captureScreenshot,
storeRenderedAuditArtifacts,
@@ -1523,7 +1881,7 @@ describe("rendered audit evidence", () => {
? { pages: [{ id: "home", path: "" }] }
: { breakpoints: [] },
}) as never,
- startPreview: vi.fn(),
+ startPreview: createStartPreview(),
stopPreview: vi.fn(),
captureScreenshot,
});
diff --git a/packages/project-build/src/mcp-rendered-audit.ts b/packages/project-build/src/mcp-rendered-audit.ts
index f1f017c8e6..f763319c96 100644
--- a/packages/project-build/src/mcp-rendered-audit.ts
+++ b/packages/project-build/src/mcp-rendered-audit.ts
@@ -1,11 +1,13 @@
import type { ProjectSessionEnvelope } from "./project-session";
import type {
+ GeneratedBuildMetrics,
RenderedAuditCheck,
RenderedAuditFailure,
renderedAuditPlan,
} from "./runtime/audit";
import {
auditContractVersion,
+ generatedBuildMetrics as generatedBuildMetricsSchema,
renderedAuditManifestVersion,
} from "./runtime/audit";
import type { z } from "zod";
@@ -31,10 +33,48 @@ type ExecuteRead = (
input: unknown
) => Promise<ProjectSessionEnvelope>;
+const readAllPaginatedItems = async (
+ executeRead: ExecuteRead,
+ command: "list-pages" | "list-breakpoints",
+ key: "pages" | "breakpoints"
+) => {
+ const items: unknown[] = [];
+ const seenCursors = new Set<string>();
+ let cursor: string | undefined;
+ let firstEnvelope: ProjectSessionEnvelope | undefined;
+ do {
+ const envelope = await executeRead(command, { cursor, limit: 200 });
+ firstEnvelope ??= envelope;
+ if (isRecord(envelope.result) === false) {
+ throw new Error(`${command} returned an invalid result.`);
+ }
+ const page = envelope.result[key];
+ if (Array.isArray(page) === false) {
+ throw new Error(`${command} did not return ${key}.`);
+ }
+ items.push(...page);
+ const nextCursor = envelope.result.nextCursor;
+ cursor = typeof nextCursor === "string" ? nextCursor : undefined;
+ if (cursor !== undefined && seenCursors.has(cursor)) {
+ throw new Error(`${command} returned a repeated pagination cursor.`);
+ }
+ if (cursor !== undefined) {
+ seenCursors.add(cursor);
+ }
+ } while (cursor !== undefined);
+ if (firstEnvelope === undefined || isRecord(firstEnvelope.result) === false) {
+ throw new Error(`${command} returned no result.`);
+ }
+ return {
+ ...firstEnvelope,
+ result: { ...firstEnvelope.result, [key]: items, nextCursor: null },
+ };
+};
+
type StartPreview = (
input: { source: "session"; port: number; imageDomains?: string[] },
progress: { report: (message: string) => void }
-) => Promise<unknown>;
+) => Promise<{ url: string; generatedBuildMetrics?: unknown }>;
type CaptureScreenshot = (
input: ProjectSessionScreenshotInput
@@ -75,6 +115,7 @@ export type RenderedAuditArtifactManifest = {
artifactWriteMs: number;
targetCleanupMs: number;
};
+ generatedBuildMetrics: GeneratedBuildMetrics | null;
};
type StoreRenderedAuditArtifacts = (
@@ -87,7 +128,7 @@ const renderedAuditScreenshotTimeout = 10_000;
const renderedAuditCaptureTimeout = 30_000;
const renderedAuditPageTimeout = 120_000;
const renderedAuditOverallTimeout = 5 * 60_000;
-const renderedAuditPreviewPort = 5177;
+const automaticPreviewPort = 0;
const renderedAuditCaptureConcurrency = 6;
const getRenderedAuditCaptureKey = (
@@ -95,16 +136,29 @@ const getRenderedAuditCaptureKey = (
viewport: { width: number; height: number }
) => `${pageId}\n${viewport.width}\n${viewport.height}`;
+const getRenderedIssueConfidence = (
+ kind: RenderedAuditCheck["issues"][number]
+) =>
+ kind === "hidden-content" ||
+ kind === "overlapping-elements" ||
+ kind === "cross-breakpoint-layout-change" ||
+ kind === "eager-below-fold-image" ||
+ kind === "oversized-image"
+ ? ("advisory" as const)
+ : ("exact" as const);
+
const getRenderedAuditScreenshotInput = ({
pageId,
pagePath,
viewport,
performanceEnabled,
+ accessibilityEnabled,
}: {
pageId: string;
pagePath: string;
viewport: { width: number; height: number };
performanceEnabled: boolean;
+ accessibilityEnabled: boolean;
}): ProjectSessionScreenshotInput => ({
path: pagePath,
output: `.webstudio/audits/screenshots/${pageId.replaceAll(/[^a-z0-9_-]/gi, "_")}-${viewport.width}x${viewport.height}.webp`,
@@ -113,6 +167,7 @@ const getRenderedAuditScreenshotInput = ({
fullPage: true,
includeImageMetrics: performanceEnabled,
includeResourceMetrics: performanceEnabled,
+ includeContrastMetrics: accessibilityEnabled,
browser: "auto",
waitForTimeout: 0,
timeout: renderedAuditScreenshotTimeout,
@@ -390,6 +445,163 @@ type Layout = NonNullable<ProjectSessionScreenshotResult["layout"]> & {
resources: NonNullable<
NonNullable<ProjectSessionScreenshotResult["layout"]>["resources"]
>;
+ contrasts: NonNullable<
+ NonNullable<ProjectSessionScreenshotResult["layout"]>["contrasts"]
+ >;
+};
+
+type GeometryLayout = Layout & {
+ elementGeometry: RenderedAuditCheck["layout"]["elementGeometry"];
+};
+
+const emptyElementGeometry: GeometryLayout["elementGeometry"] = {
+ total: 0,
+ sampled: 0,
+ truncated: false,
+ elements: [],
+};
+
+export const getRenderedGeometryIssues = (
+ layout: GeometryLayout
+): RenderedAuditCheck["geometryIssues"] => {
+ const issues: RenderedAuditCheck["geometryIssues"] = [];
+ for (const element of layout.elementGeometry.elements) {
+ if (element.clippedX || element.clippedY) {
+ issues.push({
+ kind: "clipped-content",
+ confidence: "exact",
+ instanceId: element.instanceId,
+ message: "Rendered content exceeds a clipping boundary.",
+ evidence: {
+ clippedX: element.clippedX,
+ clippedY: element.clippedY,
+ },
+ });
+ }
+ for (const relatedInstanceId of element.overlapsWith) {
+ if (element.instanceId.localeCompare(relatedInstanceId) >= 0) {
+ continue;
+ }
+ issues.push({
+ kind: "overlapping-elements",
+ confidence: "advisory",
+ instanceId: element.instanceId,
+ relatedInstanceId,
+ message:
+ "Rendered element bounds overlap; inspect the screenshot to determine whether this is intentional.",
+ evidence: {},
+ });
+ }
+ }
+ return issues;
+};
+
+const addCrossBreakpointGeometryIssues = (
+ checks: RenderedAuditCheck[]
+): RenderedAuditCheck[] => {
+ const checksByPage = checks.reduce((pages, check) => {
+ const pageChecks = pages.get(check.pageId) ?? [];
+ pageChecks.push(check);
+ pages.set(check.pageId, pageChecks);
+ return pages;
+ }, new Map<string, RenderedAuditCheck[]>());
+ const additions = new Map<
+ RenderedAuditCheck,
+ RenderedAuditCheck["geometryIssues"]
+ >();
+ for (const pageChecks of checksByPage.values()) {
+ pageChecks.sort(
+ (left, right) => left.viewport.width - right.viewport.width
+ );
+ const elementsByCheck = pageChecks.map(
+ (check) =>
+ new Map(
+ check.layout.elementGeometry.elements.map((element) => [
+ element.instanceId,
+ element,
+ ])
+ )
+ );
+ const firstCheck = pageChecks[0];
+ const firstElements = elementsByCheck[0];
+ if (firstCheck !== undefined && firstElements !== undefined) {
+ const hiddenIssues = additions.get(firstCheck) ?? [];
+ for (const [instanceId, element] of firstElements) {
+ if (
+ elementsByCheck.every(
+ (elements) => elements.get(instanceId)?.visible === false
+ )
+ ) {
+ hiddenIssues.push({
+ kind: "hidden-content",
+ confidence: "advisory",
+ instanceId,
+ message:
+ "This element is hidden at every audited viewport; verify that it is intentionally unreachable.",
+ evidence: { hiddenReason: element.hiddenReason },
+ });
+ }
+ }
+ additions.set(firstCheck, hiddenIssues);
+ }
+ for (let index = 1; index < pageChecks.length; index++) {
+ const previous = pageChecks[index - 1]!;
+ const check = pageChecks[index]!;
+ const previousElements = elementsByCheck[index - 1]!;
+ const geometryIssues = additions.get(check) ?? [];
+ for (const element of check.layout.elementGeometry.elements) {
+ const previousElement = previousElements.get(element.instanceId);
+ if (previousElement === undefined) {
+ continue;
+ }
+ const normalizedXChange = Math.abs(
+ previousElement.x / previous.viewport.width -
+ element.x / check.viewport.width
+ );
+ const normalizedWidthChange = Math.abs(
+ previousElement.width / previous.viewport.width -
+ element.width / check.viewport.width
+ );
+ const overlapChanged =
+ [...previousElement.overlapsWith].sort().join("\n") !==
+ [...element.overlapsWith].sort().join("\n");
+ if (
+ previousElement.visible === element.visible &&
+ normalizedXChange <= 0.35 &&
+ normalizedWidthChange <= 0.6 &&
+ overlapChanged === false
+ ) {
+ continue;
+ }
+ geometryIssues.push({
+ kind: "cross-breakpoint-layout-change",
+ confidence: "advisory",
+ instanceId: element.instanceId,
+ message:
+ "This element changes visibility, position, size, or overlap state between audited breakpoints; inspect both screenshots.",
+ evidence: {
+ sourceViewportWidth: previous.viewport.width,
+ targetViewportWidth: check.viewport.width,
+ sourceVisible: previousElement.visible,
+ targetVisible: element.visible,
+ sourceX: previousElement.x,
+ targetX: element.x,
+ sourceWidth: previousElement.width,
+ targetWidth: element.width,
+ },
+ });
+ }
+ additions.set(check, geometryIssues);
+ }
+ }
+ return checks.map((check) => {
+ const addedIssues = additions.get(check) ?? [];
+ return {
+ ...check,
+ geometryIssues: [...check.geometryIssues, ...addedIssues],
+ issues: [...check.issues, ...addedIssues.map((issue) => issue.kind)],
+ };
+ });
};
export const getRenderedImageIssues = (
@@ -454,11 +666,27 @@ export const getRenderedResourceIssues = (
return issues;
});
+export const getRenderedContrastIssues = (
+ layout: Layout
+): NonNullable<RenderedAuditCheck["contrastIssues"]> =>
+ layout.contrasts.flatMap((contrast) =>
+ contrast.ratio < contrast.requiredRatio
+ ? [
+ {
+ kind: "low-text-contrast" as const,
+ confidence: "exact" as const,
+ ...contrast,
+ },
+ ]
+ : []
+ );
+
const getRenderedAuditPlan = (
pagesResult: unknown,
breakpointsResult: unknown,
input: RenderedAuditInput,
- performanceEnabled: boolean
+ performanceEnabled: boolean,
+ accessibilityEnabled: boolean
): RenderedAuditPlan => {
const normalizePagePath = (path: string) => path || "/";
const candidates =
@@ -514,6 +742,7 @@ const getRenderedAuditPlan = (
"legacy-font-format",
] as const)
: []),
+ ...(accessibilityEnabled ? (["low-text-contrast"] as const) : []),
],
captureCount: pages.length * viewports.length,
};
@@ -525,12 +754,14 @@ const mergeRenderedAudit = ({
checks,
failures,
plan,
+ generatedBuildMetrics,
}: {
envelope: ProjectSessionEnvelope;
input: RenderedAuditInput;
checks: RenderedAuditCheck[];
failures: RenderedAuditFailure[];
plan?: RenderedAuditPlan;
+ generatedBuildMetrics?: GeneratedBuildMetrics;
}): ProjectSessionEnvelope => {
const result = envelope.result;
if (isRecord(result) === false) {
@@ -654,6 +885,7 @@ const mergeRenderedAudit = ({
for (const kind of new Set(check.issues)) {
const summary = summaries.get(kind) ?? {
kind,
+ confidence: getRenderedIssueConfidence(kind),
count: 0,
captureCount: 0,
pagePaths: new Set<string>(),
@@ -669,7 +901,7 @@ const mergeRenderedAudit = ({
}
}
return summaries;
- }, new Map<RenderedAuditCheck["issues"][number], { kind: RenderedAuditCheck["issues"][number]; count: number; captureCount: number; pagePaths: Set<string> }>())
+ }, new Map<RenderedAuditCheck["issues"][number], { kind: RenderedAuditCheck["issues"][number]; confidence: "exact" | "advisory"; count: number; captureCount: number; pagePaths: Set<string> }>())
.values(),
({ pagePaths, ...summary }) => ({
...summary,
@@ -723,12 +955,24 @@ const mergeRenderedAudit = ({
renderedPlan: plan ?? null,
renderedCaptureSummary,
renderedCaptureStatuses,
+ generatedBuildSummary:
+ generatedBuildMetrics === undefined
+ ? null
+ : {
+ version: generatedBuildMetrics.version,
+ fileCount: generatedBuildMetrics.fileCount,
+ bytes: generatedBuildMetrics.bytes,
+ gzipBytes: generatedBuildMetrics.gzipBytes,
+ client: generatedBuildMetrics.client,
+ server: generatedBuildMetrics.server,
+ },
manualCheckCount: result.manualCheckCount,
...(isVerbose
? {
renderedChecks: orderedChecks,
renderedFailures: orderedFailures,
manualChecks: manualChecks ?? [],
+ generatedBuildMetrics: generatedBuildMetrics ?? null,
}
: { renderedIssueSummaries, renderedFailureSummaries }),
},
@@ -778,6 +1022,8 @@ export const augmentAuditWithRenderedChecks = async ({
const result = envelope.result;
const performanceEnabled =
Array.isArray(result.scopes) && result.scopes.includes("performance");
+ const accessibilityEnabled =
+ Array.isArray(result.scopes) && result.scopes.includes("accessibility");
const checks: RenderedAuditCheck[] = [];
const failures: RenderedAuditFailure[] = [];
const performance = {
@@ -794,6 +1040,8 @@ export const augmentAuditWithRenderedChecks = async ({
artifactWriteMs: 0,
targetCleanupMs: 0,
};
+ let generatedBuildMetrics: GeneratedBuildMetrics | undefined;
+ let previewOrigin: string | undefined;
const captureTimeout = timeouts?.capture ?? renderedAuditCaptureTimeout;
const pageTimeout = timeouts?.page ?? renderedAuditPageTimeout;
let overallTimeout = getRenderedAuditOverallTimeout(1, timeouts?.overall);
@@ -830,12 +1078,14 @@ export const augmentAuditWithRenderedChecks = async ({
});
};
const finish = async () => {
+ const completedChecks = addCrossBreakpointGeometryIssues(checks);
let merged = mergeRenderedAudit({
envelope,
input: renderedInput,
- checks,
+ checks: completedChecks,
failures,
plan,
+ generatedBuildMetrics,
});
if (
plan !== undefined &&
@@ -857,7 +1107,7 @@ export const augmentAuditWithRenderedChecks = async ({
captureStatuses: Array.isArray(merged.result.renderedCaptureStatuses)
? merged.result.renderedCaptureStatuses
: [],
- checks: [...checks],
+ checks: completedChecks,
failures: [...failures],
screenshot: {
format: "webp",
@@ -865,9 +1115,10 @@ export const augmentAuditWithRenderedChecks = async ({
scale: 0.5,
},
performance: { ...performance },
+ generatedBuildMetrics: generatedBuildMetrics ?? null,
});
const screenshotCount = new Set([
- ...checks.map((check) => check.screenshotPath),
+ ...completedChecks.map((check) => check.screenshotPath),
...failures.flatMap((failure) =>
failure.screenshotPath === undefined ? [] : [failure.screenshotPath]
),
@@ -895,9 +1146,10 @@ export const augmentAuditWithRenderedChecks = async ({
merged = mergeRenderedAudit({
envelope,
input: renderedInput,
- checks,
+ checks: completedChecks,
failures,
plan,
+ generatedBuildMetrics,
});
}
}
@@ -909,8 +1161,8 @@ export const augmentAuditWithRenderedChecks = async ({
let breakpointsEnvelope: ProjectSessionEnvelope;
try {
[pagesEnvelope, breakpointsEnvelope] = await Promise.all([
- executeRead("list-pages", {}),
- executeRead("list-breakpoints", {}),
+ readAllPaginatedItems(executeRead, "list-pages", "pages"),
+ readAllPaginatedItems(executeRead, "list-breakpoints", "breakpoints"),
]);
} catch (error) {
failures.push({
@@ -928,7 +1180,16 @@ export const augmentAuditWithRenderedChecks = async ({
pagesEnvelope.result,
breakpointsEnvelope.result,
renderedInput,
- performanceEnabled
+ performanceEnabled,
+ accessibilityEnabled
+ );
+ reportProgress?.(
+ `tool audit progress ${JSON.stringify({
+ phase: "planned",
+ pages: plan.pages.length,
+ viewports: plan.viewports.length,
+ captures: plan.captureCount,
+ })}`
);
if (plan.pages.length === 0) {
failures.push({
@@ -990,14 +1251,27 @@ export const augmentAuditWithRenderedChecks = async ({
const previewStartStartedAt = Date.now();
try {
- await startPreview(
+ const previewResult = await startPreview(
{
source: "session",
- port: renderedAuditPreviewPort,
+ port: automaticPreviewPort,
imageDomains: renderedInput.imageDomains,
},
{ report: (message) => reportProgress?.(message) }
);
+ const previewUrl = new URL(previewResult.url);
+ if (previewUrl.hostname !== "127.0.0.1") {
+ throw new Error(
+ `Rendered audit preview must use 127.0.0.1, received ${previewUrl.origin}.`
+ );
+ }
+ previewOrigin = previewUrl.origin;
+ const parsedGeneratedBuildMetrics = generatedBuildMetricsSchema.safeParse(
+ isRecord(previewResult) ? previewResult.generatedBuildMetrics : undefined
+ );
+ if (parsedGeneratedBuildMetrics.success) {
+ generatedBuildMetrics = parsedGeneratedBuildMetrics.data;
+ }
performance.previewStartMs = Date.now() - previewStartStartedAt;
} catch (error) {
performance.previewStartMs = Date.now() - previewStartStartedAt;
@@ -1040,12 +1314,10 @@ export const augmentAuditWithRenderedChecks = async ({
pagePath: page.pagePath,
viewport,
performanceEnabled,
+ accessibilityEnabled,
})
);
try {
- reportProgress?.(
- `tool audit capturing ${pages.length} pages across ${inputs.length} viewport widths`
- );
const screenshots = await withRenderedAuditCancellation(
withRenderedAuditCaptureTimeout(
capturePageScreenshots(inputs),
@@ -1111,13 +1383,14 @@ export const augmentAuditWithRenderedChecks = async ({
};
let nextPage = 0;
const captureNextPage = async (): Promise<void> => {
- const page = plan.pages[nextPage];
- nextPage += 1;
- if (page === undefined) {
- return;
+ while (true) {
+ const page = plan.pages[nextPage];
+ nextPage += 1;
+ if (page === undefined) {
+ return;
+ }
+ await capturePageBatch([page]);
}
- await capturePageBatch([page]);
- await captureNextPage();
};
await Promise.all(
Array.from(
@@ -1133,269 +1406,313 @@ export const augmentAuditWithRenderedChecks = async ({
}
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) {
+ let completedCaptures = 0;
+ let lastReportedMilestone = 0;
+ const reportCaptureComplete = () => {
+ completedCaptures += 1;
+ const milestone = Math.floor(
+ (completedCaptures / Math.max(1, captures.length)) * 10
+ );
+ if (milestone <= lastReportedMilestone && completedCaptures > 1) {
return;
}
- const { page, viewport } = capture;
- 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();
- }
+ lastReportedMilestone = milestone;
reportProgress?.(
- `tool audit capturing ${pagePath} at ${viewport.width}px`
+ `tool audit progress ${JSON.stringify({
+ phase: "capture",
+ completed: completedCaptures,
+ total: captures.length,
+ })}`
);
- try {
- 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({
- 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: viewportSize,
- message: "Screenshot did not return rendered layout metrics.",
- });
- return await captureNext();
+ };
+ const captureNext = async (): Promise<void> => {
+ while (true) {
+ if (signal?.aborted) {
+ recordCancellation();
+ return;
}
- 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 capture = captures[nextCapture];
+ nextCapture += 1;
+ if (capture === undefined) {
+ return;
}
- const finalUrl = new URL(screenshot.navigation.finalUrl);
+ const { page, viewport } = capture;
if (
- finalUrl.origin !== `http://127.0.0.1:${renderedAuditPreviewPort}`
+ terminalCaptureKeys.has(
+ getRenderedAuditCaptureKey(page.pageId, viewport)
+ )
) {
- 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();
+ reportCaptureComplete();
+ continue;
}
- 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
- ) {
+ 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_ROUTE_MISMATCH",
+ code: "RENDERED_AUDIT_OVERALL_TIMEOUT",
phase: "capture",
- retryable: false,
+ retryable: true,
remediation:
- "Inspect generated redirects and route definitions, then provide the canonical concrete page path.",
+ "Run a focused page audit or reduce the viewport plan, then retry the remaining pages.",
pageId: page.pageId,
pagePath,
viewport: viewportSize,
- screenshotPath: screenshot.output,
- message: `Requested ${requestedRoute}, but the generated preview finished at ${finalRoute}.`,
+ message: `Rendered audit exceeded its ${overallTimeout}ms overall timeout.`,
});
- return await captureNext();
+ reportCaptureComplete();
+ continue;
}
- if (
- screenshot.navigation.status !== undefined &&
- screenshot.navigation.status >= 400
- ) {
+ if (now - pageStart > pageTimeout) {
failures.push({
- code: "RENDERED_AUDIT_HTTP_ERROR",
+ code: "RENDERED_AUDIT_PAGE_TIMEOUT",
phase: "capture",
- retryable: false,
+ retryable: true,
remediation:
- "Verify that the generated project defines this route and that the preview server can render it.",
+ "Audit this page alone and inspect slow resources or readiness behavior before retrying the full run.",
pageId: page.pageId,
pagePath,
viewport: viewportSize,
- screenshotPath: screenshot.output,
- message: `Generated preview returned HTTP ${screenshot.navigation.status} for ${screenshot.navigation.finalUrl}.`,
+ message: `Rendered page audit exceeded its ${pageTimeout}ms timeout.`,
});
- return await captureNext();
+ reportCaptureComplete();
+ continue;
}
- 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.",
+ try {
+ const screenshot =
+ resizedScreenshots.get(
+ getRenderedAuditCaptureKey(page.pageId, viewport)
+ ) ??
+ (await withRenderedAuditCancellation(
+ withRenderedAuditCaptureTimeout(
+ captureScreenshot(
+ getRenderedAuditScreenshotInput({
+ pageId: page.pageId,
+ pagePath,
+ viewport: viewportSize,
+ performanceEnabled,
+ accessibilityEnabled,
+ })
+ ),
+ captureTimeout
+ ),
+ signal
+ ));
+ performance.captureCount += 1;
+ if (screenshot.timings !== undefined) {
+ 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({
+ 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: viewportSize,
+ message: "Screenshot did not return rendered layout metrics.",
+ });
+ reportCaptureComplete();
+ continue;
+ }
+ 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.",
+ });
+ reportCaptureComplete();
+ continue;
+ }
+ const finalUrl = new URL(screenshot.navigation.finalUrl);
+ if (finalUrl.origin !== previewOrigin) {
+ 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}.`,
+ });
+ reportCaptureComplete();
+ continue;
+ }
+ 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}.`,
+ });
+ reportCaptureComplete();
+ continue;
+ }
+ 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}.`,
+ });
+ reportCaptureComplete();
+ continue;
+ }
+ 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.`,
+ });
+ reportCaptureComplete();
+ continue;
+ }
+ 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.`,
+ });
+ reportCaptureComplete();
+ continue;
+ }
+ const layout: GeometryLayout = {
+ ...screenshot.layout,
+ navigation: screenshot.navigation,
+ elementGeometry:
+ "elementGeometry" in screenshot.layout &&
+ isRecord(screenshot.layout.elementGeometry)
+ ? (screenshot.layout
+ .elementGeometry as GeometryLayout["elementGeometry"])
+ : emptyElementGeometry,
+ images: screenshot.layout.images ?? [],
+ resources: screenshot.layout.resources ?? [],
+ contrasts: screenshot.layout.contrasts ?? [],
+ };
+ const imageIssues = performanceEnabled
+ ? getRenderedImageIssues(layout)
+ : [];
+ const resourceIssues = performanceEnabled
+ ? getRenderedResourceIssues(layout)
+ : [];
+ const geometryIssues = getRenderedGeometryIssues(layout);
+ const contrastIssues = accessibilityEnabled
+ ? getRenderedContrastIssues(layout)
+ : [];
+ checks.push({
pageId: page.pageId,
pagePath,
viewport: viewportSize,
screenshotPath: screenshot.output,
- message: `Captured ${screenshot.navigation.finalUrl} without a generated Webstudio page marker.`,
+ layout,
+ issues: [
+ ...(layout.horizontalOverflow
+ ? (["horizontal-overflow"] as const)
+ : []),
+ ...geometryIssues.map((issue) => issue.kind),
+ ...imageIssues.map((issue) => issue.kind),
+ ...resourceIssues.map((issue) => issue.kind),
+ ...contrastIssues.map((issue) => issue.kind),
+ ],
+ geometryIssues,
+ imageIssues,
+ resourceIssues,
+ contrastIssues,
});
- return await captureNext();
- }
- if (screenshot.navigation.layoutStable === false) {
+ } catch (error) {
+ if (error instanceof RenderedAuditCancelledError) {
+ recordCancellation(capture);
+ reportCaptureComplete();
+ return;
+ }
failures.push({
- code: "RENDERED_AUDIT_LAYOUT_UNSTABLE",
+ code:
+ error instanceof RenderedAuditCaptureTimeoutError
+ ? "RENDERED_AUDIT_CAPTURE_TIMEOUT"
+ : "RENDERED_AUDIT_SCREENSHOT_FAILED",
phase: "capture",
retryable: true,
remediation:
- "Retry after the page finishes loading, or provide a readiness selector for asynchronously rendered content.",
+ 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: viewportSize,
- screenshotPath: screenshot.output,
- message: `Captured ${screenshot.navigation.finalUrl} before its layout stabilized.`,
+ message: error instanceof Error ? error.message : String(error),
});
- return await captureNext();
- }
- const layout: Layout = {
- ...screenshot.layout,
- navigation: screenshot.navigation,
- images: screenshot.layout.images ?? [],
- resources: screenshot.layout.resources ?? [],
- };
- const imageIssues = performanceEnabled
- ? getRenderedImageIssues(layout)
- : [];
- const resourceIssues = performanceEnabled
- ? getRenderedResourceIssues(layout)
- : [];
- checks.push({
- pageId: page.pageId,
- pagePath,
- viewport: viewportSize,
- screenshotPath: screenshot.output,
- layout,
- issues: [
- ...(layout.horizontalOverflow
- ? (["horizontal-overflow"] as const)
- : []),
- ...imageIssues.map((issue) => issue.kind),
- ...resourceIssues.map((issue) => issue.kind),
- ],
- imageIssues,
- resourceIssues,
- });
- } catch (error) {
- if (error instanceof RenderedAuditCancelledError) {
- recordCancellation(capture);
- return;
}
- failures.push({
- 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: viewportSize,
- message: error instanceof Error ? error.message : String(error),
- });
+ reportCaptureComplete();
}
- await captureNext();
};
await Promise.all(
Array.from(
@@ -1424,4 +1741,7 @@ export const augmentAuditWithRenderedChecks = async ({
return await finish();
};
-export const __testing__ = { mergeRenderedAudit };
+export const __testing__ = {
+ addCrossBreakpointGeometryIssues,
+ mergeRenderedAudit,
+};
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index 86e508fd2e..fa510ed444 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -225,12 +225,31 @@ const publicMcpOperations: readonly PublicMcpOperation[] = [
"breakpoints",
],
}),
+ publicOperation({
+ command: "verify-bindings",
+ id: "project.verifyBindings",
+ description: "Verify persisted bindings",
+ inputSchema: getTestInputSchema(
+ z.object({
+ pagePath: z.string().optional(),
+ instanceId: z.string().optional(),
+ limit: z.number().int().positive().optional(),
+ })
+ ),
+ readNamespaces: ["pages", "instances", "props", "resources", "dataSources"],
+ }),
publicOperation({
command: "list-breakpoints",
id: "breakpoints.list",
description: "List breakpoints",
readNamespaces: ["breakpoints"],
}),
+ publicOperation({
+ command: "list-design-tokens",
+ id: "designTokens.list",
+ description: "List design tokens",
+ readNamespaces: ["styleSources", "styles"],
+ }),
publicOperation({
command: "whoami",
id: "auth.me",
@@ -406,6 +425,21 @@ const publicMcpOperations: readonly PublicMcpOperation[] = [
})
),
}),
+ styleOperation({
+ command: "attach-design-token",
+ id: "designTokens.attach",
+ description: "Attach a reusable style token",
+ readNamespaces: ["styleSources", "styleSourceSelections"],
+ writeNamespaces: ["styleSourceSelections"],
+ invalidatesNamespaces: ["styleSourceSelections"],
+ inputSchema: getTestInputSchema(
+ z.object({
+ designTokenId: z.string(),
+ instanceIds: z.array(z.string()).min(1),
+ position: z.enum(["before-local", "after-local"]).optional(),
+ })
+ ),
+ }),
publicOperation({
command: "apply-patch",
id: "build.applyPatch",
@@ -1295,7 +1329,7 @@ describe("project session mcp adapter", () => {
}
);
const startPreview = vi.fn(async () => ({
- url: "http://127.0.0.1:5173",
+ url: "http://127.0.0.1:5177",
running: true,
}));
const stopPreview = vi.fn(async () => ({
@@ -2085,7 +2119,7 @@ describe("project session mcp adapter", () => {
executeOperation,
});
- await adapter.callTool({
+ const result = await adapter.callTool({
name: "insert-component",
input: {
parentInstanceId: "body",
@@ -2104,9 +2138,36 @@ describe("project session mcp adapter", () => {
},
})
);
+ expect(result.structuredContent.meta).toMatchObject({
+ next: [expect.stringContaining("run audit")],
+ });
+ });
+
+ test("requires binding verification after binding-related mutations", async () => {
+ const operation = publicOperation({
+ command: "bind-props",
+ id: "props.bind",
+ method: "mutation",
+ permit: "edit",
+ description: "Bind props",
+ writeNamespaces: ["props"],
+ invalidatesNamespaces: ["props"],
+ });
+ const adapter = createProjectSessionMcpCore({
+ operations: [operation],
+ createProjectSession: createSessionFactory(),
+ executeOperation: createExecuteOperation(),
+ });
+
+ const result = await adapter.callTool({ name: operation.command });
+
+ expect(result.structuredContent.meta.next).toEqual([
+ expect.stringContaining("run verify-bindings"),
+ expect.stringContaining("run audit"),
+ ]);
});
- test("normalizes create-page description alias to meta description", async () => {
+ test("normalizes create-page description and preserves basic auth", async () => {
const executeOperation = createExecuteOperation(async () =>
createEnvelope({
operationId: "pages.create",
@@ -2133,6 +2194,13 @@ describe("project session mcp adapter", () => {
meta: z
.object({
description: z.string().optional(),
+ auth: z
+ .object({
+ method: z.literal("basic"),
+ login: z.string(),
+ password: z.string(),
+ })
+ .optional(),
})
.optional(),
})
@@ -2155,6 +2223,13 @@ describe("project session mcp adapter", () => {
title: "Harbor Ops Design System",
description:
"A realistic component coverage page for the Harbor Ops logistics product design system.",
+ meta: {
+ auth: {
+ method: "basic",
+ login: "editor",
+ password: "private-value",
+ },
+ },
},
});
@@ -2168,6 +2243,11 @@ describe("project session mcp adapter", () => {
meta: {
description:
"A realistic component coverage page for the Harbor Ops logistics product design system.",
+ auth: {
+ method: "basic",
+ login: "editor",
+ password: "private-value",
+ },
},
},
})
@@ -3073,7 +3153,7 @@ describe("project session mcp adapter", () => {
expect(index.structuredContent.data).toEqual(
expect.objectContaining({
readThisFirst: expect.stringContaining(
- "do one small discovery step, then act"
+ "first call meta.guide with the user's objective"
),
delegatedAgentRule: expect.stringContaining(
"shortcut command such as webstudio meta.index"
@@ -3216,7 +3296,7 @@ describe("project session mcp adapter", () => {
phase: "page-creation",
purpose: expect.stringContaining("Create it only if lookup proves"),
allowedTools: expect.arrayContaining(["list-pages"]),
- commandPattern: expect.stringMatching(/list-pages.*includeFolders/),
+ commandPattern: expect.stringMatching(/list-pages.*limit/),
fallbackCommandPattern: expect.stringMatching(
/create-page.*\/design-system/
),
@@ -3619,6 +3699,18 @@ describe("project session mcp adapter", () => {
name: "meta.guide",
input: { brief: "Bind a dynamic expression to a prop" },
});
+ const authenticatedPageGuide = await adapter.callTool({
+ name: "meta.guide",
+ input: { brief: "Build a Supabase authenticated account page" },
+ });
+ const designInputGuide = await adapter.callTool({
+ name: "meta.guide",
+ input: { brief: "Recreate this Figma design as a responsive page" },
+ });
+ const craftGuide = await adapter.callTool({
+ name: "meta.guide",
+ input: { brief: "Add a section that preserves this Craft project" },
+ });
const getComponentToolNames = (
getComponentDetails.structuredContent.data as {
tools: { name: string }[];
@@ -3676,6 +3768,57 @@ describe("project session mcp adapter", () => {
]),
})
);
+ expect(authenticatedPageGuide.structuredContent.data).toEqual(
+ expect.objectContaining({
+ workflow: expect.arrayContaining([
+ expect.stringContaining("existing auth resources"),
+ expect.stringContaining("Never place credentials"),
+ expect.stringContaining("signed-out, loading, signed-in"),
+ expect.stringContaining("not an authorization boundary"),
+ expect.stringContaining("call verify-bindings"),
+ ]),
+ tools: expect.arrayContaining([
+ expect.objectContaining({ name: "list-instances" }),
+ expect.objectContaining({ name: "insert-fragment" }),
+ expect.objectContaining({ name: "verify-bindings" }),
+ expect.objectContaining({ name: "audit" }),
+ ]),
+ })
+ );
+ expect(designInputGuide.structuredContent.data).toEqual(
+ expect.objectContaining({
+ workflow: expect.arrayContaining([
+ expect.stringContaining("Interpret the supplied design"),
+ expect.stringContaining(
+ "Before the first mutation, call list-breakpoints and list-design-tokens"
+ ),
+ expect.stringContaining("parallel design system"),
+ expect.stringContaining("semantic editable structure"),
+ expect.stringContaining("actual breakpoint ranges"),
+ expect.stringContaining("Run rendered audit"),
+ ]),
+ tools: expect.arrayContaining([
+ expect.objectContaining({ name: "list-breakpoints" }),
+ expect.objectContaining({ name: "components.search" }),
+ expect.objectContaining({ name: "insert-fragment" }),
+ expect.objectContaining({ name: "attach-design-token" }),
+ expect.objectContaining({ name: "update-styles" }),
+ ]),
+ })
+ );
+ expect(craftGuide.structuredContent.data).toEqual(
+ expect.objectContaining({
+ workflow: expect.arrayContaining([
+ expect.stringContaining('"scopes":["craft"]'),
+ expect.stringContaining("do not add Craft"),
+ expect.stringContaining("only the first reported"),
+ expect.stringContaining("templateCompatibility"),
+ ]),
+ tools: expect.arrayContaining([
+ expect.objectContaining({ name: "audit" }),
+ ]),
+ })
+ );
});
test("rejects invalid focused discovery input with path-specific messages", async () => {
@@ -4944,11 +5087,13 @@ describe("project session mcp adapter", () => {
output: "current.png",
host: undefined,
port: undefined,
+ imageDomains: undefined,
source: undefined,
viewport: { width: 1440, height: 900 },
fullPage: true,
includeImageMetrics: false,
includeResourceMetrics: false,
+ includeContrastMetrics: false,
browser: "auto",
browserPath: undefined,
waitUntil: "networkidle",
@@ -5701,6 +5846,9 @@ describe("project session mcp adapter", () => {
const components = await adapter.readResource({
uri: "webstudio://project/components",
});
+ const componentsVerbose = await adapter.readResource({
+ uri: "webstudio://project/components?verbose=true",
+ });
expect(JSON.parse(status.contents[0]?.text ?? "{}")).toEqual(
expect.objectContaining({
@@ -5713,8 +5861,15 @@ describe("project session mcp adapter", () => {
})
);
expect(JSON.parse(tools.contents[0]?.text ?? "{}")).toEqual(
- expect.objectContaining({ tools: expect.any(Array) })
+ expect.objectContaining({
+ detail: "compact",
+ returnedCount: 20,
+ nextCursor: "20",
+ tools: expect.any(Array),
+ })
);
+ expect(tools.contents[0]?.text).not.toContain("inputSchema");
+ expect((tools.contents[0]?.text ?? "").length).toBeLessThan(16_000);
expect(JSON.parse(toolsOverview.contents[0]?.text ?? "{}")).toEqual(
expect.objectContaining({
usage: expect.stringContaining("Short tool overview"),
@@ -5722,7 +5877,7 @@ describe("project session mcp adapter", () => {
capabilities: expect.arrayContaining([
expect.objectContaining({
area: "content",
- tools: expect.arrayContaining(["delete-instance"]),
+ count: expect.any(Number),
}),
]),
})
@@ -5784,6 +5939,15 @@ describe("project session mcp adapter", () => {
namespaces: expect.objectContaining({
"@webstudio-is/sdk-components-react-radix": expect.any(Number),
}),
+ })
+ );
+ expect(componentOverviewData).not.toHaveProperty("components");
+ const compactComponents = JSON.parse(components.contents[0]?.text ?? "{}");
+ expect(compactComponents).toEqual(
+ expect.objectContaining({
+ detail: "compact",
+ returnedCount: 20,
+ nextCursor: "20",
components: expect.arrayContaining([
expect.objectContaining({
component: "@webstudio-is/sdk-components-react-radix:Accordion",
@@ -5794,14 +5958,17 @@ describe("project session mcp adapter", () => {
]),
})
);
- for (const component of componentOverviewData.components) {
+ for (const component of compactComponents.components) {
expect(component).not.toHaveProperty("contentModel");
expect(component).not.toHaveProperty("props");
expect(component).not.toHaveProperty("states");
}
- expect(JSON.parse(components.contents[0]?.text ?? "{}")).toEqual(
+ expect((components.contents[0]?.text ?? "").length).toBeLessThan(16_000);
+ expect(JSON.parse(componentsVerbose.contents[0]?.text ?? "{}")).toEqual(
expect.objectContaining({
source: "@webstudio-is/sdk-components-registry/metas",
+ detail: "verbose",
+ returnedCount: 20,
components: expect.arrayContaining([
expect.objectContaining({
component: "@webstudio-is/sdk-components-react-radix:Accordion",
@@ -5827,6 +5994,80 @@ describe("project session mcp adapter", () => {
).rejects.toThrow('Unknown MCP resource "webstudio://project/unknown".');
});
+ test("pages discovery resources without omissions or duplicate entries", async () => {
+ const adapter = createProjectSessionMcpCore({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation: createExecuteOperation(),
+ });
+ const readCatalog = async (
+ resource: "tools" | "components",
+ verbose: boolean
+ ) => {
+ const ids: string[] = [];
+ let cursor: string | undefined;
+ let total = 0;
+ do {
+ const query = new URLSearchParams({
+ limit: "13",
+ verbose: String(verbose),
+ ...(cursor === undefined ? {} : { cursor }),
+ });
+ const result = await adapter.readResource({
+ uri: `webstudio://project/${resource}?${query}`,
+ });
+ const data = JSON.parse(result.contents[0]?.text ?? "{}");
+ const entries = data[resource] as Array<{
+ name?: string;
+ component?: string;
+ }>;
+ expect(data.returnedCount).toBe(entries.length);
+ expect(entries.length).toBeLessThanOrEqual(13);
+ ids.push(
+ ...entries.map(({ name, component }) => name ?? component ?? "")
+ );
+ total = data.total;
+ cursor = data.nextCursor;
+ } while (cursor !== undefined);
+ expect(ids).toHaveLength(total);
+ expect(new Set(ids).size).toBe(ids.length);
+ return ids;
+ };
+
+ const compactTools = await readCatalog("tools", false);
+ const verboseTools = await readCatalog("tools", true);
+ const compactComponents = await readCatalog("components", false);
+ const verboseComponents = await readCatalog("components", true);
+
+ expect(compactTools).toEqual(verboseTools);
+ expect(compactTools).toEqual(adapter.listTools().map(({ name }) => name));
+ expect(compactComponents).toEqual(verboseComponents);
+ });
+
+ test("caps and validates discovery resource pagination", async () => {
+ const adapter = createProjectSessionMcpCore({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation: createExecuteOperation(),
+ });
+ const capped = await adapter.readResource({
+ uri: "webstudio://project/tools?limit=500",
+ });
+ const cappedData = JSON.parse(capped.contents[0]?.text ?? "{}");
+ expect(cappedData.returnedCount).toBeLessThanOrEqual(50);
+
+ await expect(
+ adapter.readResource({
+ uri: "webstudio://project/tools?cursor=invalid",
+ })
+ ).rejects.toThrow("Invalid webstudio://project/tools cursor");
+ await expect(
+ adapter.readResource({
+ uri: "webstudio://project/components?limit=0",
+ })
+ ).rejects.toThrow("limit must be at least 1");
+ });
+
test("connects through the official MCP SDK and exposes discovery", async () => {
const server = await createProjectSessionMcpServer({
operations: publicMcpOperations,
@@ -5954,10 +6195,12 @@ describe("project session mcp adapter", () => {
});
test("sends sparse protocol-native startup logging after initialization", async () => {
+ const onInitialized = vi.fn();
const server = await createProjectSessionMcpServer({
operations: publicMcpOperations,
createProjectSession: createSessionFactory(),
executeOperation: createExecuteOperation(),
+ onInitialized,
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
@@ -5985,6 +6228,8 @@ describe("project session mcp adapter", () => {
data: expect.stringContaining("ready with"),
},
]);
+ expect(onInitialized).toHaveBeenCalledOnce();
+ expect(onInitialized).toHaveBeenCalledWith("test-client");
} finally {
await client.close();
await server.close();
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index 1abad49505..31d681422e 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -76,8 +76,6 @@ import {
} from "./runtime/errors";
import { z } from "zod";
-export { paginateOutput, projectOutput } from "./runtime/output";
-
type PublicMcpOperationMethod = "query" | "mutation";
type PublicMcpOperationPermit = BuilderApiCapability;
@@ -136,6 +134,7 @@ export type ProjectSessionScreenshotInput = {
fullPage?: boolean;
includeImageMetrics?: boolean;
includeResourceMetrics?: boolean;
+ includeContrastMetrics?: boolean;
browser: ScreenshotBrowser;
browserPath?: string;
waitUntil?: ScreenshotWaitUntil;
@@ -220,6 +219,16 @@ export type ProjectSessionScreenshotResult = {
duration: number;
renderBlockingStatus?: string;
}>;
+ contrasts?: Array<{
+ instanceId: string;
+ tagName: string;
+ foreground: string;
+ background: string;
+ ratio: number;
+ requiredRatio: 3 | 4.5;
+ fontSize: number;
+ fontWeight: number;
+ }>;
};
};
@@ -930,6 +939,12 @@ const screenshotInputSchema = {
description:
"Include sanitized Resource Timing transfer and render-blocking metadata. Rendered audit enables this automatically; omit for compact ordinary screenshots.",
},
+ includeContrastMetrics: {
+ type: "boolean",
+ default: false,
+ description:
+ "Include only statically resolvable opaque text/background contrast measurements. Rendered accessibility audit enables this automatically.",
+ },
browser: {
type: "string",
enum: screenshotBrowserChoices,
@@ -1305,7 +1320,7 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
"preview.status": [{}],
"preview.stop": [{}],
status: [{}, { verbose: true }],
- "list-pages": [{ includeFolders: true }],
+ "list-pages": [{ limit: 20 }],
"get-page-by-path": [{ path: "/pricing" }],
"list-instances": [{ pagePath: "/", maxDepth: 3 }],
"inspect-instance": [
@@ -2283,6 +2298,7 @@ type ProjectSessionMcpStructuredContent =
data: unknown;
meta: {
session?: ReturnType<typeof serializeProjectSessionMeta>;
+ next?: string[];
};
}
| {
@@ -2291,6 +2307,7 @@ type ProjectSessionMcpStructuredContent =
error: McpStructuredError;
meta: {
session?: ReturnType<typeof serializeProjectSessionMeta>;
+ next?: string[];
};
};
@@ -2298,7 +2315,7 @@ class ProjectSessionMcpCheckpointError extends Error {
code = "CHECKPOINT_REQUIRED";
}
-type ProjectSessionMcpCheckpoint = {
+export type ProjectSessionMcpCheckpoint = {
tool: string;
message: string;
nextCommand?: string;
@@ -2404,7 +2421,7 @@ const toMetaResult = (data: unknown): ProjectSessionMcpToolResult => {
};
};
-const getMcpCheckpoint = (
+export const getProjectSessionMcpCheckpoint = (
tool: string,
data: unknown
): ProjectSessionMcpCheckpoint | undefined => {
@@ -3273,7 +3290,11 @@ const filterCapabilities = (tools: readonly ProjectSessionMcpTool[]) => {
return capabilities;
};
-const startupGuidance = readProjectBuildDoc("mcp-startup-guidance").trim();
+const startupGuidance = [
+ "For any multi-step authoring task, first call meta.guide with the user's objective and follow its complete workflow, including final audit, preview, and screenshot steps.",
+ "Mutation responses can include meta.next. Treat those steps as required before reporting completion.",
+ readProjectBuildDoc("mcp-startup-guidance").trim(),
+].join("\n\n");
const formatExpressionMethods = (methods: ReadonlySet<string>) =>
[...methods]
.sort((left, right) => left.localeCompare(right))
@@ -3291,6 +3312,21 @@ const expressionsGuide = readProjectBuildDoc("expressions")
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.";
+const bindingVerificationWriteNamespaces = new Set([
+ "props",
+ "dataSources",
+ "resources",
+]);
+
+const visualVerificationWriteNamespaces = new Set([
+ "pages",
+ "instances",
+ "props",
+ "styles",
+ "styleSources",
+ "styleSourceSelections",
+]);
+
const getComponentStateUsage = (
states:
| readonly {
@@ -3388,10 +3424,8 @@ const getComponentCatalog = () => ({
.sort((left, right) => left.component.localeCompare(right.component)),
});
-const getComponentCatalogOverview = () => {
- const categories = new Map<string, number>();
- const namespaces = new Map<string, number>();
- const components = [...componentMetas.entries()]
+const getCompactComponentCatalogEntries = () =>
+ [...componentMetas.entries()]
.filter(
([_component, meta]) =>
isComponentMetaUnavailableInCatalog(meta) === false
@@ -3400,8 +3434,6 @@ const getComponentCatalogOverview = () => {
const [parsedNamespace, exportName] = parseComponentName(component);
const namespace = parsedNamespace ?? "global";
const category = meta.category ?? "uncategorized";
- namespaces.set(namespace, (namespaces.get(namespace) ?? 0) + 1);
- categories.set(category, (categories.get(category) ?? 0) + 1);
return {
component,
exportName,
@@ -3411,14 +3443,22 @@ const getComponentCatalogOverview = () => {
};
})
.sort((left, right) => left.component.localeCompare(right.component));
+
+const getComponentCatalogOverview = () => {
+ const categories = new Map<string, number>();
+ const namespaces = new Map<string, number>();
+ const components = getCompactComponentCatalogEntries();
+ for (const { category, namespace } of components) {
+ namespaces.set(namespace, (namespaces.get(namespace) ?? 0) + 1);
+ categories.set(category, (categories.get(category) ?? 0) + 1);
+ }
return {
source: "@webstudio-is/sdk-components-registry/metas",
usage:
- 'Short component overview. Prefer MCP tools components.list({"source":"all"}), templates.list({}), components.search({"brief":"radix select"}), and components.get({"component":"@webstudio-is/sdk-components-react-radix:Select"}) for structured discovery. Read webstudio://project/components only when you need the full catalog.',
+ 'Short component overview. Prefer MCP tools components.list({"source":"all"}), templates.list({}), components.search({"brief":"radix select"}), and components.get({"component":"@webstudio-is/sdk-components-react-radix:Select"}) for structured discovery. Read the bounded webstudio://project/components catalog only when needed.',
count: components.length,
namespaces: Object.fromEntries([...namespaces.entries()].sort()),
categories: Object.fromEntries([...categories.entries()].sort()),
- components,
};
};
@@ -3532,7 +3572,7 @@ const getComponentSummary = () => {
}
return {
usage:
- "Use this structured summary before reading full component resources. Do not dump/parse webstudio://project/components for common discovery. Use components.list for shadcn-compatible registry items, components.search for search, templates.list for templates, and components.get/templates.get for one item.",
+ "Use this structured summary before paging through component resources. Do not dump/parse the whole component catalog. Prefer components.list for shadcn-compatible registry items, components.search for search, templates.list for templates, and components.get/templates.get for one item.",
total: entries.length,
namespaceCounts: Object.fromEntries([...namespaces.entries()].sort()),
templateComponents: entries
@@ -4253,12 +4293,12 @@ const getComponentDetails = (component: string) => {
const getToolCatalogOverview = (tools: readonly ProjectSessionMcpTool[]) => ({
usage:
- 'Short tool overview. Do one small discovery step, then act. Start with meta.index or meta.guide({"brief":"Create a pricing page"}). Use meta.get_more_tools({"tools":["insert-fragment"]}) for the primary authored/styled insertion tool. Read webstudio://project/tools only when you need the full catalog.',
+ 'Short tool overview. Do one small discovery step, then act. Start with meta.index or meta.guide({"brief":"Create a pricing page"}). Use meta.get_more_tools({"tools":["insert-fragment"]}) for exact details, or read the bounded webstudio://project/tools catalog.',
count: tools.length,
capabilities: filterCapabilities(tools).map((capability) => ({
area: capability.area,
goal: capability.goal,
- tools: capability.tools,
+ count: capability.tools.length,
})),
});
@@ -4285,7 +4325,7 @@ const getMetaIndex = (
overview:
"Do not call every discovery tool up front. Use this meta.index response for orientation, then call at most one focused discovery tool before acting.",
tools:
- 'Use meta.get_more_tools({"tools":["insert-fragment"]}) for the primary authored/styled insertion tool. Use {"brief":"style updates"} only for search. Read webstudio://project/tools only when the full operation catalog is necessary.',
+ 'Use meta.get_more_tools({"tools":["insert-fragment"]}) for the primary authored/styled insertion tool. Use {"brief":"style updates"} only for search. Page through webstudio://project/tools only when broader operation discovery is necessary.',
insertFragment:
'Primary authored/styled insertion command shape: node 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">Section title</ws.element><ws.element ws:tag="p">Section copy.</ws.element></ws.element>"}\' --dry-run. Use parentInstanceId, not parentId. Use Webstudio components/helpers such as ws.element, radix.*, css, token, expression, and ActionValue. Use ws:style={css`...`} for Webstudio-native CSS, or style={{ padding: 24 }} for React-style object syntax converted into editable Webstudio styles. Use node packages/cli/local.js mcp single-op-call insert-fragment only when you need the explicit MCP form.',
resources:
@@ -4323,57 +4363,148 @@ const getMetaIndex = (
};
};
+const metaGoalGuides = [
+ {
+ pattern: /json\s*-?\s*ld|structured\s+data/i,
+ tools: [
+ "components.get",
+ "list-instances",
+ "insert-component",
+ "update-props",
+ "audit",
+ ],
+ workflow: [
+ 'Call components.get with {"component":"JsonLd"}; do not use update-page custom metadata for JSON-LD.',
+ "Find the page HeadSlot instance with list-instances.",
+ 'Insert JsonLd under HeadSlot with insert-component, then set code with update-props using type "string" and a compact JSON object or array string.',
+ 'Run audit with {"scopes":["seo"],"pagePath":"<path>"} and fix any JSON-LD finding.',
+ ],
+ },
+ {
+ pattern:
+ /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,
+ tools: [
+ "components.get",
+ "list-variables",
+ "list-resources",
+ "insert-collection",
+ "inspect-instance",
+ "audit",
+ ],
+ workflow: [
+ "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.",
+ "Call insert-collection once with the complete iterable and one repeated-item JSX root. Use expression`collectionItem.name` and expression`collectionItemKey` inside the item fragment; the operation creates and binds private parameters atomically.",
+ "Wrap multiple repeated sibling instances in one ws.element. Do not create, replace, or delete Collection parameter records manually.",
+ "Verify that every array/object entry renders once. For repeated Radix items, bind a stable unique id or slug to required value props.",
+ ],
+ },
+ {
+ pattern:
+ /\bexpressions?\b|computed\s+(?:text|value|prop|metadata|url)|dynamic\s+(?:text|prop|binding)/i,
+ tools: [
+ "list-variables",
+ "list-resources",
+ "list-texts",
+ "inspect-instance",
+ "update-text",
+ "bind-props",
+ "update-resource",
+ ],
+ workflow: [
+ "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.",
+ ],
+ },
+ {
+ pattern:
+ /authenticated?\s+(?:page|route|screen)|(?:supabase|firebase)\s+auth|sign(?:ed)?[- ]?(?:in|out)|login\s+(?:page|flow)|user\s+session/i,
+ tools: [
+ "get-project-settings",
+ "list-resources",
+ "list-variables",
+ "list-instances",
+ "create-page",
+ "create-resource",
+ "create-variable",
+ "insert-fragment",
+ "bind-props",
+ "verify-bindings",
+ "update-page",
+ "preview.start",
+ "screenshot",
+ "audit",
+ ],
+ workflow: [
+ "Inspect the project's existing auth resources, variables, embeds, page settings, and agent instructions before choosing a provider workflow. Reuse that convention; do not add a second auth system implicitly.",
+ "Never place credentials, service-role keys, refresh tokens, private session values, or authenticated response bodies in project data, command output, screenshots, agent instructions, or error reports. Ask the user to configure secrets in the provider/server environment.",
+ "Model explicit signed-out, loading, signed-in, and failed-auth UI states with ordinary components and bindings. Use page basic auth only when the user asks for Webstudio's fixed login/password gate; it is not Supabase or Firebase authentication.",
+ "Use focused resources and variables for public client configuration and session-shaped data. Keep authorization enforcement and privileged provider calls server-side; a hidden Builder element is not an authorization boundary.",
+ "After creating or changing authentication expressions, call verify-bindings for the account page and resolve every validity, scope, and reference finding before previewing.",
+ "Preview and verify every auth state with non-secret fixture data, then audit the route. Do not claim the real provider flow works until redirects, session refresh, failure handling, and protected data access are exercised in its configured environment.",
+ ],
+ },
+ {
+ pattern:
+ /(?:figma|wireframe|screenshot|design\s*(?:guide|input|file)|design\.md|inception).*(?:page|site|build|implement|recreate)|(?:build|implement|recreate).*(?:figma|wireframe|screenshot|design\s*(?:guide|input|file)|design\.md|inception)/i,
+ tools: [
+ "list-pages",
+ "list-breakpoints",
+ "list-variables",
+ "list-design-tokens",
+ "list-style-sources",
+ "attach-design-token",
+ "list-assets",
+ "components.search",
+ "create-page",
+ "insert-fragment",
+ "update-styles",
+ "upload-asset",
+ "preview.start",
+ "screenshot",
+ "screenshot.diff",
+ "audit",
+ ],
+ workflow: [
+ "Interpret the supplied design before mutating: identify page sections, responsive behavior, reusable patterns, assets, typography, color, spacing, and interaction states. Ask for missing source assets rather than inventing brand-critical content.",
+ "Before the first mutation, call list-breakpoints and list-design-tokens. Reuse the returned breakpoint ids and attach relevant token ids to the new instances; do not continue with disconnected local copies when matching tokens exist.",
+ "Inspect the target project's pages, variables, design tokens, style sources, components, and assets. Reuse exact existing values and patterns; do not create a parallel design system from approximate screenshot colors or spacing.",
+ "Attach existing design tokens to the new page's instances when they represent the intended typography, color, or other shared style. Reusing only the token's current raw value creates a disconnected local copy.",
+ "Create semantic editable structure with insert-fragment and known components. Use assets for real imagery and text/controls for real content; do not flatten the design into one image or absolute-position every element.",
+ "Implement responsive behavior inside the project's actual breakpoint ranges. Capture one familiar desktop and mobile viewport, plus one representative viewport for any distinct intermediate breakpoint behavior.",
+ "Run rendered audit and inspect screenshots after each bounded page section. Iterate on hierarchy, overflow, wrapping, image choice, spacing, and states; visual similarity is evidence, not permission to discard accessibility or project conventions.",
+ ],
+ },
+ {
+ pattern: /\bcraft\b/i,
+ tools: [
+ "audit",
+ "list-variables",
+ "list-design-tokens",
+ "list-style-sources",
+ "list-pages",
+ "update-styles",
+ ],
+ workflow: [
+ 'Run audit with {"scopes":["craft"]} before changing the project. Use profileStatuses for the detected profile, source provenance, next action, preservation guidance, and template compatibility.',
+ "If Craft is not detected, do not add Craft variables, tokens, or templates unless the user explicitly asks to adopt Craft.",
+ "For partial or modified Craft projects, apply only the first reported missing or incompatible requirement, preserve project-specific values and non-Craft styles, then rerun the Craft audit.",
+ "Use a Craft-dependent template only when templateCompatibility is compatible; requires-review means repair or explicitly resolve the mismatch first.",
+ ],
+ },
+] as const;
+
const getMetaGuide = (
brief: string,
tools: readonly ProjectSessionMcpTool[],
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(
- [
- "components.get",
- "list-instances",
- "insert-component",
- "update-props",
- "audit",
- ],
- tools
- )
- : isCollectionGoal
- ? getExactTools(
- [
- "components.get",
- "list-variables",
- "list-resources",
- "insert-collection",
- "inspect-instance",
- "audit",
- ],
- 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 goalGuide = metaGoalGuides.find(({ pattern }) => pattern.test(brief));
+ const matches =
+ goalGuide === undefined
+ ? getMatchingTools(brief, tools).slice(0, 12)
+ : getExactTools(goalGuide.tools, tools);
const canVerifyVisually =
tools.some((tool) => tool.name === "preview.start") &&
tools.some((tool) => tool.name === "screenshot");
@@ -4385,30 +4516,7 @@ const getMetaGuide = (
delegatedAgentRule:
"Do not spend the whole phase on discovery. If you are delegated/non-streaming and 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 before the next MCP command.",
workflow: [
- ...(isJsonLdGoal
- ? [
- 'Call components.get with {"component":"JsonLd"}; do not use update-page custom metadata for JSON-LD.',
- "Find the page HeadSlot instance with list-instances.",
- 'Insert JsonLd under HeadSlot with insert-component, then set code with update-props using type "string" and a compact JSON object or array string.',
- 'Run audit with {"scopes":["seo"],"pagePath":"<path>"} and fix any JSON-LD finding.',
- ]
- : []),
- ...(isCollectionGoal
- ? [
- "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.",
- "Call insert-collection once with the complete iterable and one repeated-item JSX root. Use expression`collectionItem.name` and expression`collectionItemKey` inside the item fragment; the operation creates and binds private parameters atomically.",
- "Wrap multiple repeated sibling instances in one ws.element. Do not create, replace, or delete Collection parameter records manually.",
- "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.",
- ]
- : []),
+ ...(goalGuide?.workflow ?? []),
"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)
@@ -4486,8 +4594,7 @@ const designSystemWorkflowPhases: Record<
purpose:
"Identify exactly one target page and return its page id and root instance id. Create it only if lookup proves it is missing.",
allowedTools: ["create-page", "list-pages", "get-page-by-path"],
- commandPattern:
- "node packages/cli/local.js list-pages '{\"includeFolders\":true}'",
+ commandPattern: "node packages/cli/local.js list-pages '{\"limit\":20}'",
fallbackCommandPattern:
'node packages/cli/local.js create-page \'{"path":"/design-system","name":"Design System"}\'',
expectedReturn: [
@@ -4619,6 +4726,72 @@ const serializeToolDetails = (tool: ProjectSessionMcpTool) => ({
annotations: tool.annotations,
});
+const serializeCompactTool = (tool: ProjectSessionMcpTool) => ({
+ name: tool.name,
+ description:
+ tool.description.length <= 240
+ ? tool.description
+ : `${tool.description.slice(0, 239)}…`,
+ method: tool.annotations.method,
+ requiredInputFields: tool.annotations.requiredInputFields,
+});
+
+const maxDiscoveryResourcePageSize = 50;
+const defaultDiscoveryResourcePageSize = 20;
+
+const getDiscoveryResourceInput = (uri: string, resourceUri: string) => {
+ const url = new URL(uri);
+ const baseUri = `${url.protocol}//${url.host}${url.pathname}`;
+ if (baseUri !== resourceUri) {
+ return;
+ }
+ for (const name of url.searchParams.keys()) {
+ if (["cursor", "limit", "verbose"].includes(name) === false) {
+ throw new Error(`Unknown ${resourceUri} parameter "${name}".`);
+ }
+ }
+ const cursor = url.searchParams.get("cursor");
+ if (cursor !== null && /^(0|[1-9]\d*)$/.test(cursor) === false) {
+ throw new Error(`Invalid ${resourceUri} cursor "${cursor}".`);
+ }
+ const rawLimit = url.searchParams.get("limit");
+ if (rawLimit !== null && /^(0|[1-9]\d*)$/.test(rawLimit) === false) {
+ throw new Error(`Invalid ${resourceUri} limit "${rawLimit}".`);
+ }
+ const requestedLimit =
+ rawLimit === null
+ ? defaultDiscoveryResourcePageSize
+ : Number.parseInt(rawLimit, 10);
+ if (requestedLimit < 1) {
+ throw new Error(`${resourceUri} limit must be at least 1.`);
+ }
+ const rawVerbose = url.searchParams.get("verbose");
+ if (rawVerbose !== null && rawVerbose !== "true" && rawVerbose !== "false") {
+ throw new Error(`${resourceUri} verbose must be true or false.`);
+ }
+ return {
+ offset: cursor === null ? 0 : Number.parseInt(cursor, 10),
+ limit: Math.min(requestedLimit, maxDiscoveryResourcePageSize),
+ verbose: rawVerbose === "true",
+ };
+};
+
+const paginateDiscoveryResource = (
+ items: readonly unknown[],
+ input: NonNullable<ReturnType<typeof getDiscoveryResourceInput>>
+) => {
+ const page = items.slice(input.offset, input.offset + input.limit);
+ return {
+ total: items.length,
+ returnedCount: page.length,
+ nextCursor:
+ input.offset + page.length < items.length
+ ? String(input.offset + page.length)
+ : undefined,
+ page,
+ };
+};
+
const getMoreTools = (
brief: string,
toolNames: readonly string[],
@@ -4705,27 +4878,28 @@ export const listProjectSessionMcpResources =
uri: "webstudio://project/tools-overview",
name: "Webstudio operation tools overview",
description:
- "Small operation overview grouped by capability area. Use before reading the full tool catalog.",
+ "Small operation overview grouped by capability area. Use before paging through the tool catalog.",
mimeType: "application/json",
},
{
uri: "webstudio://project/tools",
name: "Webstudio operation tools",
- description: "Catalog-derived MCP tools available for the project.",
+ description:
+ "Bounded tool catalog. Supports cursor, limit (maximum 50), and verbose query parameters.",
mimeType: "application/json",
},
{
uri: "webstudio://project/components-overview",
name: "Webstudio components overview",
description:
- "Small component overview with ids, labels, namespaces, and categories. Use before reading the full component catalog.",
+ "Small component overview with namespace and category counts. Use before paging through the component catalog.",
mimeType: "application/json",
},
{
uri: "webstudio://project/components",
name: "Webstudio components",
description:
- "Registry-derived component catalog with props, states, and content model composition constraints.",
+ "Bounded component catalog. Supports cursor, limit (maximum 50), and verbose query parameters.",
mimeType: "application/json",
},
{
@@ -4756,12 +4930,14 @@ const toCallResult = (
options: {
verboseSession?: boolean;
error?: { code: string; message: string };
+ next?: string[];
} = {}
): ProjectSessionMcpToolResult => {
const meta = {
session: serializeProjectSessionMeta(envelope, {
verbose: options.verboseSession,
}),
+ ...(options.next === undefined ? {} : { next: options.next }),
};
const structuredContent: ProjectSessionMcpStructuredContent =
options.error === undefined
@@ -4983,6 +5159,7 @@ const getScreenshotInput = (input: unknown): ProjectSessionScreenshotInput => {
fullPage: input.fullPage === true,
includeImageMetrics: input.includeImageMetrics === true,
includeResourceMetrics: input.includeResourceMetrics === true,
+ includeContrastMetrics: input.includeContrastMetrics === true,
browser,
browserPath:
typeof input.browserPath === "string" ? input.browserPath : undefined,
@@ -5201,22 +5378,7 @@ const getImportInput = (input: unknown): ProjectSessionImportInput => {
};
};
-export const createProjectSessionMcpCore = <Command extends string = string>({
- operations,
- createProjectSession,
- executeOperation,
- importProject,
- captureScreenshot,
- capturePageScreenshots,
- diffScreenshots,
- installOcr,
- startPreview,
- getPreviewStatus,
- stopPreview,
- guidance,
- reportToolProgress,
- storeRenderedAuditArtifacts,
-}: {
+type ProjectSessionMcpCoreOptions<Command extends string> = {
operations: readonly (PublicMcpOperation & { command: Command })[];
createProjectSession: CreateProjectSession;
executeOperation: ExecuteMcpOperation<Command>;
@@ -5233,14 +5395,31 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
storeRenderedAuditArtifacts?: (
manifest: RenderedAuditArtifactManifest
) => Promise<string>;
-}) => {
+};
+
+export const createProjectSessionMcpCore = <Command extends string = string>({
+ operations,
+ createProjectSession,
+ executeOperation,
+ importProject,
+ captureScreenshot,
+ capturePageScreenshots,
+ diffScreenshots,
+ installOcr,
+ startPreview,
+ getPreviewStatus,
+ stopPreview,
+ guidance,
+ reportToolProgress,
+ storeRenderedAuditArtifacts,
+}: ProjectSessionMcpCoreOptions<Command>) => {
let session: ReturnType<CreateProjectSession> | undefined;
let pendingCheckpoint: ProjectSessionMcpCheckpoint | undefined;
const toCheckpointedMetaResult = (
tool: string,
data: unknown
): ProjectSessionMcpToolResult => {
- pendingCheckpoint = getMcpCheckpoint(tool, data);
+ pendingCheckpoint = getProjectSessionMcpCheckpoint(tool, data);
return toMetaResult(data);
};
const operationByCommand = new Map(
@@ -5284,13 +5463,31 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
],
};
}
- if (uri === "webstudio://project/tools") {
+ const toolsInput = getDiscoveryResourceInput(
+ uri,
+ "webstudio://project/tools"
+ );
+ if (toolsInput !== undefined) {
+ const tools = listTools();
+ const serializedTools = toolsInput.verbose
+ ? tools.map(serializeToolDetails)
+ : tools.map(serializeCompactTool);
+ const { page, ...pagination } = paginateDiscoveryResource(
+ serializedTools,
+ toolsInput
+ );
return {
contents: [
{
uri,
mimeType: "application/json",
- text: JSON.stringify({ tools: listTools() }),
+ text: JSON.stringify({
+ usage:
+ "Use cursor to continue. Pass verbose=true for schemas and examples for this page only.",
+ detail: toolsInput.verbose ? "verbose" : "compact",
+ ...pagination,
+ tools: page,
+ }),
},
],
};
@@ -5306,13 +5503,34 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
],
};
}
- if (uri === "webstudio://project/components") {
+ const componentsInput = getDiscoveryResourceInput(
+ uri,
+ "webstudio://project/components"
+ );
+ if (componentsInput !== undefined) {
+ const compactCatalog = getComponentCatalogOverview();
+ const items = componentsInput.verbose
+ ? getComponentCatalog().components
+ : getCompactComponentCatalogEntries();
+ const { page, ...pagination } = paginateDiscoveryResource(
+ items,
+ componentsInput
+ );
return {
contents: [
{
uri,
mimeType: "application/json",
- text: JSON.stringify(getComponentCatalog()),
+ text: JSON.stringify({
+ source: "@webstudio-is/sdk-components-registry/metas",
+ usage:
+ "Use cursor to continue. Pass verbose=true for props, states, and composition details for this page only.",
+ detail: componentsInput.verbose ? "verbose" : "compact",
+ namespaces: compactCatalog.namespaces,
+ categories: compactCatalog.categories,
+ ...pagination,
+ components: page,
+ }),
},
],
};
@@ -5684,7 +5902,34 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
error: getRenderedAuditError(auditedEnvelope, isRenderedAudit),
});
}
- return toCallResult(envelope);
+ const needsBindingVerification = operation.writeNamespaces.some(
+ (namespace) => bindingVerificationWriteNamespaces.has(namespace)
+ );
+ const needsVisualVerification = operation.writeNamespaces.some(
+ (namespace) => visualVerificationWriteNamespaces.has(namespace)
+ );
+ const next = [
+ ...(needsBindingVerification
+ ? [
+ "After changing props, variables, or resources, run verify-bindings for the changed page or instance and resolve every finding.",
+ ]
+ : []),
+ ...(needsVisualVerification
+ ? [
+ "Before reporting completion, run audit for the changed page or project.",
+ ...(startPreview !== undefined && captureScreenshot !== undefined
+ ? [
+ "For visual changes, start a session preview and capture desktop and mobile screenshots before reporting completion.",
+ ]
+ : []),
+ ]
+ : []),
+ ];
+ return toCallResult(envelope, {
+ ...(operation.method !== "mutation" || dryRun || next.length === 0
+ ? {}
+ : { next }),
+ });
},
};
};
@@ -5770,25 +6015,12 @@ export const createProjectSessionMcpServer = async <
getErrorCode,
reportLog,
storeRenderedAuditArtifacts,
+ onInitialized,
toolHeartbeatIntervalMs = 10_000,
-}: {
- operations: readonly (PublicMcpOperation & { command: Command })[];
- createProjectSession: CreateProjectSession;
- executeOperation: ExecuteMcpOperation<Command>;
- importProject?: ImportProject;
- captureScreenshot?: CaptureScreenshot;
- capturePageScreenshots?: CapturePageScreenshots;
- diffScreenshots?: DiffScreenshots;
- installOcr?: InstallOcr;
- startPreview?: StartPreview;
- getPreviewStatus?: GetPreviewStatus;
- stopPreview?: StopPreview;
- guidance?: ProjectSessionMcpGuidance;
+}: Omit<ProjectSessionMcpCoreOptions<Command>, "reportToolProgress"> & {
getErrorCode?: McpErrorCodeResolver;
reportLog?: (level: McpLogLevel, message: string) => void;
- storeRenderedAuditArtifacts?: (
- manifest: RenderedAuditArtifactManifest
- ) => Promise<string>;
+ onInitialized?: (clientName: string | undefined) => void;
toolHeartbeatIntervalMs?: number;
}) => {
const server = new Server(
@@ -5830,6 +6062,7 @@ export const createProjectSessionMcpServer = async <
});
server.oninitialized = () => {
+ onInitialized?.(server.getClientVersion()?.name);
sendLog(
"info",
`ready with ${core.listTools().length} tools; use tools/list, meta.index, or webstudio://project/guide`
diff --git a/packages/project-build/src/project-session.test.ts b/packages/project-build/src/project-session.test.ts
index e7d8363567..302fc064e7 100644
--- a/packages/project-build/src/project-session.test.ts
+++ b/packages/project-build/src/project-session.test.ts
@@ -630,6 +630,106 @@ describe("project session", () => {
).toMatchObject({ component: "ws:collection" });
});
+ test("plans and commits one runtime UI integration that survives refresh", async () => {
+ let remote = createSnapshot();
+ const storage = createStorage(createPersistedSnapshot());
+ const transport = createTransport(remote);
+ transport.fetchNamespaces = async (input) => {
+ transport.loadedNamespaces.push([...input.namespaces]);
+ return remote;
+ };
+ let serverGeneratedId = 0;
+ transport.executeServerOperation = async <Result>(input: {
+ operationId: string;
+ input: unknown;
+ }) => {
+ transport.serverOperations.push(input);
+ const mutation =
+ await executeBuilderRuntimeOperation<BuilderRuntimeMutation>({
+ id: input.operationId,
+ state: remote.state,
+ input: input.input,
+ context: {
+ projectVersion: remote.version,
+ createId: () => `runtime-ui-id-${serverGeneratedId++}`,
+ },
+ });
+ const transaction: BuilderPatchTransaction = {
+ id: `runtime-ui-transaction-${serverGeneratedId++}`,
+ payload: mutation.payload,
+ };
+ remote = {
+ ...remote,
+ version: remote.version + 1,
+ state: applyBuilderPatchTransactions(remote.state, [transaction]).state,
+ };
+ return mutation.result as Result;
+ };
+ const session = createSession({ storage, transport });
+ const input = {
+ parentInstanceId: "instance-root",
+ variables: [
+ {
+ name: "ResultsLabel",
+ value: { type: "string" as const, value: "Results" },
+ },
+ ],
+ resources: [
+ {
+ resource: {
+ name: "Results",
+ method: "get" as const,
+ url: "https://api.example.com/results",
+ headers: [],
+ },
+ dataSourceName: "Results",
+ exposeAsDataSource: true,
+ },
+ ],
+ structure: {
+ type: "collection" as const,
+ data: { type: "expression" as const, value: "Results.data" },
+ itemFragment: await parseWebstudioJsxFragment(
+ '<ws.element ws:tag="article">{expression`collectionItem.title`}</ws.element>'
+ ),
+ },
+ bindings: [],
+ retainedBehavior: [],
+ unsupportedConversions: [],
+ };
+
+ await session.initialize();
+ const planned = await session.mutate("runtimeUi.integrate", input, {
+ dryRun: true,
+ });
+ expect(planned.source).toBe("dry-run");
+ expect(planned.state.committed).toBe(false);
+ expect(planned.transaction?.payload).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ namespace: "resources" }),
+ expect.objectContaining({ namespace: "instances" }),
+ ])
+ );
+ expect(transport.commits).toHaveLength(0);
+
+ const committed = await session.mutate("runtimeUi.integrate", input);
+ expect(committed.state.committed).toBe(true);
+ const result = committed.result as {
+ created: { rootInstanceIds: string[] };
+ editableStructure: { usesCollection: boolean };
+ };
+ expect(result.editableStructure.usesCollection).toBe(true);
+ const collectionId = result.created.rootInstanceIds[0];
+ expect(remote.state.instances?.get(collectionId)).toMatchObject({
+ component: "ws:collection",
+ });
+
+ await session.refresh(["instances", "props", "dataSources", "resources"]);
+ expect(
+ storage.saved.at(-1)?.state.instances?.get(collectionId)
+ ).toMatchObject({ component: "ws:collection" });
+ });
+
test("commits remotely before applying mutation locally", async () => {
const storage = createStorage(createPersistedSnapshot());
const transport = createTransport();
diff --git a/packages/project-build/src/runtime.ts b/packages/project-build/src/runtime.ts
index f840337f09..db1579cab1 100644
--- a/packages/project-build/src/runtime.ts
+++ b/packages/project-build/src/runtime.ts
@@ -1,6 +1,7 @@
export * from "./build-integrity";
export * from "./shared/graph-utils";
export * from "./runtime/assets";
+export * from "./runtime/binding-verification";
export * from "./runtime/auth";
export * from "./runtime/block";
export * from "./runtime/breakpoints";
@@ -22,6 +23,7 @@ export * from "./runtime/instances";
export * from "./runtime/lookup";
export * from "./runtime/matcher";
export * from "./runtime/mutation";
+export * from "./runtime/output";
export * from "./runtime/page-copy";
export * from "./runtime/pages";
export * from "./runtime/project-settings";
diff --git a/packages/project-build/src/runtime/assets.test.ts b/packages/project-build/src/runtime/assets.test.ts
index e2024daa5f..af912db4b7 100644
--- a/packages/project-build/src/runtime/assets.test.ts
+++ b/packages/project-build/src/runtime/assets.test.ts
@@ -323,6 +323,11 @@ describe("asset runtime operations", () => {
usages: [
{ namespace: "props", instanceId: "body", path: ["prop", "value"] },
],
+ detail: "compact",
+ total: 1,
+ returnedCount: 1,
+ nextCursor: null,
+ filters: { assetId: "asset" },
});
});
diff --git a/packages/project-build/src/runtime/assets.ts b/packages/project-build/src/runtime/assets.ts
index 05e22142d4..90c3c9cf46 100644
--- a/packages/project-build/src/runtime/assets.ts
+++ b/packages/project-build/src/runtime/assets.ts
@@ -954,20 +954,25 @@ export const findAssetUsage = (
BuilderState,
"assets" | "pages" | "props" | "styles" | "resources" | "dataSources"
>,
- input: { assetId: string }
+ input: { assetId: string } & PaginatedOutputInput
) => {
const assets = Array.from(getRequiredAssets(state).values());
const asset = findAsset(assets, input.assetId);
if (asset === undefined) {
return throwBuilderRuntimeError("NOT_FOUND", "Asset not found");
}
- return {
- usages: createAssetUsageList({
+ const { items, ...pagination } = paginateOutput({
+ items: createAssetUsageList({
asset,
assets,
build: getRequiredAssetReferenceBuild(state),
}),
- };
+ cursor: input.cursor,
+ limit: input.limit,
+ filters: { assetId: input.assetId },
+ verbose: input.verbose,
+ });
+ return { usages: items, ...pagination };
};
export const replaceAsset = (
diff --git a/packages/project-build/src/runtime/audit.test.ts b/packages/project-build/src/runtime/audit.test.ts
index f646a30e89..94df686893 100644
--- a/packages/project-build/src/runtime/audit.test.ts
+++ b/packages/project-build/src/runtime/audit.test.ts
@@ -8,7 +8,13 @@ import {
import { executeBuilderRuntimeOperation } from "./registry";
import { setImageDescriptions } from "./assets";
import { analyzeProject, searchProject } from "./search";
-import { audit, auditRuleId, auditRules, normalizeAuditFinding } from "./audit";
+import {
+ audit,
+ auditRuleId,
+ auditRules,
+ normalizeAuditFinding,
+ renderedAuditCheck,
+} from "./audit";
import type { BuilderState } from "../state/builder-state";
import { applyBuilderPatchTransactions } from "../state/patch";
import {
@@ -18,6 +24,84 @@ import {
} from "./runtime.test-fixtures";
describe("project audit and analysis", () => {
+ test("keeps rendered geometry bounded and confidence semantics explicit", () => {
+ const geometryIssue = {
+ instanceId: "content",
+ message: "Content is clipped.",
+ evidence: { clippedX: true },
+ };
+ const check = {
+ pageId: "home",
+ pagePath: "/",
+ viewport: { width: 375, height: 812 },
+ screenshotPath: "/tmp/home.webp",
+ layout: {
+ viewportWidth: 375,
+ viewportHeight: 812,
+ contentWidth: 375,
+ contentHeight: 1200,
+ horizontalOverflow: false,
+ elementGeometry: {
+ total: 0,
+ sampled: 0,
+ truncated: false,
+ elements: [],
+ },
+ images: [],
+ resources: [],
+ },
+ issues: ["clipped-content"],
+ geometryIssues: [
+ {
+ ...geometryIssue,
+ kind: "clipped-content",
+ confidence: "exact",
+ },
+ ],
+ imageIssues: [],
+ resourceIssues: [],
+ };
+
+ expect(renderedAuditCheck.safeParse(check).success).toBe(true);
+ expect(
+ renderedAuditCheck.safeParse({
+ ...check,
+ geometryIssues: [
+ {
+ ...geometryIssue,
+ kind: "hidden-content",
+ confidence: "exact",
+ },
+ ],
+ }).success
+ ).toBe(false);
+ expect(
+ renderedAuditCheck.safeParse({
+ ...check,
+ layout: {
+ ...check.layout,
+ elementGeometry: {
+ total: 251,
+ sampled: 251,
+ truncated: false,
+ elements: Array.from({ length: 251 }, (_, index) => ({
+ instanceId: String(index),
+ tagName: "div",
+ x: 0,
+ y: 0,
+ width: 1,
+ height: 1,
+ visible: true,
+ clippedX: false,
+ clippedY: false,
+ overlapsWith: [],
+ })),
+ },
+ },
+ }).success
+ ).toBe(false);
+ });
+
test("requires every emitted audit rule to be registered", () => {
expect(Object.keys(auditRules).sort()).toEqual(
[...auditRuleId.options].sort()
@@ -849,6 +933,9 @@ describe("project audit and analysis", () => {
searchProject(searchState, { query: "video.example.com" })
).toMatchObject({
total: 1,
+ returnedCount: 1,
+ nextCursor: null,
+ detail: "compact",
matches: [
{
kind: "prop",
@@ -2516,6 +2603,47 @@ describe("project audit and analysis", () => {
);
});
+ test("audits legacy selectors that escape scope and orphan breakpoints", () => {
+ const styles: NonNullable<BuilderState["styles"]> = new Map(state.styles);
+ styles.set("local:missing:color::hover, body", {
+ styleSourceId: "local",
+ breakpointId: "missing",
+ property: "color",
+ state: ":hover, body",
+ value: { type: "keyword", value: "red" },
+ });
+
+ const result = audit(
+ { ...state, styles },
+ { scopes: ["styles"], verbose: true },
+ { projectVersion: 1 }
+ );
+
+ expect(result.findings).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ ruleId: "invalid-style-state-selector",
+ severity: "warning",
+ location: expect.objectContaining({
+ styleSourceId: "local",
+ breakpointId: "missing",
+ stateSelector: ":hover, body",
+ styleProperty: "color",
+ }),
+ }),
+ expect.objectContaining({
+ ruleId: "orphan-style-breakpoint",
+ severity: "warning",
+ location: expect.objectContaining({
+ styleSourceId: "local",
+ breakpointId: "missing",
+ styleProperty: "color",
+ }),
+ }),
+ ])
+ );
+ });
+
test("audits disabled atomic CSS as a performance optimization", () => {
const result = audit(
{
diff --git a/packages/project-build/src/runtime/audit.ts b/packages/project-build/src/runtime/audit.ts
index b96a0572a3..68faab1521 100644
--- a/packages/project-build/src/runtime/audit.ts
+++ b/packages/project-build/src/runtime/audit.ts
@@ -15,6 +15,11 @@ import {
getAccessibleContentState,
isDynamicPropType,
} from "./accessibility-analysis";
+import {
+ analyzeCraftProfile,
+ craftProfile,
+ craftProfileStatus,
+} from "./craft-profile";
export const auditScope = z.enum([
"accessibility",
@@ -23,8 +28,13 @@ export const auditScope = z.enum([
"assets",
"styles",
"performance",
+ "craft",
]);
+const defaultAuditScopes = auditScope.options.filter(
+ (scope) => scope !== "craft"
+);
+
export const auditSeverity = z.enum(["error", "warning", "info"]);
export const auditContractVersion = 2 as const;
export const renderedAuditManifestVersion = 1 as const;
@@ -95,17 +105,25 @@ export const auditRuleId = z.enum([
"unused-breakpoint",
"duplicate-design-token-declarations",
"style-on-dom-transparent-component",
+ "invalid-style-state-selector",
+ "orphan-style-breakpoint",
"atomic-css-disabled",
+ "craft-not-detected",
+ "craft-missing-semantic-variables",
+ "craft-container-token-missing",
+ "craft-container-token-incompatible",
+ "craft-style-guide-page-missing",
]);
const auditScopeDescription = [
- "Audit scopes. Omit to run all scopes.",
+ "Audit scopes. Omit to run all standard scopes; Craft remains opt-in.",
"accessibility errors: missing-alt, missing-image-input-alt, missing-iframe-title, missing-accessible-name, missing-form-label, invalid-aria-role, missing-required-aria-role-property, role-interactive-not-focusable, aria-hidden-focusable, invalid-aria-state, invalid-aria-number, autoplay-media-with-sound, invalid-label-reference, duplicate-id, and missing-aria-reference; warnings: missing-image-description, unsupported-aria-role-property, positive-tabindex, missing-page-heading, skipped-heading-level, missing-main-landmark, and multiple-main-landmarks. Documentation: https://www.w3.org/WAI/WCAG22/understanding/.",
"security errors: non-get-resource-exposed-as-data-source; warning: target-blank-without-noopener. Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/noopener.",
"seo errors: empty-page-title, invalid-json-ld, and json-ld-in-custom-metadata; warnings: missing-page-description, empty-page-description, invalid-page-language, missing-social-image-asset, duplicate-page-title, duplicate-page-description, missing-json-ld-context, unknown-schema-org-type, deprecated-schema-org-type, unknown-schema-org-property, deprecated-schema-org-property, unsupported-schema-org-property, and incompatible-schema-org-value. Documentation: https://developers.google.com/search/docs/fundamentals/seo-starter-guide.",
"assets info: unused-asset. Documentation: https://docs.webstudio.is/university/foundations/anatomy-of-the-webstudio-builder.",
- "styles warning: style-on-dom-transparent-component; info: unused-design-token, unused-css-variable, unused-local-style-source, unused-breakpoint, and duplicate-design-token-declarations. Documentation: https://docs.webstudio.is/university/foundations/design-tokens.",
+ "styles warnings: style-on-dom-transparent-component, invalid-style-state-selector, and orphan-style-breakpoint; info: unused-design-token, unused-css-variable, unused-local-style-source, unused-breakpoint, and duplicate-design-token-declarations. Documentation: https://docs.webstudio.is/university/foundations/design-tokens.",
"performance info: atomic-css-disabled. Rendered checks add image loading/sizing, render-blocking resource, and legacy font-format evidence. Documentation: https://docs.webstudio.is/university/foundations/project-settings#atomic-css.",
+ "craft is an opt-in, read-only compatibility check and is excluded when scopes are omitted. Documentation: https://docs.webstudio.is/university/craft.",
].join(" ");
export const auditInput = z
@@ -152,6 +170,8 @@ export const auditLocation = z
cssVariableName: z.string().optional(),
cssVariableScope: z.string().optional(),
breakpointId: z.string().optional(),
+ stateSelector: z.string().optional(),
+ styleProperty: z.string().optional(),
resourceId: z.string().optional(),
dataSourceId: z.string().optional(),
htmlId: z.string().optional(),
@@ -208,13 +228,103 @@ export const manualAuditCheck = z.object({
export const renderedAuditIssueKind = z.enum([
"horizontal-overflow",
+ "clipped-content",
+ "hidden-content",
+ "overlapping-elements",
+ "cross-breakpoint-layout-change",
"broken-image",
"eager-below-fold-image",
"oversized-image",
"render-blocking-resource",
"legacy-font-format",
+ "low-text-contrast",
]);
+const renderedElementGeometry = z.object({
+ instanceId: z.string(),
+ tagName: z.string(),
+ x: z.number(),
+ y: z.number(),
+ width: z.number().nonnegative(),
+ height: z.number().nonnegative(),
+ visible: z.boolean(),
+ hiddenReason: z
+ .enum(["display", "visibility", "opacity", "hidden"])
+ .optional(),
+ clippedX: z.boolean(),
+ clippedY: z.boolean(),
+ overlapsWith: z.array(z.string()).max(5),
+});
+
+const renderedGeometryIssueBase = z.object({
+ instanceId: z.string(),
+ relatedInstanceId: z.string().optional(),
+ message: z.string(),
+ evidence: z.object({
+ clippedX: z.boolean().optional(),
+ clippedY: z.boolean().optional(),
+ hiddenReason: renderedElementGeometry.shape.hiddenReason,
+ sourceViewportWidth: z.number().int().positive().optional(),
+ targetViewportWidth: z.number().int().positive().optional(),
+ sourceVisible: z.boolean().optional(),
+ targetVisible: z.boolean().optional(),
+ sourceX: z.number().optional(),
+ targetX: z.number().optional(),
+ sourceWidth: z.number().nonnegative().optional(),
+ targetWidth: z.number().nonnegative().optional(),
+ }),
+});
+
+const renderedGeometryIssue = z.union([
+ renderedGeometryIssueBase.extend({
+ kind: z.literal("clipped-content"),
+ confidence: z.literal("exact"),
+ }),
+ renderedGeometryIssueBase.extend({
+ kind: z.enum([
+ "hidden-content",
+ "overlapping-elements",
+ "cross-breakpoint-layout-change",
+ ]),
+ confidence: z.literal("advisory"),
+ }),
+]);
+
+const renderedImageMetric = 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(),
+});
+
+const renderedResourceMetric = z.object({
+ pathname: z.string(),
+ initiatorType: z.string(),
+ transferSize: z.number().nonnegative(),
+ encodedBodySize: z.number().nonnegative(),
+ decodedBodySize: z.number().nonnegative(),
+ duration: z.number().nonnegative(),
+ renderBlockingStatus: z.string().optional(),
+});
+
+const renderedContrastMetric = z.object({
+ instanceId: z.string(),
+ tagName: z.string(),
+ foreground: z.string(),
+ background: z.string(),
+ ratio: z.number().positive(),
+ requiredRatio: z.union([z.literal(3), z.literal(4.5)]),
+ fontSize: z.number().positive(),
+ fontWeight: z.number().nonnegative(),
+});
+
export const renderedAuditCheck = z.object({
pageId: z.string(),
pagePath: z.string(),
@@ -230,65 +340,40 @@ export const renderedAuditCheck = z.object({
contentWidth: z.number().int().positive(),
contentHeight: z.number().int().positive(),
horizontalOverflow: z.boolean(),
- 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(),
- })
- ),
- resources: z.array(
- z.object({
- pathname: z.string(),
- initiatorType: z.string(),
- transferSize: z.number().nonnegative(),
- encodedBodySize: z.number().nonnegative(),
- decodedBodySize: z.number().nonnegative(),
- duration: z.number().nonnegative(),
- renderBlockingStatus: z.string().optional(),
- })
- ),
+ elementGeometry: z.object({
+ total: z.number().int().nonnegative(),
+ sampled: z.number().int().nonnegative().max(250),
+ truncated: z.boolean(),
+ elements: z.array(renderedElementGeometry).max(250),
+ }),
+ images: z.array(renderedImageMetric),
+ resources: z.array(renderedResourceMetric),
+ contrasts: z.array(renderedContrastMetric).optional(),
}),
issues: z.array(renderedAuditIssueKind),
+ geometryIssues: z.array(renderedGeometryIssue),
imageIssues: z.array(
- z.object({
+ renderedImageMetric.omit({ complete: true }).extend({
kind: z.enum([
"broken-image",
"eager-below-fold-image",
"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(),
})
),
resourceIssues: z.array(
- z.object({
+ renderedResourceMetric.extend({
kind: z.enum(["render-blocking-resource", "legacy-font-format"]),
- pathname: z.string(),
- initiatorType: z.string(),
- transferSize: z.number().nonnegative(),
- encodedBodySize: z.number().nonnegative(),
- decodedBodySize: z.number().nonnegative(),
- duration: z.number().nonnegative(),
- renderBlockingStatus: z.string().optional(),
})
),
+ contrastIssues: z
+ .array(
+ renderedContrastMetric.extend({
+ kind: z.literal("low-text-contrast"),
+ confidence: z.literal("exact"),
+ })
+ )
+ .optional(),
});
export const renderedAuditFailure = z.object({
@@ -355,6 +440,32 @@ export const renderedAuditArtifactManifestSummary = z.object({
screenshotCount: z.number().int().nonnegative(),
});
+const generatedBuildTotals = z.object({
+ fileCount: z.number().int().nonnegative(),
+ bytes: z.number().int().nonnegative(),
+ gzipBytes: z.number().int().nonnegative(),
+});
+
+export const generatedBuildMetrics = generatedBuildTotals.extend({
+ version: z.literal(1),
+ client: generatedBuildTotals,
+ server: generatedBuildTotals,
+ largestFiles: z
+ .array(
+ z.object({
+ path: z.string(),
+ bytes: z.number().int().nonnegative(),
+ gzipBytes: z.number().int().nonnegative(),
+ kind: z.enum(["script", "style", "image", "font", "other"]),
+ })
+ )
+ .max(20),
+});
+
+const generatedBuildSummary = generatedBuildMetrics.omit({
+ largestFiles: true,
+});
+
export const renderedAuditFailureSummary = renderedAuditFailure
.pick({
code: true,
@@ -365,6 +476,7 @@ export const renderedAuditFailureSummary = renderedAuditFailure
export const renderedAuditIssueSummary = z.object({
kind: renderedAuditIssueKind,
+ confidence: z.enum(["exact", "advisory"]),
count: z.number().int().positive(),
captureCount: z.number().int().positive(),
pagePaths: z.array(z.string()).max(5),
@@ -395,6 +507,7 @@ export const renderedAuditPlan = z.object({
"oversized-image",
"render-blocking-resource",
"legacy-font-format",
+ "low-text-contrast",
])
),
captureCount: z.number().int().nonnegative(),
@@ -429,7 +542,9 @@ const auditResultBase = z.object({
renderedCaptureSummary: renderedAuditCaptureSummary,
renderedCaptureStatuses: z.array(renderedAuditCaptureStatus),
renderedArtifactManifest: renderedAuditArtifactManifestSummary.nullable(),
+ generatedBuildSummary: generatedBuildSummary.nullable(),
nextCursor: z.string().nullable(),
+ profileStatuses: z.array(craftProfileStatus),
});
export const compactAuditResult = auditResultBase.extend({
@@ -446,6 +561,7 @@ export const verboseAuditResult = auditResultBase.extend({
manualChecks: z.array(manualAuditCheck),
renderedChecks: z.array(renderedAuditCheck),
renderedFailures: z.array(renderedAuditFailure),
+ generatedBuildMetrics: generatedBuildMetrics.nullable(),
});
export const auditResult = z.discriminatedUnion("verbose", [
@@ -460,6 +576,7 @@ export type AuditSummary = z.infer<typeof auditSummary>;
export type AuditResult = z.infer<typeof auditResult>;
export type CompactAuditResult = z.infer<typeof compactAuditResult>;
export type VerboseAuditResult = z.infer<typeof verboseAuditResult>;
+export type GeneratedBuildMetrics = z.infer<typeof generatedBuildMetrics>;
export type RenderedAuditCheck = z.infer<typeof renderedAuditCheck>;
export type RenderedAuditFailure = z.infer<typeof renderedAuditFailure>;
@@ -483,6 +600,7 @@ const auditDocumentationByScope: Record<AuditRule["scope"], string> = {
styles: "https://docs.webstudio.is/university/foundations/design-tokens",
performance:
"https://docs.webstudio.is/university/foundations/project-settings#atomic-css",
+ craft: craftProfile.provenance.url,
};
const rule = (
@@ -793,6 +911,18 @@ export const auditRules = {
"Move the style to a rendered child or wrap the component in an Element and style that wrapper.",
"https://docs.webstudio.is/university/core-components/collection"
),
+ "invalid-style-state-selector": rule(
+ "styles",
+ "warning",
+ "The style state selector is not a valid element-scoped suffix and may escape its component or generate invalid CSS.",
+ "Replace it with one pseudo-class, pseudo-element, attribute selector, or a compound suffix that remains scoped to the styled element."
+ ),
+ "orphan-style-breakpoint": rule(
+ "styles",
+ "warning",
+ "The style declaration references a breakpoint that does not exist, so the declaration cannot render.",
+ "Move the declaration to an existing breakpoint or remove it."
+ ),
"atomic-css-disabled": rule(
"performance",
"info",
@@ -800,6 +930,36 @@ export const auditRules = {
"Enable atomic CSS for optimized published output unless human-readable exported classes are required.",
"https://docs.webstudio.is/university/foundations/project-settings#atomic-css"
),
+ "craft-not-detected": rule(
+ "craft",
+ "info",
+ "No Craft signature was found. Craft is optional, so this is not a project defect.",
+ "Adopt Craft only when the project should use that system; otherwise leave the project unchanged."
+ ),
+ "craft-missing-semantic-variables": rule(
+ "craft",
+ "warning",
+ "A partial Craft setup is missing semantic variables defined by the Craft profile.",
+ "Define the first reported missing variable on Global Root, then rerun the Craft audit before adding more."
+ ),
+ "craft-container-token-missing": rule(
+ "craft",
+ "warning",
+ "Craft 1.2 uses a container token for consistent vertical layout and spacing.",
+ 'Create a token named "container" with display flex, flex direction column, and gap var(--gap-m).'
+ ),
+ "craft-container-token-incompatible": rule(
+ "craft",
+ "warning",
+ "The container token differs from the Craft 1.2 compatibility contract.",
+ "Correct the first reported declaration and rerun the Craft audit."
+ ),
+ "craft-style-guide-page-missing": rule(
+ "craft",
+ "info",
+ "Craft recommends an internal Style Guide page for shared references and page templates.",
+ 'Add or rename the internal reference page to "Style Guide" when that workflow is useful.'
+ ),
} satisfies Record<AuditRuleId, AuditRule>;
const getRule = (ruleId: string) => {
@@ -823,6 +983,8 @@ const locationKeys = new Set([
"designTokenId",
"designTokenIds",
"breakpointId",
+ "stateSelector",
+ "styleProperty",
"resourceId",
"dataSourceId",
"jsonLdPath",
@@ -1093,7 +1255,7 @@ export function audit(
"Audit requires the current project version"
);
}
- const scopes = input.scopes ?? auditScope.options;
+ const scopes = input.scopes ?? defaultAuditScopes;
const selectedSeverities = input.severities ?? auditSeverity.options;
let selectedPage: ReturnType<typeof findSerializedPageByInput> | undefined;
let normalizedInput = input;
@@ -1115,13 +1277,20 @@ export function audit(
pageId: selectedPage?.id,
verbose: input.verbose === true,
});
- const raw = analyzeProject(state, {
- scopes,
- pageId: normalizedInput.pageId,
- pagePath: normalizedInput.pagePath,
- limit: Number.MAX_SAFE_INTEGER,
- });
- const normalizedFindings = raw.matches
+ const standardScopes = scopes.filter((scope) => scope !== "craft");
+ const raw =
+ standardScopes.length === 0
+ ? { matches: [] }
+ : analyzeProject(state, {
+ scopes: standardScopes,
+ pageId: normalizedInput.pageId,
+ pagePath: normalizedInput.pagePath,
+ limit: Number.MAX_SAFE_INTEGER,
+ });
+ const craftAnalysis = scopes.includes("craft")
+ ? analyzeCraftProfile(state)
+ : undefined;
+ const normalizedFindings = [...raw.matches, ...(craftAnalysis?.matches ?? [])]
.map(canonicalizeAuditMatchPagePaths)
.map(normalizeAuditFinding)
.sort(
@@ -1143,7 +1312,7 @@ export function audit(
const findings = allFindings.filter((finding) =>
severities.has(finding.severity)
);
- const limit = input.limit ?? 50;
+ const limit = input.limit ?? 20;
let offset = 0;
if (input.cursor !== undefined) {
const cursor = decodeCursor(input.cursor);
@@ -1187,7 +1356,10 @@ export function audit(
pagePath: getAuditPagePath(pages, selectedPage),
projectWideScopes: scopes.filter(
(scope) =>
- scope === "assets" || scope === "styles" || scope === "performance"
+ scope === "assets" ||
+ scope === "styles" ||
+ scope === "performance" ||
+ scope === "craft"
),
};
}
@@ -1255,6 +1427,8 @@ export function audit(
},
renderedCaptureStatuses: [],
renderedArtifactManifest: null,
+ generatedBuildSummary: null,
+ profileStatuses: craftAnalysis === undefined ? [] : [craftAnalysis.status],
nextCursor:
offset + limit < findings.length
? encodeCursor(context.projectVersion, offset + limit, cursorSignature)
@@ -1269,6 +1443,7 @@ export function audit(
manualChecks: offset === 0 ? manualChecks : [],
renderedChecks: [],
renderedFailures: [],
+ generatedBuildMetrics: null,
});
}
return compactAuditResult.parse({
diff --git a/packages/project-build/src/runtime/binding-verification.acceptance.test.ts b/packages/project-build/src/runtime/binding-verification.acceptance.test.ts
new file mode 100644
index 0000000000..b2762e3e3f
--- /dev/null
+++ b/packages/project-build/src/runtime/binding-verification.acceptance.test.ts
@@ -0,0 +1,246 @@
+import { encodeDataVariableId } from "@webstudio-is/sdk";
+import { describe, expect, test } from "vitest";
+import type { BuilderRuntimeMutation } from "./mutation";
+import { applyBuilderPatchTransactions } from "../state/patch";
+import {
+ createBuilderStateFromSerializedSnapshot,
+ createSerializedBuilderStateSnapshotFromState,
+} from "../state/adapters";
+import { executeBuilderRuntimeOperation } from "./registry";
+import { verifyBindings } from "./binding-verification";
+import { createBindingVerificationFixture } from "./binding-verification.test-fixtures";
+
+const createContext = () => {
+ let nextId = 0;
+ return {
+ createId: () => `acceptance-${nextId++}`,
+ };
+};
+
+const applyMutation = (
+ state: ReturnType<typeof createBindingVerificationFixture>,
+ id: string,
+ input: unknown,
+ context: ReturnType<typeof createContext>
+) => {
+ const result = executeBuilderRuntimeOperation({
+ id,
+ state,
+ input,
+ context,
+ });
+ expect(result).toMatchObject({ kind: "mutation" });
+ return applyBuilderPatchTransactions(state, [
+ {
+ id: `transaction-${id}`,
+ payload: (result as BuilderRuntimeMutation).payload,
+ },
+ ]).state;
+};
+
+describe("dynamic binding verification acceptance", () => {
+ test("checks realistic text, prop, action, parameter, resource, and metadata bindings", () => {
+ const state = createBindingVerificationFixture();
+ const result = verifyBindings(state, { limit: 200 });
+
+ expect(result.analysis).toEqual({
+ staticIntegrity: "complete",
+ renderedResolution: "not-evaluated",
+ externalResourcesExecuted: false,
+ });
+ expect(result.findings).toEqual([]);
+ expect(result.summary.bindingsChecked).toBeGreaterThanOrEqual(18);
+
+ const bindingKinds = new Set<string>();
+ for (const instance of state.instances!.values()) {
+ for (const child of instance.children) {
+ if (child.type === "expression") {
+ bindingKinds.add("text-expression");
+ }
+ }
+ }
+ for (const prop of state.props!.values()) {
+ if (prop.type === "expression") {
+ bindingKinds.add("prop-expression");
+ }
+ if (prop.type === "action") {
+ bindingKinds.add("prop-action");
+ }
+ if (prop.type === "resource") {
+ bindingKinds.add("prop-resource");
+ }
+ if (prop.type === "parameter") {
+ bindingKinds.add("prop-parameter");
+ }
+ }
+ bindingKinds.add("resource-expression");
+ bindingKinds.add("page-metadata");
+ expect(bindingKinds).toEqual(
+ new Set([
+ "text-expression",
+ "prop-expression",
+ "prop-action",
+ "prop-resource",
+ "prop-parameter",
+ "resource-expression",
+ "page-metadata",
+ ])
+ );
+ });
+
+ test("keeps root-scoped resource expressions in a page verification", () => {
+ const state = createBindingVerificationFixture();
+ state.resources!.get("health-resource")!.url = "unknownTenant";
+
+ const result = verifyBindings(state, { pagePath: "/" });
+
+ expect(result.findings).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: "unknown-identifier",
+ bindingKind: "resource-expression",
+ location: expect.objectContaining({
+ pageId: "catalog-page",
+ resourceId: "health-resource",
+ }),
+ }),
+ ])
+ );
+ });
+
+ test("preserves binding meaning through the persisted session boundary", () => {
+ const state = createBindingVerificationFixture();
+ const restored = createBuilderStateFromSerializedSnapshot(
+ createSerializedBuilderStateSnapshotFromState(state)
+ );
+
+ expect(verifyBindings(restored, { limit: 200 })).toEqual(
+ verifyBindings(state, { limit: 200 })
+ );
+ expect(restored.instances).toEqual(state.instances);
+ expect(restored.props).toEqual(state.props);
+ expect(restored.dataSources).toEqual(state.dataSources);
+ expect(restored.resources).toEqual(state.resources);
+ });
+
+ test("survives create, inspect, update, and failed mutation semantics", () => {
+ let state = createBindingVerificationFixture();
+ const context = createContext();
+
+ state = applyMutation(
+ state,
+ "variables.create",
+ {
+ scopeInstanceId: "body",
+ name: "region",
+ value: { type: "string", value: "eu-west" },
+ },
+ context
+ );
+ expect(state.dataSources?.has("acceptance-0")).toBe(true);
+
+ const createResource = executeBuilderRuntimeOperation({
+ id: "resources.create",
+ state,
+ input: {
+ resource: {
+ name: "Regional products",
+ method: "get",
+ url: '"/api/products?region=" + region',
+ headers: [
+ { name: "x-region", value: "region" },
+ {
+ name: "accept",
+ value: { type: "literal", value: "application/json" },
+ },
+ ],
+ searchParams: [
+ { name: "source", value: { type: "literal", value: "catalog" } },
+ ],
+ },
+ scopeInstanceId: "body",
+ dataSourceName: "RegionalProducts",
+ exposeAsDataSource: true,
+ },
+ context,
+ });
+ expect(createResource).toMatchObject({
+ kind: "mutation",
+ result: { resourceId: "acceptance-1", dataSourceId: "acceptance-2" },
+ });
+ state = applyBuilderPatchTransactions(state, [
+ {
+ id: "create-regional-resource",
+ payload: (createResource as BuilderRuntimeMutation).payload,
+ },
+ ]).state;
+
+ state = applyMutation(
+ state,
+ "instances.bindProps",
+ {
+ bindings: [
+ {
+ instanceId: "hero",
+ name: "aria-label",
+ binding: { type: "expression", value: "region" },
+ },
+ ],
+ },
+ context
+ );
+ const regionalProp = [...(state.props?.values() ?? [])].find(
+ (prop) => prop.instanceId === "hero" && prop.name === "aria-label"
+ );
+ expect(regionalProp).toMatchObject({
+ type: "expression",
+ value: encodeDataVariableId("acceptance-0"),
+ });
+
+ const inspection = executeBuilderRuntimeOperation({
+ id: "instances.inspect",
+ state,
+ input: { instanceId: "hero", include: ["bindings"] },
+ context,
+ });
+ expect(inspection).toMatchObject({
+ bindings: expect.arrayContaining([
+ expect.objectContaining({ name: "aria-label", type: "expression" }),
+ ]),
+ });
+
+ const clean = verifyBindings(state, { pagePath: "/" });
+ expect(clean.findings).toEqual([]);
+
+ state = applyMutation(
+ state,
+ "variables.update",
+ {
+ dataSourceId: "acceptance-0",
+ values: { scopeInstanceId: "detail-body" },
+ },
+ context
+ );
+ const outOfScope = verifyBindings(state, { pagePath: "/" });
+ expect(outOfScope.findings).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: "out-of-scope-data-source",
+ location: expect.objectContaining({ dataSourceId: "acceptance-0" }),
+ }),
+ ])
+ );
+
+ expect(() =>
+ executeBuilderRuntimeOperation({
+ id: "resources.update",
+ state,
+ input: {
+ resourceId: "acceptance-1",
+ values: { url: "region +" },
+ },
+ context,
+ })
+ ).toThrow();
+ });
+});
diff --git a/packages/project-build/src/runtime/binding-verification.test-fixtures.ts b/packages/project-build/src/runtime/binding-verification.test-fixtures.ts
new file mode 100644
index 0000000000..ebbc90e827
--- /dev/null
+++ b/packages/project-build/src/runtime/binding-verification.test-fixtures.ts
@@ -0,0 +1,329 @@
+import { encodeDataVariableId } from "@webstudio-is/sdk";
+import type { BuilderState } from "../state/builder-state";
+
+const createPage = ({
+ id,
+ name,
+ path,
+ rootInstanceId,
+ title,
+ description,
+}: {
+ id: string;
+ name: string;
+ path: string;
+ rootInstanceId: string;
+ title: string;
+ description: string;
+}) => ({
+ id,
+ name,
+ path,
+ rootInstanceId,
+ title,
+ meta: {
+ description,
+ custom: [{ property: "og:description", content: description }],
+ },
+});
+
+export const createBindingVerificationFixture = (): BuilderState => {
+ const featuredProductId = "featured-product";
+ const productsId = "products-data";
+ const itemParameterId = "collection-item";
+ const itemKeyParameterId = "collection-item-key";
+ const healthDataSourceId = "health-data";
+ const featuredProduct = encodeDataVariableId(featuredProductId);
+ const products = encodeDataVariableId(productsId);
+ const itemParameter = encodeDataVariableId(itemParameterId);
+ const itemKeyParameter = encodeDataVariableId(itemKeyParameterId);
+
+ return {
+ pages: {
+ homePageId: "catalog-page",
+ rootFolderId: "root-folder",
+ meta: {},
+ compiler: {},
+ pages: new Map([
+ [
+ "catalog-page",
+ createPage({
+ id: "catalog-page",
+ name: "Catalog",
+ path: "",
+ rootInstanceId: "body",
+ title: "siteName",
+ description: `${featuredProduct}.name + " catalog"`,
+ }),
+ ],
+ [
+ "detail-page",
+ createPage({
+ id: "detail-page",
+ name: "Product detail",
+ path: "/products/example",
+ rootInstanceId: "detail-body",
+ title: '"Product detail"',
+ description: '"A product detail page"',
+ }),
+ ],
+ ]),
+ folders: new Map([
+ [
+ "root-folder",
+ {
+ id: "root-folder",
+ name: "Root",
+ slug: "",
+ children: ["catalog-page", "detail-page"],
+ },
+ ],
+ ]),
+ },
+ instances: new Map([
+ [
+ "body",
+ {
+ type: "instance",
+ id: "body",
+ component: "Body",
+ children: [
+ { type: "id", value: "hero" },
+ { type: "id", value: "catalog" },
+ { type: "id", value: "checkout" },
+ ],
+ },
+ ],
+ [
+ "hero",
+ {
+ type: "instance",
+ id: "hero",
+ component: "Text",
+ tag: "h1",
+ children: [{ type: "expression", value: `${featuredProduct}.name` }],
+ },
+ ],
+ [
+ "catalog",
+ {
+ type: "instance",
+ id: "catalog",
+ component: "Collection",
+ children: [{ type: "id", value: "product-card" }],
+ },
+ ],
+ [
+ "product-card",
+ {
+ type: "instance",
+ id: "product-card",
+ component: "Text",
+ tag: "article",
+ children: [
+ { type: "expression", value: `${itemParameter}?.name` },
+ { type: "expression", value: `${itemKeyParameter}` },
+ ],
+ },
+ ],
+ [
+ "checkout",
+ {
+ type: "instance",
+ id: "checkout",
+ component: "Form",
+ children: [],
+ },
+ ],
+ [
+ "detail-body",
+ {
+ type: "instance",
+ id: "detail-body",
+ component: "Body",
+ children: [{ type: "id", value: "detail-title" }],
+ },
+ ],
+ [
+ "detail-title",
+ {
+ type: "instance",
+ id: "detail-title",
+ component: "Text",
+ children: [],
+ },
+ ],
+ ]),
+ props: new Map([
+ [
+ "hero-title",
+ {
+ id: "hero-title",
+ instanceId: "hero",
+ name: "title",
+ type: "expression",
+ value: `${featuredProduct}.name ?? "Untitled"`,
+ },
+ ],
+ [
+ "catalog-data",
+ {
+ id: "catalog-data",
+ instanceId: "catalog",
+ name: "data",
+ type: "expression",
+ value: `${products}?.data?.items`,
+ },
+ ],
+ [
+ "product-link",
+ {
+ id: "product-link",
+ instanceId: "product-card",
+ name: "href",
+ type: "expression",
+ value: `${itemParameter}?.slug`,
+ },
+ ],
+ [
+ "product-parameter",
+ {
+ id: "product-parameter",
+ instanceId: "product-card",
+ name: "item",
+ type: "parameter",
+ value: itemParameterId,
+ },
+ ],
+ [
+ "product-resource",
+ {
+ id: "product-resource",
+ instanceId: "checkout",
+ name: "action",
+ type: "resource",
+ value: "product-action",
+ },
+ ],
+ [
+ "checkout-action",
+ {
+ id: "checkout-action",
+ instanceId: "checkout",
+ name: "onSubmit",
+ type: "action",
+ value: [
+ {
+ type: "execute",
+ args: ["event"],
+ code: "event.submitted = true",
+ },
+ ],
+ },
+ ],
+ ]),
+ dataSources: new Map([
+ [
+ featuredProductId,
+ {
+ id: featuredProductId,
+ type: "variable",
+ name: "featuredProduct",
+ scopeInstanceId: "body",
+ value: {
+ type: "json",
+ value: { id: "starter", name: "Starter", tenant: "northstar" },
+ },
+ },
+ ],
+ [
+ "site-name",
+ {
+ id: "site-name",
+ type: "variable",
+ name: "siteName",
+ scopeInstanceId: "body",
+ value: { type: "string", value: "Northstar Catalog" },
+ },
+ ],
+ [
+ productsId,
+ {
+ id: productsId,
+ type: "resource",
+ name: "Products",
+ scopeInstanceId: "body",
+ resourceId: "products-resource",
+ },
+ ],
+ [
+ itemParameterId,
+ {
+ id: itemParameterId,
+ type: "parameter",
+ name: "collectionItem",
+ scopeInstanceId: "catalog",
+ },
+ ],
+ [
+ itemKeyParameterId,
+ {
+ id: itemKeyParameterId,
+ type: "parameter",
+ name: "collectionItemKey",
+ scopeInstanceId: "catalog",
+ },
+ ],
+ [
+ healthDataSourceId,
+ {
+ id: healthDataSourceId,
+ type: "resource",
+ name: "Health",
+ resourceId: "health-resource",
+ },
+ ],
+ ]),
+ resources: new Map([
+ [
+ "products-resource",
+ {
+ id: "products-resource",
+ name: "Products",
+ method: "get",
+ url: '"/api/products?tenant=" + featuredProduct.tenant',
+ headers: [{ name: "x-path", value: "system.pathname" }],
+ searchParams: [{ name: "page", value: '"1"' }],
+ },
+ ],
+ [
+ "product-action",
+ {
+ id: "product-action",
+ name: "Submit product",
+ method: "post",
+ url: '"/api/products/" + featuredProduct.id',
+ headers: [{ name: "Content-Type", value: '"application/json"' }],
+ searchParams: [],
+ body: "{ id: featuredProduct.id, source: system.pathname }",
+ },
+ ],
+ [
+ "health-resource",
+ {
+ id: "health-resource",
+ name: "Health",
+ method: "get",
+ url: '"/api/health?path=" + system.pathname',
+ headers: [],
+ searchParams: [],
+ },
+ ],
+ ]),
+ styleSources: new Map(),
+ styleSourceSelections: new Map(),
+ styles: new Map(),
+ breakpoints: new Map([["base", { id: "base", label: "Base" }]]),
+ assets: new Map(),
+ };
+};
diff --git a/packages/project-build/src/runtime/binding-verification.test.ts b/packages/project-build/src/runtime/binding-verification.test.ts
new file mode 100644
index 0000000000..8914c28d51
--- /dev/null
+++ b/packages/project-build/src/runtime/binding-verification.test.ts
@@ -0,0 +1,406 @@
+import { describe, expect, test } from "vitest";
+import { encodeDataVariableId } from "@webstudio-is/sdk";
+import type { BuilderState } from "../state/builder-state";
+import { executeBuilderRuntimeOperation } from "./registry";
+import { verifyBindings } from "./binding-verification";
+import { context, expectRuntimeValidationError } from "./runtime.test-fixtures";
+
+const createState = (): BuilderState => {
+ const global = encodeDataVariableId("global-title");
+ const item = encodeDataVariableId("collection-item");
+ return {
+ pages: {
+ homePageId: "home",
+ rootFolderId: "root",
+ meta: {},
+ compiler: {},
+ pages: new Map([
+ [
+ "home",
+ {
+ id: "home",
+ name: "Home",
+ title: global,
+ path: "",
+ rootInstanceId: "body",
+ meta: { description: `${global} ?? "Catalog"` },
+ },
+ ],
+ [
+ "other",
+ {
+ id: "other",
+ name: "Other",
+ title: '"Other"',
+ path: "/other",
+ rootInstanceId: "other-body",
+ meta: {},
+ },
+ ],
+ ]),
+ folders: new Map([
+ [
+ "root",
+ {
+ id: "root",
+ name: "Root",
+ slug: "",
+ children: ["home", "other"],
+ },
+ ],
+ ]),
+ },
+ instances: new Map([
+ [
+ "body",
+ {
+ type: "instance",
+ id: "body",
+ component: "Body",
+ children: [
+ { type: "id", value: "collection" },
+ { type: "id", value: "sibling" },
+ ],
+ },
+ ],
+ [
+ "collection",
+ {
+ type: "instance",
+ id: "collection",
+ component: "Collection",
+ children: [{ type: "id", value: "item" }],
+ },
+ ],
+ [
+ "item",
+ {
+ type: "instance",
+ id: "item",
+ component: "Text",
+ children: [{ type: "expression", value: `${item}.name` }],
+ },
+ ],
+ [
+ "sibling",
+ {
+ type: "instance",
+ id: "sibling",
+ component: "Text",
+ children: [],
+ },
+ ],
+ [
+ "other-body",
+ {
+ type: "instance",
+ id: "other-body",
+ component: "Body",
+ children: [],
+ },
+ ],
+ ]),
+ props: new Map([
+ [
+ "item-expression",
+ {
+ id: "item-expression",
+ instanceId: "item",
+ name: "title",
+ type: "expression",
+ value: `${item}.name`,
+ },
+ ],
+ [
+ "item-action",
+ {
+ id: "item-action",
+ instanceId: "item",
+ name: "onClick",
+ type: "action",
+ value: [{ type: "execute", args: ["event"], code: "event" }],
+ },
+ ],
+ [
+ "item-parameter",
+ {
+ id: "item-parameter",
+ instanceId: "item",
+ name: "item",
+ type: "parameter",
+ value: "collection-item",
+ },
+ ],
+ [
+ "item-resource",
+ {
+ id: "item-resource",
+ instanceId: "item",
+ name: "action",
+ type: "resource",
+ value: "posts-resource",
+ },
+ ],
+ ]),
+ dataSources: new Map([
+ [
+ "global-title",
+ {
+ id: "global-title",
+ type: "variable",
+ name: "globalTitle",
+ scopeInstanceId: "body",
+ value: { type: "string", value: "Catalog" },
+ },
+ ],
+ [
+ "collection-item",
+ {
+ id: "collection-item",
+ type: "parameter",
+ name: "collectionItem",
+ scopeInstanceId: "collection",
+ },
+ ],
+ [
+ "collection-key",
+ {
+ id: "collection-key",
+ type: "parameter",
+ name: "collectionItemKey",
+ scopeInstanceId: "collection",
+ },
+ ],
+ [
+ "posts",
+ {
+ id: "posts",
+ type: "resource",
+ name: "posts",
+ scopeInstanceId: "body",
+ resourceId: "posts-resource",
+ },
+ ],
+ ]),
+ resources: new Map([
+ [
+ "posts-resource",
+ {
+ id: "posts-resource",
+ name: "Posts",
+ method: "get",
+ url: `"/posts?title=" + ${global}`,
+ headers: [{ name: "x-path", value: "$ws$system.pathname" }],
+ searchParams: [],
+ },
+ ],
+ ]),
+ };
+};
+
+describe("project.verifyBindings", () => {
+ test("accepts Collection locals, action args, resources, and page metadata", () => {
+ const result = verifyBindings(createState(), {});
+
+ expect(result.analysis).toEqual({
+ staticIntegrity: "complete",
+ renderedResolution: "not-evaluated",
+ externalResourcesExecuted: false,
+ });
+ expect(result.summary.bindingsChecked).toBeGreaterThan(8);
+ expect(result.findings).toEqual([]);
+ });
+
+ test("reports missing references, scope violations, unknown names, and stale ids", () => {
+ const state = createState();
+ const stale = encodeDataVariableId("deleted-variable");
+ const item = encodeDataVariableId("collection-item");
+ state.instances?.get("item")?.children.push({
+ type: "expression",
+ value: "misspelled.name",
+ });
+ state.props?.set("stale-expression", {
+ id: "stale-expression",
+ instanceId: "item",
+ name: "stale",
+ type: "expression",
+ value: stale,
+ });
+ state.props?.set("invalid-expression", {
+ id: "invalid-expression",
+ instanceId: "item",
+ name: "invalid",
+ type: "expression",
+ value: "item +",
+ });
+ state.props?.set("out-of-scope-expression", {
+ id: "out-of-scope-expression",
+ instanceId: "sibling",
+ name: "itemName",
+ type: "expression",
+ value: `${item}.name`,
+ });
+ state.props?.set("missing-parameter", {
+ id: "missing-parameter",
+ instanceId: "item",
+ name: "missingItem",
+ type: "parameter",
+ value: "deleted-parameter",
+ });
+ state.props?.set("out-of-scope-parameter", {
+ id: "out-of-scope-parameter",
+ instanceId: "sibling",
+ name: "item",
+ type: "parameter",
+ value: "collection-item",
+ });
+ state.props?.set("missing-resource", {
+ id: "missing-resource",
+ instanceId: "item",
+ name: "action2",
+ type: "resource",
+ value: "deleted-resource",
+ });
+
+ const result = verifyBindings(state, { limit: 200 });
+ const codes = result.findings.map(({ code }) => code);
+
+ expect(codes).toEqual(
+ expect.arrayContaining([
+ "invalid-expression",
+ "unknown-identifier",
+ "stale-data-source-id",
+ "out-of-scope-data-source",
+ "missing-parameter",
+ "out-of-scope-parameter",
+ "missing-resource",
+ ])
+ );
+ expect(result.findings).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ code: "missing-resource",
+ remediation: expect.stringContaining("existing resource"),
+ }),
+ ])
+ );
+ });
+
+ test("identifies missing resources owned by data sources", () => {
+ const state = createState();
+ const posts = state.dataSources!.get("posts");
+ if (posts?.type !== "resource") {
+ throw new Error("Expected resource data source fixture");
+ }
+ posts.resourceId = "deleted-resource";
+
+ const result = verifyBindings(state, { limit: 200 });
+
+ expect(result.findings).toContainEqual(
+ expect.objectContaining({
+ code: "missing-resource",
+ bindingKind: "data-source-resource",
+ location: expect.objectContaining({
+ dataSourceId: "posts",
+ resourceId: "deleted-resource",
+ path: ["dataSources", "posts", "resourceId"],
+ }),
+ })
+ );
+ });
+
+ test("accepts a parameter prop on the Collection that owns it", () => {
+ const state = createState();
+ state.props?.set("collection-item-prop", {
+ id: "collection-item-prop",
+ instanceId: "collection",
+ name: "item",
+ type: "parameter",
+ value: "collection-item",
+ });
+
+ const result = verifyBindings(state, { limit: 200 });
+
+ expect(result.findings).not.toContainEqual(
+ expect.objectContaining({
+ bindingKind: "prop-parameter",
+ location: expect.objectContaining({ propId: "collection-item-prop" }),
+ })
+ );
+ });
+
+ test("filters by page and instance subtree and paginates stable findings", () => {
+ const state = createState();
+ state.pages!.pages.get("other")!.title = "unknownOther";
+ state.instances
+ ?.get("item")
+ ?.children.push(
+ { type: "expression", value: "unknownOne" },
+ { type: "expression", value: "unknownTwo" }
+ );
+
+ const first = verifyBindings(state, {
+ pagePath: "/",
+ instanceId: "item",
+ limit: 1,
+ });
+ const second = verifyBindings(state, {
+ pagePath: "/",
+ instanceId: "item",
+ limit: 1,
+ cursor: first.nextCursor ?? undefined,
+ });
+
+ expect(first.total).toBe(2);
+ expect(first.returnedCount).toBe(1);
+ expect(first.nextCursor).toBe("1");
+ expect(second.findings[0]?.id).not.toBe(first.findings[0]?.id);
+ expect([...first.findings, ...second.findings]).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ location: expect.objectContaining({ pageId: "other" }),
+ }),
+ ])
+ );
+ });
+
+ test("reports the full path for a page nested in a folder", () => {
+ const state = createState();
+ state.pages!.folders.get("root")!.children = ["home", "section"];
+ state.pages!.folders.set("section", {
+ id: "section",
+ name: "Section",
+ slug: "section",
+ children: ["other"],
+ });
+ state.pages!.pages.get("other")!.title =
+ encodeDataVariableId("global-title");
+
+ const result = verifyBindings(state, { pageId: "other" });
+
+ expect(result.findings).toContainEqual(
+ expect.objectContaining({
+ code: "out-of-scope-data-source",
+ location: expect.objectContaining({
+ pageId: "other",
+ pagePath: "/section/other",
+ }),
+ })
+ );
+ });
+
+ test("is exposed through the canonical runtime operation", () => {
+ const result = executeBuilderRuntimeOperation({
+ id: "project.verifyBindings",
+ state: createState(),
+ input: { pageId: "home" },
+ context,
+ });
+
+ expect(result).toMatchObject({ contractVersion: 1, findings: [] });
+ expectRuntimeValidationError("project.verifyBindings", {
+ pageId: "home",
+ pagePath: "/",
+ });
+ });
+});
diff --git a/packages/project-build/src/runtime/binding-verification.ts b/packages/project-build/src/runtime/binding-verification.ts
new file mode 100644
index 0000000000..24f97a3016
--- /dev/null
+++ b/packages/project-build/src/runtime/binding-verification.ts
@@ -0,0 +1,643 @@
+import {
+ decodeDataVariableId,
+ encodeDataVariableId,
+ findTreeInstanceIds,
+ getExpressionIdentifiers,
+ lintExpression,
+ ROOT_INSTANCE_ID,
+ SYSTEM_VARIABLE_ID,
+ isLiteralExpression,
+ type Instance,
+ type Page,
+} from "@webstudio-is/sdk";
+import { z } from "zod";
+import type { BuilderState } from "../state/builder-state";
+import { throwBuilderRuntimeError } from "./errors";
+import { findAvailableVariables, listResourceExpressions } from "./data";
+import {
+ findSerializedPageByInput,
+ getSerializedPagePath,
+ getSerializedPages,
+ listPageMetadataExpressions,
+} from "./pages";
+import { listPropExpressions } from "./props";
+import {
+ paginateOutput,
+ paginatedOutputInputSchema,
+ paginatedOutputMetadataSchema,
+} from "./output";
+
+export const bindingVerificationContractVersion = 1 as const;
+
+export const bindingVerificationInput = paginatedOutputInputSchema
+ .extend({
+ pageId: z
+ .string()
+ .optional()
+ .describe("Verify only bindings on this page."),
+ pagePath: z
+ .string()
+ .optional()
+ .describe("Verify only bindings on the page matching this path."),
+ instanceId: z
+ .string()
+ .optional()
+ .describe("Verify only bindings in this instance subtree."),
+ })
+ .strict()
+ .refine(
+ ({ pageId, pagePath }) => pageId === undefined || pagePath === undefined,
+ { message: "Use either pageId or pagePath, not both", path: ["pageId"] }
+ );
+
+export const bindingVerificationFindingCode = z.enum([
+ "invalid-expression",
+ "unknown-identifier",
+ "stale-data-source-id",
+ "out-of-scope-data-source",
+ "missing-resource",
+ "missing-parameter",
+ "out-of-scope-parameter",
+]);
+
+export const bindingVerificationFinding = z.object({
+ id: z.string(),
+ code: bindingVerificationFindingCode,
+ category: z.enum(["validity", "scope", "reference"]),
+ severity: z.enum(["error", "warning"]),
+ bindingKind: z.enum([
+ "text-expression",
+ "prop-expression",
+ "prop-action",
+ "prop-resource",
+ "data-source-resource",
+ "prop-parameter",
+ "resource-expression",
+ "page-metadata",
+ ]),
+ message: z.string(),
+ remediation: z.string(),
+ location: z.object({
+ pageId: z.string().optional(),
+ pagePath: z.string().optional(),
+ instanceId: z.string().optional(),
+ propId: z.string().optional(),
+ propName: z.string().optional(),
+ resourceId: z.string().optional(),
+ dataSourceId: z.string().optional(),
+ path: z.array(z.string()),
+ }),
+ range: z
+ .object({
+ from: z.number().int().nonnegative(),
+ to: z.number().int().nonnegative(),
+ })
+ .optional(),
+});
+
+export const bindingVerificationResult = z.object({
+ contractVersion: z.literal(bindingVerificationContractVersion),
+ analysis: z.object({
+ staticIntegrity: z.literal("complete"),
+ renderedResolution: z.literal("not-evaluated"),
+ externalResourcesExecuted: z.literal(false),
+ }),
+ summary: z.object({
+ bindingsChecked: z.number().int().nonnegative(),
+ findings: z.number().int().nonnegative(),
+ }),
+ findings: z.array(bindingVerificationFinding),
+ ...paginatedOutputMetadataSchema.shape,
+});
+
+export type BindingVerificationInput = z.infer<typeof bindingVerificationInput>;
+export type BindingVerificationFinding = z.infer<
+ typeof bindingVerificationFinding
+>;
+
+type Location = BindingVerificationFinding["location"];
+type BindingKind = BindingVerificationFinding["bindingKind"];
+
+const getRequiredState = (state: BuilderState) => {
+ if (
+ state.pages === undefined ||
+ state.instances === undefined ||
+ state.props === undefined ||
+ state.dataSources === undefined ||
+ state.resources === undefined
+ ) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "Binding verification requires pages, instances, props, data sources, and resources"
+ );
+ }
+ return {
+ pages: state.pages,
+ instances: state.instances,
+ props: state.props,
+ dataSources: state.dataSources,
+ resources: state.resources,
+ };
+};
+
+const locationKey = (location: Location) =>
+ [
+ location.pageId,
+ location.instanceId,
+ location.propId,
+ location.resourceId,
+ location.dataSourceId,
+ ...location.path,
+ ]
+ .filter((value) => value !== undefined)
+ .join(":");
+
+const createFinding = (
+ code: BindingVerificationFinding["code"],
+ bindingKind: BindingKind,
+ location: Location,
+ details: Pick<
+ BindingVerificationFinding,
+ "category" | "severity" | "message" | "remediation"
+ > & { range?: BindingVerificationFinding["range"] }
+): BindingVerificationFinding => ({
+ id: `${code}:${bindingKind}:${locationKey(location)}${details.range === undefined ? "" : `:${details.range.from}:${details.range.to}`}`,
+ code,
+ bindingKind,
+ location,
+ ...details,
+});
+
+const shouldVerifyPageMetadataExpression = (
+ expression: string,
+ availableVariables: ReadonlySet<string>
+) => {
+ if (isLiteralExpression(expression)) {
+ return false;
+ }
+ if (
+ Array.from(getExpressionIdentifiers(expression)).some(
+ (identifier) =>
+ decodeDataVariableId(identifier) !== undefined ||
+ availableVariables.has(identifier)
+ )
+ ) {
+ return true;
+ }
+ // Page metadata accepts plain fixed strings, which are stored without JS
+ // string delimiters. Verify computed syntax while leaving ordinary
+ // imported/editor-authored text alone.
+ return /\?\?|&&|\|\||===|!==|==|!=|<=|>=|\s[+*/%]\s|\s-\s/.test(expression);
+};
+
+export const verifyBindings = (
+ state: BuilderState,
+ input: BindingVerificationInput
+) => {
+ const { pages, instances, props, dataSources, resources } =
+ getRequiredState(state);
+ const serializedPages = getSerializedPages({ pages });
+ const pagePathById = new Map(
+ serializedPages.pages.map((page) => [
+ page.id,
+ getSerializedPagePath(serializedPages, page) || "/",
+ ])
+ );
+ let selectedPage: Page | undefined;
+ if (input.pageId !== undefined || input.pagePath !== undefined) {
+ const serializedPage = findSerializedPageByInput(serializedPages, input);
+ selectedPage =
+ serializedPage === undefined
+ ? undefined
+ : pages.pages.get(serializedPage.id);
+ if (selectedPage === undefined) {
+ return throwBuilderRuntimeError("NOT_FOUND", "Page not found");
+ }
+ }
+ if (
+ input.instanceId !== undefined &&
+ instances.has(input.instanceId) === false
+ ) {
+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");
+ }
+
+ let selectedInstanceIds: Set<string> | undefined;
+ if (selectedPage !== undefined) {
+ selectedInstanceIds = findTreeInstanceIds(
+ instances,
+ selectedPage.rootInstanceId
+ );
+ }
+ if (input.instanceId !== undefined) {
+ const subtreeIds = findTreeInstanceIds(instances, input.instanceId);
+ selectedInstanceIds =
+ selectedInstanceIds === undefined
+ ? subtreeIds
+ : new Set(
+ [...subtreeIds].filter((instanceId) =>
+ selectedInstanceIds?.has(instanceId)
+ )
+ );
+ if (selectedInstanceIds.size === 0) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "The selected instance is not on the selected page"
+ );
+ }
+ }
+
+ const pageByInstanceId = new Map<string, Page>();
+ for (const page of pages.pages.values()) {
+ for (const instanceId of findTreeInstanceIds(
+ instances,
+ page.rootInstanceId
+ )) {
+ if (pageByInstanceId.has(instanceId) === false) {
+ pageByInstanceId.set(instanceId, page);
+ }
+ }
+ }
+ const withPage = (instanceId: string, location: Location): Location => {
+ const page = pageByInstanceId.get(instanceId);
+ return page === undefined
+ ? location
+ : {
+ pageId: page.id,
+ pagePath: pagePathById.get(page.id) ?? "/",
+ ...location,
+ };
+ };
+
+ const findings: BindingVerificationFinding[] = [];
+ let bindingsChecked = 0;
+ const verifyExpression = ({
+ expression,
+ instanceId,
+ bindingKind,
+ location,
+ allowAssignment = false,
+ variables = [],
+ }: {
+ expression: string;
+ instanceId: Instance["id"];
+ bindingKind: BindingKind;
+ location: Location;
+ allowAssignment?: boolean;
+ variables?: readonly string[];
+ }) => {
+ bindingsChecked += 1;
+ const availableDataSources = findAvailableVariables({
+ startingInstanceId: instanceId,
+ instances,
+ dataSources,
+ });
+ const availableIds = new Set(availableDataSources.map(({ id }) => id));
+ const availableVariables = new Set(variables);
+ for (const dataSource of availableDataSources) {
+ availableVariables.add(dataSource.name);
+ availableVariables.add(encodeDataVariableId(dataSource.id));
+ }
+ availableVariables.add("system");
+ availableVariables.add(encodeDataVariableId(SYSTEM_VARIABLE_ID));
+ // Encoded identifiers get dedicated reference/scope findings below.
+ for (const identifier of getExpressionIdentifiers(expression)) {
+ if (decodeDataVariableId(identifier) !== undefined) {
+ availableVariables.add(identifier);
+ }
+ }
+
+ const diagnostics = lintExpression({
+ expression,
+ availableVariables,
+ allowAssignment,
+ });
+ for (const diagnostic of diagnostics) {
+ const unknownMatch = diagnostic.message.match(
+ /^"(.+)" is not defined in the scope$/
+ );
+ const code = unknownMatch ? "unknown-identifier" : "invalid-expression";
+ findings.push(
+ createFinding(code, bindingKind, location, {
+ category: unknownMatch ? "scope" : "validity",
+ severity: diagnostic.severity === "error" ? "error" : "warning",
+ message: diagnostic.message,
+ remediation: unknownMatch
+ ? `Define ${JSON.stringify(unknownMatch[1])} in this instance scope or use an available variable, then rerun verify-bindings.`
+ : "Correct the persisted expression using supported Webstudio expression syntax, then rerun verify-bindings.",
+ range: { from: diagnostic.from, to: diagnostic.to },
+ })
+ );
+ }
+ for (const identifier of getExpressionIdentifiers(expression)) {
+ const dataSourceId = decodeDataVariableId(identifier);
+ if (dataSourceId === undefined || dataSourceId === SYSTEM_VARIABLE_ID) {
+ continue;
+ }
+ const dataSource = dataSources.get(dataSourceId);
+ if (dataSource === undefined) {
+ findings.push(
+ createFinding(
+ "stale-data-source-id",
+ bindingKind,
+ { ...location, dataSourceId },
+ {
+ category: "reference",
+ severity: "error",
+ message: `Expression references missing data source ${JSON.stringify(dataSourceId)}.`,
+ remediation:
+ "Rebind this expression to a current in-scope variable; do not reuse the stale internal id.",
+ }
+ )
+ );
+ } else if (availableIds.has(dataSourceId) === false) {
+ findings.push(
+ createFinding(
+ "out-of-scope-data-source",
+ bindingKind,
+ { ...location, dataSourceId },
+ {
+ category: "scope",
+ severity: "error",
+ message: `Expression references ${JSON.stringify(dataSource.name)} outside its instance scope.`,
+ remediation:
+ "Move the binding into the variable's scope or rebind it to a variable available at this instance.",
+ }
+ )
+ );
+ }
+ }
+ };
+
+ const isSelectedInstance = (instanceId: string) =>
+ selectedInstanceIds === undefined || selectedInstanceIds.has(instanceId);
+
+ for (const instance of instances.values()) {
+ if (isSelectedInstance(instance.id) === false) {
+ continue;
+ }
+ for (const [childIndex, child] of instance.children.entries()) {
+ if (child.type !== "expression") {
+ continue;
+ }
+ verifyExpression({
+ expression: child.value,
+ instanceId: instance.id,
+ bindingKind: "text-expression",
+ location: withPage(instance.id, {
+ instanceId: instance.id,
+ path: [
+ "instances",
+ instance.id,
+ "children",
+ String(childIndex),
+ "value",
+ ],
+ }),
+ });
+ }
+ }
+
+ const resourceScopes = new Map<string, Set<string>>();
+ const addResourceScope = (resourceId: string, instanceId: string) => {
+ const scopes = resourceScopes.get(resourceId) ?? new Set<string>();
+ scopes.add(instanceId);
+ resourceScopes.set(resourceId, scopes);
+ };
+ for (const prop of props.values()) {
+ if (isSelectedInstance(prop.instanceId) === false) {
+ continue;
+ }
+ const baseLocation = withPage(prop.instanceId, {
+ instanceId: prop.instanceId,
+ propId: prop.id,
+ propName: prop.name,
+ path: ["props", prop.id, "value"],
+ });
+ if (prop.type === "resource") {
+ bindingsChecked += 1;
+ addResourceScope(prop.value, prop.instanceId);
+ if (resources.has(prop.value) === false) {
+ findings.push(
+ createFinding(
+ "missing-resource",
+ "prop-resource",
+ { ...baseLocation, resourceId: prop.value },
+ {
+ category: "reference",
+ severity: "error",
+ message: `Prop ${JSON.stringify(prop.name)} references missing resource ${JSON.stringify(prop.value)}.`,
+ remediation:
+ "Bind the prop to an existing resource or remove the stale resource binding.",
+ }
+ )
+ );
+ }
+ continue;
+ }
+ if (prop.type === "parameter") {
+ bindingsChecked += 1;
+ const parameter = dataSources.get(prop.value);
+ const availableIds = new Set(
+ findAvailableVariables({
+ startingInstanceId: prop.instanceId,
+ instances,
+ dataSources,
+ }).map(({ id }) => id)
+ );
+ if (parameter === undefined) {
+ findings.push(
+ createFinding(
+ "missing-parameter",
+ "prop-parameter",
+ { ...baseLocation, dataSourceId: prop.value },
+ {
+ category: "reference",
+ severity: "error",
+ message: `Prop ${JSON.stringify(prop.name)} references missing parameter ${JSON.stringify(prop.value)}.`,
+ remediation:
+ "Rebind the prop to a current parameter available at this instance.",
+ }
+ )
+ );
+ } else if (
+ parameter.scopeInstanceId !== prop.instanceId &&
+ availableIds.has(parameter.id) === false
+ ) {
+ findings.push(
+ createFinding(
+ "out-of-scope-parameter",
+ "prop-parameter",
+ { ...baseLocation, dataSourceId: parameter.id },
+ {
+ category: "scope",
+ severity: "error",
+ message: `Prop ${JSON.stringify(prop.name)} references parameter ${JSON.stringify(parameter.name)} outside its instance scope.`,
+ remediation:
+ "Bind the prop to a parameter available at this instance or move it into the parameter's scope.",
+ }
+ )
+ );
+ }
+ continue;
+ }
+ for (const entry of listPropExpressions(prop)) {
+ verifyExpression({
+ expression: entry.expression,
+ instanceId: prop.instanceId,
+ bindingKind: prop.type === "action" ? "prop-action" : "prop-expression",
+ location: {
+ ...baseLocation,
+ path: [...baseLocation.path, ...entry.path],
+ },
+ allowAssignment: entry.allowAssignment,
+ variables: entry.variables,
+ });
+ }
+ }
+
+ for (const dataSource of dataSources.values()) {
+ if (dataSource.type !== "resource") {
+ continue;
+ }
+ const scopeInstanceId = dataSource.scopeInstanceId ?? ROOT_INSTANCE_ID;
+ if (
+ scopeInstanceId !== ROOT_INSTANCE_ID &&
+ isSelectedInstance(scopeInstanceId) === false
+ ) {
+ continue;
+ }
+ if (
+ scopeInstanceId === ROOT_INSTANCE_ID &&
+ selectedPage === undefined &&
+ input.instanceId !== undefined
+ ) {
+ continue;
+ }
+ bindingsChecked += 1;
+ addResourceScope(dataSource.resourceId, scopeInstanceId);
+ if (resources.has(dataSource.resourceId) === false) {
+ findings.push(
+ createFinding(
+ "missing-resource",
+ "data-source-resource",
+ {
+ instanceId:
+ scopeInstanceId === ROOT_INSTANCE_ID
+ ? undefined
+ : scopeInstanceId,
+ resourceId: dataSource.resourceId,
+ dataSourceId: dataSource.id,
+ path: ["dataSources", dataSource.id, "resourceId"],
+ },
+ {
+ category: "reference",
+ severity: "error",
+ message: `Data source ${JSON.stringify(dataSource.name)} references missing resource ${JSON.stringify(dataSource.resourceId)}.`,
+ remediation:
+ "Reconnect this data source to an existing resource or remove the stale data source.",
+ }
+ )
+ );
+ }
+ }
+
+ if (selectedInstanceIds === undefined && selectedPage === undefined) {
+ for (const resourceId of resources.keys()) {
+ if (resourceScopes.has(resourceId) === false) {
+ addResourceScope(resourceId, ROOT_INSTANCE_ID);
+ }
+ }
+ }
+ for (const [resourceId, scopeInstanceIds] of resourceScopes) {
+ const resource = resources.get(resourceId);
+ if (resource === undefined) {
+ continue;
+ }
+ for (const scopeInstanceId of scopeInstanceIds) {
+ const expressionInstanceId =
+ scopeInstanceId === ROOT_INSTANCE_ID
+ ? (selectedPage?.rootInstanceId ?? ROOT_INSTANCE_ID)
+ : scopeInstanceId;
+ for (const entry of listResourceExpressions(resource)) {
+ verifyExpression({
+ expression: entry.expression,
+ instanceId: expressionInstanceId,
+ bindingKind: "resource-expression",
+ location: withPage(expressionInstanceId, {
+ instanceId:
+ expressionInstanceId === ROOT_INSTANCE_ID
+ ? undefined
+ : expressionInstanceId,
+ resourceId,
+ path: ["resources", resourceId, ...entry.path],
+ }),
+ });
+ }
+ }
+ }
+
+ const metadataPages = selectedPage
+ ? [selectedPage]
+ : input.instanceId === undefined
+ ? [...pages.pages.values()]
+ : [];
+ for (const page of metadataPages) {
+ const availableVariables = new Set<string>(["system"]);
+ for (const dataSource of findAvailableVariables({
+ startingInstanceId: page.rootInstanceId,
+ instances,
+ dataSources,
+ })) {
+ availableVariables.add(dataSource.name);
+ availableVariables.add(encodeDataVariableId(dataSource.id));
+ }
+ for (const entry of listPageMetadataExpressions(page)) {
+ if (
+ shouldVerifyPageMetadataExpression(
+ entry.expression,
+ availableVariables
+ ) === false
+ ) {
+ continue;
+ }
+ verifyExpression({
+ expression: entry.expression,
+ instanceId: page.rootInstanceId,
+ bindingKind: "page-metadata",
+ location: {
+ pageId: page.id,
+ pagePath: pagePathById.get(page.id) ?? "/",
+ instanceId: page.rootInstanceId,
+ path: ["pages", page.id, ...entry.path],
+ },
+ });
+ }
+ }
+
+ const sortedFindings = Array.from(
+ new Map(findings.map((finding) => [finding.id, finding])).values()
+ ).sort((left, right) => left.id.localeCompare(right.id));
+ const { items, ...pagination } = paginateOutput({
+ items: sortedFindings,
+ cursor: input.cursor,
+ limit: input.limit,
+ verbose: input.verbose,
+ filters: {
+ pageId: selectedPage?.id,
+ pagePath: input.pagePath,
+ instanceId: input.instanceId,
+ },
+ invalidCursorMessage: "Invalid binding verification cursor",
+ });
+ return {
+ contractVersion: bindingVerificationContractVersion,
+ analysis: {
+ staticIntegrity: "complete" as const,
+ renderedResolution: "not-evaluated" as const,
+ externalResourcesExecuted: false as const,
+ },
+ summary: { bindingsChecked, findings: sortedFindings.length },
+ findings: items,
+ ...pagination,
+ };
+};
diff --git a/packages/project-build/src/runtime/breakpoints.test.ts b/packages/project-build/src/runtime/breakpoints.test.ts
index 1775572b9e..2c1d5c8b31 100644
--- a/packages/project-build/src/runtime/breakpoints.test.ts
+++ b/packages/project-build/src/runtime/breakpoints.test.ts
@@ -8,6 +8,7 @@ import {
groupBreakpoints,
hasReachedBreakpointLimit,
isBaseBreakpoint,
+ isBaseWidthBreakpoint,
maxBreakpoints,
} from "./breakpoints";
@@ -29,6 +30,10 @@ describe("breakpoint grouping and matching", () => {
expect(isBaseBreakpoint({})).toBe(true);
expect(isBaseBreakpoint({ minWidth: 768 })).toBe(false);
expect(isBaseBreakpoint({ maxWidth: 767 })).toBe(false);
+ expect(isBaseWidthBreakpoint({})).toBe(true);
+ expect(
+ isBaseWidthBreakpoint({ condition: "(prefers-reduced-motion)" })
+ ).toBe(false);
});
test("groups width-based breakpoints separately from custom conditions", () => {
diff --git a/packages/project-build/src/runtime/breakpoints.ts b/packages/project-build/src/runtime/breakpoints.ts
index 36dc5fd3d7..3209395e61 100644
--- a/packages/project-build/src/runtime/breakpoints.ts
+++ b/packages/project-build/src/runtime/breakpoints.ts
@@ -22,6 +22,12 @@ export const isBaseBreakpoint = (breakpoint: {
maxWidth?: number;
}) => breakpoint.minWidth === undefined && breakpoint.maxWidth === undefined;
+export const isBaseWidthBreakpoint = (breakpoint: {
+ minWidth?: number;
+ maxWidth?: number;
+ condition?: string;
+}) => breakpoint.condition === undefined && isBaseBreakpoint(breakpoint);
+
/**
* Group breakpoints into width-based and custom condition categories.
* Width-based breakpoints are ordered: min-width (largest to smallest), base, max-width (largest to smallest).
@@ -86,11 +92,7 @@ export const findClosestBreakpoint = (
return (
closestBreakpoint ??
- existingBreakpoints.find(
- (existingBreakpoint) =>
- existingBreakpoint.condition === undefined &&
- isBaseBreakpoint(existingBreakpoint)
- ) ??
+ existingBreakpoints.find(isBaseWidthBreakpoint) ??
existingBreakpoints[0]
);
};
diff --git a/packages/project-build/src/runtime/component-insert-contract.ts b/packages/project-build/src/runtime/component-insert-contract.ts
index c84e8e3772..ce28ac475d 100644
--- a/packages/project-build/src/runtime/component-insert-contract.ts
+++ b/packages/project-build/src/runtime/component-insert-contract.ts
@@ -9,3 +9,9 @@ export const componentInsertResult = z.object({
});
export type ComponentInsertResult = z.infer<typeof componentInsertResult>;
+
+export const fragmentInsertResult = componentInsertResult.extend({
+ parentInstanceId: z.string().optional(),
+});
+
+export type FragmentInsertResult = z.infer<typeof fragmentInsertResult>;
diff --git a/packages/project-build/src/runtime/components.ts b/packages/project-build/src/runtime/components.ts
index 0bfcb471e0..9953eaea15 100644
--- a/packages/project-build/src/runtime/components.ts
+++ b/packages/project-build/src/runtime/components.ts
@@ -33,7 +33,10 @@ import {
type ComponentTemplateRegistry,
} from "./component-template";
import { isComponentAvailableForDocumentType } from "./component-catalog";
-import type { ComponentInsertResult } from "./component-insert-contract";
+import type {
+ ComponentInsertResult,
+ FragmentInsertResult,
+} from "./component-insert-contract";
import {
createCollectionFragment,
insertCollectionInput,
@@ -50,7 +53,7 @@ import {
insertIndexInput,
instanceInsertModeInput,
} from "./instances";
-import { createRuntimeMutation } from "./mutation";
+import { createRuntimeMutation, type BuilderRuntimeMutation } from "./mutation";
import { getSlotFragmentDropTargetMutable } from "./slot";
import type { ConflictResolution } from "./style-copy";
import { z } from "zod";
@@ -1001,7 +1004,7 @@ export const insertFragment = (
state: ComponentInsertState,
input: z.infer<typeof insertFragmentInput>,
context: BuilderRuntimeContext
-) => {
+): BuilderRuntimeMutation<FragmentInsertResult> => {
if (input.fragment.children.length === 0) {
return createInsertTokenFragmentMutation({
state,
diff --git a/packages/project-build/src/runtime/craft-profile.test-fixtures.ts b/packages/project-build/src/runtime/craft-profile.test-fixtures.ts
new file mode 100644
index 0000000000..f4defec081
--- /dev/null
+++ b/packages/project-build/src/runtime/craft-profile.test-fixtures.ts
@@ -0,0 +1,100 @@
+import type { StyleDecl, Styles } from "@webstudio-is/sdk";
+import { ROOT_INSTANCE_ID } from "@webstudio-is/sdk";
+import type { BuilderState } from "../state/builder-state";
+import { craftProfile } from "./craft-profile";
+
+const keyword = (value: string) => ({ type: "keyword" as const, value });
+
+export const createCraftFixture = (
+ variant: "compatible" | "partial" | "modified" | "non-craft"
+): BuilderState => {
+ if (variant === "non-craft") {
+ return {
+ styles: new Map(),
+ styleSources: new Map(),
+ styleSourceSelections: new Map(),
+ };
+ }
+ const variableNames =
+ variant === "partial"
+ ? craftProfile.checks.required.semanticVariables.slice(0, 3)
+ : craftProfile.checks.required.semanticVariables;
+ const styles: Styles = new Map(
+ variableNames.map((property) => [
+ `global:base:${property}`,
+ {
+ styleSourceId: "global",
+ breakpointId: "base",
+ property,
+ value: keyword("initial"),
+ },
+ ])
+ );
+ if (variant !== "partial") {
+ styles.set("container:base:display", {
+ styleSourceId: "container",
+ breakpointId: "base",
+ property: "display",
+ value: keyword("flex"),
+ });
+ styles.set("container:base:flexDirection", {
+ styleSourceId: "container",
+ breakpointId: "base",
+ property: "flexDirection",
+ value: keyword(variant === "compatible" ? "column" : "row"),
+ });
+ styles.set("container:base:columnGap", {
+ styleSourceId: "container",
+ breakpointId: "base",
+ property: "columnGap" as StyleDecl["property"],
+ value: { type: "var", value: "gap-m" },
+ });
+ styles.set("container:base:rowGap", {
+ styleSourceId: "container",
+ breakpointId: "base",
+ property: "rowGap" as StyleDecl["property"],
+ value: { type: "var", value: "gap-m" },
+ });
+ }
+ return {
+ pages: {
+ homePageId: "style-guide",
+ rootFolderId: "root",
+ redirects: [],
+ pages: new Map([
+ [
+ "style-guide",
+ {
+ id: "style-guide",
+ name: "Style Guide",
+ title: "Style Guide",
+ path: "",
+ rootInstanceId: "body",
+ meta: {},
+ },
+ ],
+ ]),
+ folders: new Map([
+ [
+ "root",
+ { id: "root", name: "Root", slug: "", children: ["style-guide"] },
+ ],
+ ]),
+ },
+ styleSources: new Map([
+ ["global", { id: "global", type: "local" }],
+ ...(variant === "partial"
+ ? []
+ : [
+ [
+ "container",
+ { id: "container", type: "token" as const, name: "container" },
+ ] as const,
+ ]),
+ ]),
+ styleSourceSelections: new Map([
+ [ROOT_INSTANCE_ID, { instanceId: ROOT_INSTANCE_ID, values: ["global"] }],
+ ]),
+ styles,
+ };
+};
diff --git a/packages/project-build/src/runtime/craft-profile.test.ts b/packages/project-build/src/runtime/craft-profile.test.ts
new file mode 100644
index 0000000000..58b4b22883
--- /dev/null
+++ b/packages/project-build/src/runtime/craft-profile.test.ts
@@ -0,0 +1,254 @@
+import { describe, expect, test } from "vitest";
+import type { BuilderState } from "../state/builder-state";
+import { audit } from "./audit";
+import {
+ analyzeCraftProfile,
+ craftOfficialReferenceSnapshot,
+ craftProfile,
+} from "./craft-profile";
+import { createCraftFixture } from "./craft-profile.test-fixtures";
+import { state as completeRuntimeState } from "./runtime.test-fixtures";
+import { executeBuilderRuntimeOperation } from "./registry";
+import {
+ createCraftReviewedDifferenceTable,
+ hashCraftSnapshot,
+} from "./craft-snapshot-provenance";
+
+describe("Craft authoring profile", () => {
+ test("keeps the machine-readable profile versioned and attributable", () => {
+ expect(craftProfile).toMatchObject({
+ id: "craft",
+ schemaVersion: 1,
+ craftVersion: "1.2",
+ provenance: {
+ title: expect.stringContaining("Craft"),
+ url: "https://docs.webstudio.is/university/craft",
+ authentication: "authenticated",
+ official: {
+ projectId: "3f260731-825b-486a-b534-e747f0ed6106",
+ buildId: "8f281723-e950-45a1-801c-247d692cd1ba",
+ version: 1730,
+ },
+ capture: {
+ capturedAt: expect.any(String),
+ snapshotHash: expect.stringMatching(/^sha256:/),
+ },
+ docs: {
+ capturedAt: expect.any(String),
+ contentHash: expect.stringMatching(/^sha256:/),
+ },
+ reviewedDifferences: {
+ reviewedAt: expect.any(String),
+ rows: expect.arrayContaining([
+ expect.objectContaining({ path: "container.maxWidth" }),
+ expect.objectContaining({ path: "styleGuidePage.name" }),
+ ]),
+ },
+ },
+ checks: {
+ required: expect.any(Object),
+ recommended: expect.any(Object),
+ informational: expect.any(Object),
+ },
+ });
+ });
+
+ test("keeps the reviewed official-project differences attributable", async () => {
+ const table = await createCraftReviewedDifferenceTable(
+ craftProfile.provenance.reviewedDifferences.rows
+ );
+
+ expect(table.tableHash).toBe(
+ craftProfile.provenance.reviewedDifferences.tableHash
+ );
+ });
+
+ test("keeps the sanitized official compatibility snapshot attributable", async () => {
+ expect(await hashCraftSnapshot(craftOfficialReferenceSnapshot)).toBe(
+ craftProfile.provenance.capture.snapshotHash
+ );
+ expect(craftOfficialReferenceSnapshot.semanticVariables).toEqual(
+ craftProfile.checks.required.semanticVariables
+ );
+ expect(craftOfficialReferenceSnapshot.pageNames).toContain(
+ "CSS Variables + Style Guide"
+ );
+ });
+
+ test("recognizes a known-good Craft fixture", () => {
+ const result = analyzeCraftProfile(createCraftFixture("compatible"));
+
+ expect(result.status).toMatchObject({
+ status: "compatible",
+ satisfiedRequiredChecks: 2,
+ totalRequiredChecks: 2,
+ nextAction: "No Craft profile change is required.",
+ templateCompatibility: { status: "compatible" },
+ guidance: expect.arrayContaining([
+ expect.stringContaining("Preserve existing project-specific values"),
+ ]),
+ });
+ expect(result.matches).toEqual([]);
+ });
+
+ test("recognizes the official reference page naming convention", () => {
+ const state = createCraftFixture("compatible");
+ const page = state.pages?.pages.get("style-guide");
+ if (page === undefined) {
+ throw new Error("Expected Craft fixture page");
+ }
+ page.name = "CSS Variables + Style Guide";
+
+ expect(analyzeCraftProfile(state)).toMatchObject({
+ status: { status: "compatible" },
+ matches: [],
+ });
+ });
+
+ test("reports a partial fixture with bounded evidence and a safe next action", () => {
+ const result = analyzeCraftProfile(createCraftFixture("partial"));
+
+ expect(result.status).toMatchObject({
+ status: "partial",
+ satisfiedRequiredChecks: 0,
+ nextAction: expect.stringContaining("--foreground-muted"),
+ templateCompatibility: { status: "requires-review" },
+ });
+ expect(result.matches).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "craft-missing-semantic-variables",
+ missingVariables: expect.arrayContaining(["--foreground-muted"]),
+ }),
+ expect.objectContaining({ issue: "craft-container-token-missing" }),
+ ])
+ );
+ });
+
+ test("distinguishes a complete but modified Craft fixture", () => {
+ const result = analyzeCraftProfile(createCraftFixture("modified"));
+
+ expect(result.status).toMatchObject({
+ status: "modified",
+ satisfiedRequiredChecks: 1,
+ nextAction: "Correct the container token's flexDirection declaration.",
+ });
+ expect(result.matches).toEqual([
+ expect.objectContaining({
+ issue: "craft-container-token-incompatible",
+ mismatches: ["flexDirection"],
+ }),
+ ]);
+ });
+
+ test("does not use a generic Style Guide page to characterize Craft", () => {
+ const result = analyzeCraftProfile({
+ pages: createCraftFixture("compatible").pages,
+ styles: new Map(),
+ styleSources: new Map(),
+ });
+
+ expect(result.status.status).toBe("non-craft");
+ expect(result.matches).toEqual([
+ expect.objectContaining({ issue: "craft-not-detected" }),
+ ]);
+
+ const absent = analyzeCraftProfile({
+ styles: new Map(),
+ styleSources: new Map(),
+ });
+ expect(absent.status.status).toBe("non-craft");
+ expect(absent.status.templateCompatibility.status).toBe("not-applicable");
+ expect(absent.matches).toEqual([
+ expect.objectContaining({ issue: "craft-not-detected" }),
+ ]);
+ });
+
+ test.each(["compatible", "partial", "modified", "non-craft"] as const)(
+ "keeps the %s synthetic fixture stable and does not mutate it",
+ (variant) => {
+ const state = createCraftFixture(variant);
+ const before = structuredClone(state);
+ const first = analyzeCraftProfile(state);
+ const second = analyzeCraftProfile(state);
+
+ expect(first).toEqual(second);
+ expect(first.status.status).toBe(variant);
+ expect(first.status.nextAction).toBe(second.status.nextAction);
+ expect(state).toEqual(before);
+ }
+ );
+
+ test("runs only when explicitly selected and never mutates project data", () => {
+ const state = { ...completeRuntimeState, ...createCraftFixture("partial") };
+ const before = structuredClone(state);
+
+ const defaultResult = audit(state, {}, { projectVersion: 3 });
+ const craftResult = audit(
+ state,
+ { scopes: ["craft"], verbose: true },
+ { projectVersion: 3 }
+ );
+
+ expect(defaultResult.scopes).not.toContain("craft");
+ expect(defaultResult.profileStatuses).toEqual([]);
+ expect(defaultResult.findings).not.toEqual(
+ expect.arrayContaining([expect.objectContaining({ scope: "craft" })])
+ );
+ expect(craftResult.scopes).toEqual(["craft"]);
+ expect(craftResult.profileStatuses).toEqual([
+ expect.objectContaining({
+ id: "craft",
+ status: "partial",
+ sourceUrl: craftProfile.provenance.url,
+ nextAction: expect.any(String),
+ }),
+ ]);
+ expect(craftResult.findings.every(({ scope }) => scope === "craft")).toBe(
+ true
+ );
+ expect(state).toEqual(before);
+ });
+
+ test("keeps profile status stable across paginated findings", () => {
+ const state: BuilderState = createCraftFixture("partial");
+ const first = audit(
+ state,
+ { scopes: ["craft"], limit: 1 },
+ { projectVersion: 4 }
+ );
+ const second = audit(
+ state,
+ {
+ scopes: ["craft"],
+ limit: 1,
+ cursor: first.nextCursor ?? undefined,
+ },
+ { projectVersion: 4 }
+ );
+
+ expect(first.nextCursor).not.toBeNull();
+ expect(second.profileStatuses).toEqual(first.profileStatuses);
+ expect(second.findings[0]?.id).not.toBe(first.findings[0]?.id);
+ });
+
+ test("exposes the opt-in profile through the public runtime operation", () => {
+ const result = executeBuilderRuntimeOperation({
+ id: "project.audit",
+ state: { ...completeRuntimeState, ...createCraftFixture("compatible") },
+ input: { scopes: ["craft"] },
+ context: { projectVersion: 8, createId: () => "unused" },
+ });
+
+ expect(result).toMatchObject({
+ scopes: ["craft"],
+ findings: [],
+ profileStatuses: [
+ {
+ status: "compatible",
+ sourceUrl: craftProfile.provenance.url,
+ },
+ ],
+ });
+ });
+});
diff --git a/packages/project-build/src/runtime/craft-profile.ts b/packages/project-build/src/runtime/craft-profile.ts
new file mode 100644
index 0000000000..808f3817a1
--- /dev/null
+++ b/packages/project-build/src/runtime/craft-profile.ts
@@ -0,0 +1,405 @@
+import { toValue } from "@webstudio-is/css-engine";
+import { ROOT_INSTANCE_ID } from "@webstudio-is/sdk";
+import { z } from "zod";
+import type { BuilderState } from "../state/builder-state";
+import { compareCraftSnapshotText } from "./craft-snapshot-provenance";
+
+/** Sanitized compatibility inventory captured from the authenticated template. */
+export const craftOfficialReferenceSnapshot = {
+ projectId: "3f260731-825b-486a-b534-e747f0ed6106",
+ buildId: "8f281723-e950-45a1-801c-247d692cd1ba",
+ version: 1730,
+ updatedAt: "2026-02-10T14:31:11.699+00:00",
+ counts: {
+ pages: 3,
+ breakpoints: 4,
+ styles: 915,
+ styleSources: 97,
+ styleSourceSelections: 177,
+ assets: 3,
+ },
+ pageNames: ["Readme", "CSS Variables", "CSS Variables + Style Guide"],
+ breakpoints: [
+ { label: "Base", minWidth: null, maxWidth: null },
+ { label: "Tablet", minWidth: null, maxWidth: 991 },
+ { label: "Mobile landscape", minWidth: null, maxWidth: 767 },
+ { label: "Mobile portrait", minWidth: null, maxWidth: 479 },
+ ],
+ semanticVariables: [
+ "--foreground-primary",
+ "--foreground-secondary",
+ "--foreground-accent",
+ "--foreground-muted",
+ "--foreground-border",
+ "--background-primary",
+ "--background-secondary",
+ "--background-accent",
+ "--background-card",
+ "--gap-xs",
+ "--gap-s",
+ "--gap-m",
+ "--gap-l",
+ "--spacing-default",
+ "--focus-color",
+ "--focus-width",
+ "--focus-offset",
+ "--duration-default",
+ "--easing-default",
+ ],
+ containerToken: {
+ display: "flex",
+ flexDirection: "column",
+ columnGap: "var(--gap-m)",
+ rowGap: "var(--gap-m)",
+ marginLeft: "auto",
+ marginRight: "auto",
+ paddingLeft: "var(--spacing-default)",
+ paddingRight: "var(--spacing-default)",
+ width: "100%",
+ maxWidth: "var(--size-lg, 1024px)",
+ },
+} as const;
+
+const craftSourceUrl = "https://docs.webstudio.is/university/craft";
+const craftCapturedAt = "2026-07-15T20:20:45.000Z";
+const { display, flexDirection, columnGap, rowGap } =
+ craftOfficialReferenceSnapshot.containerToken;
+const craftRequiredContainerDeclarations = {
+ display,
+ flexDirection,
+ columnGap,
+ rowGap,
+};
+
+export const craftProfile = {
+ id: "craft",
+ schemaVersion: 1,
+ craftVersion: "1.2",
+ provenance: {
+ title: "Craft - the standard for building with Webstudio",
+ url: craftSourceUrl,
+ authentication: "authenticated",
+ official: {
+ projectId: craftOfficialReferenceSnapshot.projectId,
+ buildId: craftOfficialReferenceSnapshot.buildId,
+ version: craftOfficialReferenceSnapshot.version,
+ },
+ capture: {
+ capturedAt: craftCapturedAt,
+ snapshotHash:
+ "sha256:b6c87d4df9cb39f4f955cbb574cd0aeffa4fe13ba2dd2f9275376e87dd77cc76",
+ },
+ docs: {
+ url: craftSourceUrl,
+ capturedAt: craftCapturedAt,
+ contentHash:
+ "sha256:c71e60d546343b4cb5fcd719d9ac05a98b2695751bfe511d36952714be047a83",
+ },
+ reviewedDifferences: {
+ reviewedAt: craftCapturedAt,
+ tableHash:
+ "sha256:20c2c2749f966cf63d270b141157ff76405d7de9851f9564f9f812ace4ec7c9d",
+ rows: [
+ {
+ path: "container.marginLeft",
+ kind: "added",
+ officialValue: "auto",
+ profileValue: null,
+ review:
+ "Reference-project layout default; not required by the documented Craft 1.2 compatibility contract.",
+ },
+ {
+ path: "container.marginRight",
+ kind: "added",
+ officialValue: "auto",
+ profileValue: null,
+ review:
+ "Reference-project layout default; not required by the documented Craft 1.2 compatibility contract.",
+ },
+ {
+ path: "container.maxWidth",
+ kind: "added",
+ officialValue: "var(--size-lg, 1024px)",
+ profileValue: null,
+ review:
+ "Reference-project layout default; projects may intentionally choose another container width.",
+ },
+ {
+ path: "container.paddingLeft",
+ kind: "added",
+ officialValue: "var(--spacing-default)",
+ profileValue: null,
+ review:
+ "Recommended reference-project spacing; not required for Craft compatibility.",
+ },
+ {
+ path: "container.paddingRight",
+ kind: "added",
+ officialValue: "var(--spacing-default)",
+ profileValue: null,
+ review:
+ "Recommended reference-project spacing; not required for Craft compatibility.",
+ },
+ {
+ path: "container.width",
+ kind: "added",
+ officialValue: "100%",
+ profileValue: null,
+ review:
+ "Reference-project layout default; not required by the documented Craft 1.2 compatibility contract.",
+ },
+ {
+ path: "styleGuidePage.name",
+ kind: "changed",
+ officialValue: "CSS Variables + Style Guide",
+ profileValue: "name containing Style Guide",
+ review:
+ "Match the semantic reference-page purpose without requiring one exact project-specific name.",
+ },
+ ],
+ },
+ limitations: [
+ "The University page does not enumerate the Open Props inventory, so this profile checks only the Webstudio-specific variables it names.",
+ "Subjective navigator and token-usage guidance is informational and does not affect compatibility status.",
+ ],
+ },
+ checks: {
+ required: {
+ semanticVariables: [...craftOfficialReferenceSnapshot.semanticVariables],
+ containerToken: {
+ name: "container",
+ declarations: craftRequiredContainerDeclarations,
+ },
+ },
+ recommended: {
+ styleGuidePageName: "Style Guide",
+ },
+ informational: {
+ navigatorNaming:
+ "Use semantic Title Case labels; name generic Box, Slot, HTML Embed, and Collection instances.",
+ tokenNaming:
+ "Use kebab case for utility, variant, and size tokens; use title case for semantic tokens.",
+ },
+ },
+} as const;
+
+export const craftProfileStatus = z.object({
+ id: z.literal(craftProfile.id),
+ profileVersion: z.literal(craftProfile.schemaVersion),
+ craftVersion: z.literal(craftProfile.craftVersion),
+ sourceUrl: z.literal(craftProfile.provenance.url),
+ status: z.enum(["non-craft", "partial", "modified", "compatible"]),
+ satisfiedRequiredChecks: z.number().int().nonnegative(),
+ totalRequiredChecks: z.number().int().positive(),
+ nextAction: z.string().min(1),
+ guidance: z.array(z.string().min(1)),
+ templateCompatibility: z.object({
+ profile: z.literal(`${craftProfile.id}@${craftProfile.craftVersion}`),
+ status: z.enum(["compatible", "requires-review", "not-applicable"]),
+ reason: z.string().min(1),
+ }),
+});
+
+export type CraftProfileStatus = z.infer<typeof craftProfileStatus>;
+export type CraftStatus = CraftProfileStatus["status"];
+
+export type CraftAuditMatch = Record<string, unknown> & {
+ issue: string;
+ kind: "craft";
+ message: string;
+};
+
+const getContainerTokenState = (state: BuilderState) => {
+ const expected = craftProfile.checks.required.containerToken;
+ const token = Array.from(state.styleSources?.values() ?? [])
+ .filter(
+ (source) => source.type === "token" && source.name === expected.name
+ )
+ .sort((left, right) => compareCraftSnapshotText(left.id, right.id))[0];
+ if (token === undefined) {
+ return { exists: false, compatible: false, mismatches: [] as string[] };
+ }
+ const valuesByBreakpoint = new Map<string, Map<string, string>>();
+ for (const declaration of state.styles?.values() ?? []) {
+ if (
+ declaration.styleSourceId === token.id &&
+ declaration.state === undefined
+ ) {
+ let values = valuesByBreakpoint.get(declaration.breakpointId);
+ if (values === undefined) {
+ values = new Map();
+ valuesByBreakpoint.set(declaration.breakpointId, values);
+ }
+ values.set(declaration.property, toValue(declaration.value));
+ }
+ }
+ const mismatchesByBreakpoint = Array.from(valuesByBreakpoint.entries())
+ .sort(([left], [right]) => compareCraftSnapshotText(left, right))
+ .map(([, values]) =>
+ Object.entries(expected.declarations)
+ .filter(([property, value]) => values.get(property) !== value)
+ .map(([property]) => property)
+ );
+ const mismatches =
+ mismatchesByBreakpoint.reduce<string[] | undefined>(
+ (best, candidate) =>
+ best === undefined || candidate.length < best.length ? candidate : best,
+ undefined
+ ) ?? Object.keys(expected.declarations);
+ return {
+ exists: true,
+ compatible: mismatches.length === 0,
+ mismatches,
+ styleSourceId: token.id,
+ };
+};
+
+export const analyzeCraftProfile = (
+ state: BuilderState
+): { status: CraftProfileStatus; matches: CraftAuditMatch[] } => {
+ const requiredVariables = craftProfile.checks.required.semanticVariables;
+ const rootStyleSourceIds = new Set(
+ state.styleSourceSelections?.get(ROOT_INSTANCE_ID)?.values ?? []
+ );
+ const allDefinedVariables = new Set(
+ Array.from(state.styles?.values() ?? [])
+ .map(({ property }) => property)
+ .filter((property) => property.startsWith("--"))
+ );
+ const definedVariables = new Set(
+ Array.from(state.styles?.values() ?? [])
+ .filter(({ styleSourceId }) => rootStyleSourceIds.has(styleSourceId))
+ .map(({ property }) => property)
+ .filter((property) => property.startsWith("--"))
+ );
+ const missingVariables = requiredVariables.filter(
+ (name) => definedVariables.has(name) === false
+ );
+ const variablesOutsideGlobalRoot = missingVariables.filter((name) =>
+ allDefinedVariables.has(name)
+ );
+ const container = getContainerTokenState(state);
+ const hasStyleGuide = Array.from(state.pages?.pages.values() ?? []).some(
+ (page) =>
+ page.name
+ .toLocaleLowerCase()
+ .includes(
+ craftProfile.checks.recommended.styleGuidePageName.toLocaleLowerCase()
+ )
+ );
+ const detected =
+ missingVariables.length < requiredVariables.length || container.exists;
+ const requiredResults = [missingVariables.length === 0, container.compatible];
+ const satisfiedRequiredChecks = requiredResults.filter(Boolean).length;
+ const status: CraftStatus =
+ detected === false
+ ? "non-craft"
+ : missingVariables.length > 0 || container.exists === false
+ ? "partial"
+ : container.compatible === false
+ ? "modified"
+ : "compatible";
+ const matches: CraftAuditMatch[] = [];
+
+ if (detected === false) {
+ matches.push({
+ kind: "craft",
+ issue: "craft-not-detected",
+ message: "This project does not currently appear to use Craft.",
+ detectedVariableCount: 0,
+ });
+ } else {
+ if (missingVariables.length > 0) {
+ matches.push({
+ kind: "craft",
+ issue: "craft-missing-semantic-variables",
+ message: `Craft is missing ${missingVariables.length} required semantic variable${missingVariables.length === 1 ? "" : "s"}.`,
+ missingVariables,
+ variablesOutsideGlobalRoot,
+ });
+ }
+ if (container.exists === false) {
+ matches.push({
+ kind: "craft",
+ issue: "craft-container-token-missing",
+ message: 'Craft requires a design token named "container".',
+ });
+ } else if (container.compatible === false) {
+ matches.push({
+ kind: "craft",
+ issue: "craft-container-token-incompatible",
+ message: `The container token does not match Craft 1.2 (${container.mismatches.join(", ")}).`,
+ designTokenId: container.styleSourceId,
+ mismatches: container.mismatches,
+ });
+ }
+ if (hasStyleGuide === false) {
+ matches.push({
+ kind: "craft",
+ issue: "craft-style-guide-page-missing",
+ message: "Craft recommends keeping an internal Style Guide page.",
+ });
+ }
+ }
+
+ const nextAction =
+ detected === false
+ ? "Insert the Craft Style Guide page from Marketplace only if this project should adopt Craft."
+ : missingVariables.length > 0
+ ? `Define ${missingVariables[0]} on Global Root, then rerun the Craft audit.`
+ : container.exists === false
+ ? 'Create the "container" token with the documented Craft 1.2 declarations.'
+ : container.compatible === false
+ ? `Correct the container token's ${container.mismatches[0]} declaration.`
+ : hasStyleGuide === false
+ ? "Add an internal reference page whose name identifies it as a Style Guide."
+ : "No Craft profile change is required.";
+ const guidance =
+ status === "non-craft"
+ ? [
+ "Do not add Craft variables, tokens, or templates unless the user explicitly chooses to adopt Craft.",
+ "Preserve the project's existing design system and evaluate non-Craft templates on their own requirements.",
+ ]
+ : [
+ "Preserve existing project-specific values and non-Craft styles; change only the reported missing or incompatible Craft requirement.",
+ "Prefer templates compatible with Craft 1.2 and resolve reported profile differences before insertion.",
+ "Rerun the Craft audit after each bounded repair instead of replacing the project's design system wholesale.",
+ ];
+ const templateCompatibility =
+ status === "non-craft"
+ ? {
+ profile: `${craftProfile.id}@${craftProfile.craftVersion}` as const,
+ status: "not-applicable" as const,
+ reason:
+ "This project does not use Craft; do not apply Craft-specific templates implicitly.",
+ }
+ : status === "compatible"
+ ? {
+ profile: `${craftProfile.id}@${craftProfile.craftVersion}` as const,
+ status: "compatible" as const,
+ reason:
+ "The project satisfies the required Craft 1.2 variables and container token contract.",
+ }
+ : {
+ profile: `${craftProfile.id}@${craftProfile.craftVersion}` as const,
+ status: "requires-review" as const,
+ reason:
+ "Resolve the reported Craft requirements before inserting a template that depends on Craft 1.2.",
+ };
+
+ return {
+ status: {
+ id: craftProfile.id,
+ profileVersion: craftProfile.schemaVersion,
+ craftVersion: craftProfile.craftVersion,
+ sourceUrl: craftProfile.provenance.url,
+ status,
+ satisfiedRequiredChecks,
+ totalRequiredChecks: requiredResults.length,
+ nextAction,
+ guidance,
+ templateCompatibility,
+ },
+ matches,
+ };
+};
diff --git a/packages/project-build/src/runtime/craft-snapshot-provenance.test.ts b/packages/project-build/src/runtime/craft-snapshot-provenance.test.ts
new file mode 100644
index 0000000000..d6eefa27a3
--- /dev/null
+++ b/packages/project-build/src/runtime/craft-snapshot-provenance.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, test } from "vitest";
+import {
+ craftSnapshotProvenance,
+ createCraftReviewedDifferenceTable,
+ createUnverifiedCraftProvenance,
+ hashCraftSnapshot,
+ normalizeCraftSnapshot,
+ normalizeCraftSnapshotText,
+} from "./craft-snapshot-provenance";
+
+describe("Craft snapshot provenance", () => {
+ test("normalizes text and JSON without mutating the input", () => {
+ const input = {
+ z: "e\u0301 \r\n",
+ password: "do-not-retain",
+ authToken: "also-do-not-retain",
+ url: "https://example.com/?authToken=private-token&mode=design",
+ a: [{ authorization: "Bearer private" }, -0, Number.NaN, undefined],
+ };
+ const before = structuredClone(input);
+
+ expect(normalizeCraftSnapshotText("\uFEFFa \r\nb\t")).toBe("a\nb");
+ expect(normalizeCraftSnapshot(input)).toEqual({
+ a: [{ authorization: "[REDACTED]" }, 0, null, null],
+ authToken: "[REDACTED]",
+ password: "[REDACTED]",
+ url: "https://example.com/?authToken=[REDACTED]&mode=design",
+ z: "é\n",
+ });
+ expect(input).toEqual(before);
+ });
+
+ test("hashes equivalent normalized snapshots identically", async () => {
+ const left = await hashCraftSnapshot({ b: "x\r\n", a: 1 });
+ const right = await hashCraftSnapshot({ a: 1, b: "x\n" });
+
+ expect(left).toBe(right);
+ expect(left).toMatch(/^sha256:[0-9a-f]{64}$/);
+ });
+
+ test("sorts and hashes the reviewed difference table deterministically", async () => {
+ const rows = [
+ {
+ path: "tokens.container.gap",
+ kind: "changed" as const,
+ officialValue: "var(--gap-m)",
+ profileValue: "var(--gap-l)",
+ review: "Intentional local override",
+ },
+ {
+ path: "variables.--focus-width",
+ kind: "missing" as const,
+ officialValue: "captured value",
+ profileValue: null,
+ review: "Not represented by this profile",
+ },
+ ];
+
+ const forward = await createCraftReviewedDifferenceTable(rows);
+ const reverse = await createCraftReviewedDifferenceTable(
+ [...rows].reverse()
+ );
+
+ expect(reverse).toEqual(forward);
+ expect(forward.rows.map(({ path }) => path)).toEqual([
+ "tokens.container.gap",
+ "variables.--focus-width",
+ ]);
+
+ await expect(
+ createCraftReviewedDifferenceTable([rows[0], rows[0]])
+ ).rejects.toThrow("Reviewed Craft difference paths must be unique");
+ });
+
+ test("represents missing official evidence explicitly", async () => {
+ const provenance = await createUnverifiedCraftProvenance(
+ "https://docs.webstudio.is/university/craft"
+ );
+
+ expect(craftSnapshotProvenance.parse(provenance)).toEqual(provenance);
+ expect(provenance).toMatchObject({
+ authentication: "unverified",
+ official: { projectId: null, buildId: null, version: null },
+ capture: { capturedAt: null, snapshotHash: null },
+ docs: { capturedAt: null, contentHash: null },
+ reviewedDifferences: { reviewedAt: null, rows: [] },
+ });
+ });
+});
diff --git a/packages/project-build/src/runtime/craft-snapshot-provenance.ts b/packages/project-build/src/runtime/craft-snapshot-provenance.ts
new file mode 100644
index 0000000000..89828c37b8
--- /dev/null
+++ b/packages/project-build/src/runtime/craft-snapshot-provenance.ts
@@ -0,0 +1,214 @@
+import { z } from "zod";
+
+const jsonPrimitive = z.union([z.string(), z.number(), z.boolean(), z.null()]);
+
+export type CraftSnapshotValue =
+ | z.infer<typeof jsonPrimitive>
+ | CraftSnapshotValue[]
+ | { [key: string]: CraftSnapshotValue };
+
+export const craftSnapshotHash = z.string().regex(/^sha256:[0-9a-f]{64}$/);
+
+export const craftReviewedDifference = z.object({
+ path: z.string().min(1),
+ kind: z.enum(["missing", "added", "changed"]),
+ officialValue: z.string().nullable(),
+ profileValue: z.string().nullable(),
+ review: z.string().min(1),
+});
+
+export type CraftReviewedDifference = z.infer<typeof craftReviewedDifference>;
+
+export const craftReviewedDifferenceTable = z
+ .object({
+ tableHash: craftSnapshotHash,
+ rows: z.array(craftReviewedDifference),
+ })
+ .superRefine(({ rows }, context) => {
+ const paths = new Set<string>();
+ for (const [index, row] of rows.entries()) {
+ if (paths.has(row.path)) {
+ context.addIssue({
+ code: "custom",
+ path: ["rows", index, "path"],
+ message: "Reviewed Craft difference paths must be unique",
+ });
+ }
+ paths.add(row.path);
+ }
+ });
+
+export const craftSnapshotProvenance = z.object({
+ schemaVersion: z.literal(1),
+ authentication: z.enum(["unverified", "authenticated"]),
+ official: z.object({
+ projectId: z.string().min(1).nullable(),
+ buildId: z.string().min(1).nullable(),
+ version: z.number().int().nonnegative().nullable(),
+ }),
+ capture: z.object({
+ capturedAt: z.string().datetime().nullable(),
+ snapshotHash: craftSnapshotHash.nullable(),
+ }),
+ docs: z.object({
+ url: z.string().url(),
+ capturedAt: z.string().datetime().nullable(),
+ contentHash: craftSnapshotHash.nullable(),
+ }),
+ reviewedDifferences: craftReviewedDifferenceTable.extend({
+ reviewedAt: z.string().datetime().nullable(),
+ }),
+});
+
+export type CraftSnapshotProvenance = z.infer<typeof craftSnapshotProvenance>;
+
+const sensitiveKeys = new Set([
+ "accesstoken",
+ "apikey",
+ "authtoken",
+ "authorization",
+ "clientsecret",
+ "cookie",
+ "password",
+ "privatekey",
+ "refreshtoken",
+ "secret",
+ "sessiontoken",
+]);
+
+export const compareCraftSnapshotText = (left: string, right: string) =>
+ left < right ? -1 : left > right ? 1 : 0;
+
+export const normalizeCraftSnapshotText = (value: string) =>
+ value
+ .replace(/^\uFEFF/, "")
+ .replace(/\r\n?/g, "\n")
+ .normalize("NFC")
+ .split("\n")
+ .map((line) => line.replace(/[\t ]+$/g, ""))
+ .join("\n");
+
+const sanitizeCraftSnapshotText = (value: string) =>
+ normalizeCraftSnapshotText(value)
+ .replace(
+ /([?&](?:authToken|access_token|api_key|refresh_token|session_token)=)[^&#\s]*/gi,
+ "$1[REDACTED]"
+ )
+ .replace(/\bBearer\s+[^\s"']+/gi, "Bearer [REDACTED]");
+
+const normalizeSnapshotValue = (
+ value: unknown,
+ ancestors: Set<object>
+): CraftSnapshotValue | undefined => {
+ if (value === null || typeof value === "boolean") {
+ return value;
+ }
+ if (typeof value === "string") {
+ return sanitizeCraftSnapshotText(value);
+ }
+ if (typeof value === "number") {
+ return Number.isFinite(value) ? (Object.is(value, -0) ? 0 : value) : null;
+ }
+ if (typeof value !== "object") {
+ return undefined;
+ }
+ if (ancestors.has(value)) {
+ throw new TypeError("Craft snapshots must not contain circular values");
+ }
+ ancestors.add(value);
+ if (Array.isArray(value)) {
+ const normalized = value.map(
+ (item) => normalizeSnapshotValue(item, ancestors) ?? null
+ );
+ ancestors.delete(value);
+ return normalized;
+ }
+ const normalized: Record<string, CraftSnapshotValue> = {};
+ const record = value as Record<string, unknown>;
+ for (const key of Object.keys(record).sort(compareCraftSnapshotText)) {
+ const normalizedKey = normalizeCraftSnapshotText(key);
+ const normalizedValue = sensitiveKeys.has(
+ normalizedKey.replace(/[-_]/g, "").toLowerCase()
+ )
+ ? "[REDACTED]"
+ : normalizeSnapshotValue(record[key], ancestors);
+ if (normalizedValue !== undefined) {
+ normalized[normalizedKey] = normalizedValue;
+ }
+ }
+ ancestors.delete(value);
+ return normalized;
+};
+
+/** Produces JSON-safe, key-ordered data before any snapshot comparison or hash. */
+export const normalizeCraftSnapshot = (value: unknown): CraftSnapshotValue =>
+ normalizeSnapshotValue(value, new Set()) ?? null;
+
+export const serializeCraftSnapshot = (value: unknown) =>
+ JSON.stringify(normalizeCraftSnapshot(value));
+
+export const hashCraftSnapshot = async (value: unknown) => {
+ const bytes = new TextEncoder().encode(serializeCraftSnapshot(value));
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
+ return `sha256:${Array.from(new Uint8Array(digest), (byte) =>
+ byte.toString(16).padStart(2, "0")
+ ).join("")}` as const;
+};
+
+const compareDifferences = (
+ left: CraftReviewedDifference,
+ right: CraftReviewedDifference
+) =>
+ compareCraftSnapshotText(left.path, right.path) ||
+ compareCraftSnapshotText(left.kind, right.kind) ||
+ compareCraftSnapshotText(
+ left.officialValue ?? "",
+ right.officialValue ?? ""
+ ) ||
+ compareCraftSnapshotText(left.profileValue ?? "", right.profileValue ?? "") ||
+ compareCraftSnapshotText(left.review, right.review);
+
+export const normalizeCraftReviewedDifferences = (
+ rows: readonly CraftReviewedDifference[]
+) => {
+ const normalized = rows.map((row) =>
+ craftReviewedDifference.parse({
+ ...row,
+ path: normalizeCraftSnapshotText(row.path),
+ officialValue:
+ row.officialValue === null
+ ? null
+ : normalizeCraftSnapshotText(row.officialValue),
+ profileValue:
+ row.profileValue === null
+ ? null
+ : normalizeCraftSnapshotText(row.profileValue),
+ review: normalizeCraftSnapshotText(row.review),
+ })
+ );
+ return normalized.sort(compareDifferences);
+};
+
+export const createCraftReviewedDifferenceTable = async (
+ rows: readonly CraftReviewedDifference[]
+) => {
+ const normalizedRows = normalizeCraftReviewedDifferences(rows);
+ return craftReviewedDifferenceTable.parse({
+ tableHash: await hashCraftSnapshot(normalizedRows),
+ rows: normalizedRows,
+ });
+};
+
+export const createUnverifiedCraftProvenance = async (
+ docsUrl: string
+): Promise<CraftSnapshotProvenance> => {
+ const reviewedDifferences = await createCraftReviewedDifferenceTable([]);
+ return craftSnapshotProvenance.parse({
+ schemaVersion: 1,
+ authentication: "unverified",
+ official: { projectId: null, buildId: null, version: null },
+ capture: { capturedAt: null, snapshotHash: null },
+ docs: { url: docsUrl, capturedAt: null, contentHash: null },
+ reviewedDifferences: { reviewedAt: null, ...reviewedDifferences },
+ });
+};
diff --git a/packages/project-build/src/runtime/cutover.ts b/packages/project-build/src/runtime/cutover.ts
index 515cca29ec..1a25e7c669 100644
--- a/packages/project-build/src/runtime/cutover.ts
+++ b/packages/project-build/src/runtime/cutover.ts
@@ -107,7 +107,11 @@ export const builderRuntimeCutoverManifests = [
},
{
family: "project-inspection-read",
- operationIds: ["project.search", "project.audit"] as const,
+ operationIds: [
+ "project.search",
+ "project.audit",
+ "project.verifyBindings",
+ ] as const,
callers: ["MCP/CLI project search and audit"] as const,
},
{
@@ -139,6 +143,11 @@ export const builderRuntimeCutoverManifests = [
"Builder components panel",
] as const,
},
+ {
+ family: "runtime-ui-integration",
+ operationIds: ["runtimeUi.integrate"] as const,
+ callers: ["MCP/CLI runtime UI authoring"] as const,
+ },
{
family: "text-content-mutations",
operationIds: [
diff --git a/packages/project-build/src/runtime/data.ts b/packages/project-build/src/runtime/data.ts
index 87e2a9838b..6508bc9e73 100644
--- a/packages/project-build/src/runtime/data.ts
+++ b/packages/project-build/src/runtime/data.ts
@@ -61,6 +61,11 @@ import {
} from "./expression-validation";
import { runtimeGeneratedIdInput } from "./generated-id-input";
import { createRuntimeMutation } from "./mutation";
+import {
+ paginateOutput,
+ projectOutput,
+ type PaginatedOutputInput,
+} from "./output";
import {
createPropUpsertPayload,
createValidatedPropValueFromInput,
@@ -181,12 +186,32 @@ export const serializeDataVariables = ({
export const listDataVariables = (
state: Pick<BuilderState, "dataSources">,
- input: { scopeInstanceId?: string } = {}
-) =>
- serializeDataVariables({
+ input: { scopeInstanceId?: string } & PaginatedOutputInput = {}
+) => {
+ const serialized = serializeDataVariables({
dataSources: getRequiredDataSources(state),
scopeInstanceId: input.scopeInstanceId,
});
+ const { items, ...pagination } = paginateOutput({
+ items: serialized.variables.map((variable) =>
+ projectOutput({
+ input,
+ compact: {
+ id: variable.id,
+ name: variable.name,
+ scopeInstanceId: variable.scopeInstanceId,
+ valueType: variable.value.type,
+ },
+ expanded: () => ({ value: variable.value }),
+ })
+ ),
+ cursor: input.cursor,
+ limit: input.limit,
+ filters: { scopeInstanceId: input.scopeInstanceId },
+ verbose: input.verbose,
+ });
+ return { variables: items, ...pagination };
+};
export const dataVariableValueInput = dataSourceVariableValue;
@@ -1865,7 +1890,7 @@ type ResourceExpressionFields = Partial<
Pick<Resource, "url" | "body" | "headers" | "searchParams">
>;
-const listResourceExpressions = (
+export const listResourceExpressions = (
fields: ResourceExpressionFields,
pathPrefix: string[] = []
) => [
@@ -2449,13 +2474,21 @@ export const serializeResources = ({
export const listResources = (
state: Pick<BuilderState, "dataSources" | "resources">,
- input: { scopeInstanceId?: string } = {}
+ input: { scopeInstanceId?: string } & PaginatedOutputInput = {}
) => {
- return serializeResources({
+ const serialized = serializeResources({
resources: getRequiredResources(state),
dataSources: getRequiredDataSources(state),
scopeInstanceId: input.scopeInstanceId,
});
+ const { items, ...pagination } = paginateOutput({
+ items: serialized.resources,
+ cursor: input.cursor,
+ limit: input.limit,
+ filters: { scopeInstanceId: input.scopeInstanceId },
+ verbose: input.verbose,
+ });
+ return { resources: items, ...pagination };
};
export const createResource = (
diff --git a/packages/project-build/src/runtime/expression-scope.ts b/packages/project-build/src/runtime/expression-scope.ts
new file mode 100644
index 0000000000..100521e694
--- /dev/null
+++ b/packages/project-build/src/runtime/expression-scope.ts
@@ -0,0 +1,49 @@
+import type { BuilderState } from "../state/builder-state";
+import { bindExpressionToInstanceScope, findAvailableVariables } from "./data";
+import { getExpressionWarnings } from "./expression-validation";
+
+export const bindExpressionInput = (
+ state: BuilderState,
+ instanceId: string,
+ expression: string
+) => {
+ if (state.instances === undefined || state.dataSources === undefined) {
+ return expression;
+ }
+ return bindExpressionToInstanceScope({
+ expression,
+ instanceId,
+ instances: state.instances,
+ dataSources: state.dataSources,
+ });
+};
+
+export const getScopedExpressionWarnings = (
+ state: BuilderState,
+ instanceId: string,
+ path: string[],
+ expression: string,
+ allowAssignment = false,
+ additionalVariables: readonly string[] = []
+) => {
+ if (state.instances === undefined || state.dataSources === undefined) {
+ return [];
+ }
+ const availableVariables = new Set(
+ findAvailableVariables({
+ startingInstanceId: instanceId,
+ instances: state.instances,
+ dataSources: state.dataSources,
+ }).map(({ name }) => name)
+ );
+ for (const name of additionalVariables) {
+ availableVariables.add(name);
+ }
+ return getExpressionWarnings({
+ expression,
+ availableVariables,
+ allowAssignment,
+ path,
+ instanceId,
+ });
+};
diff --git a/packages/project-build/src/runtime/fonts.ts b/packages/project-build/src/runtime/fonts.ts
index eb2edd4a65..4e0bf79ba6 100644
--- a/packages/project-build/src/runtime/fonts.ts
+++ b/packages/project-build/src/runtime/fonts.ts
@@ -2,17 +2,24 @@ import { SYSTEM_FONTS } from "@webstudio-is/fonts";
import { z } from "zod";
import type { BuilderState } from "../state/builder-state";
import { throwBuilderRuntimeError } from "./errors";
+import {
+ paginateOutput,
+ paginatedOutputInputSchema,
+ projectOutput,
+ type PaginatedOutputInput,
+} from "./output";
export const fontListInput = z.object({
includeSystem: z
.boolean()
.default(true)
.describe("Include built-in system font stacks."),
+ ...paginatedOutputInputSchema.shape,
});
export const listFonts = (
state: Pick<BuilderState, "assets">,
- input: z.infer<typeof fontListInput>
+ input: z.infer<typeof fontListInput> & PaginatedOutputInput
) => {
if (state.assets === undefined) {
return throwBuilderRuntimeError(
@@ -57,5 +64,35 @@ export const listFonts = (
description: config.description,
}))
: [];
- return { uploaded, system };
+ const { items, ...pagination } = paginateOutput({
+ items: [...uploaded, ...system].map((font) =>
+ font.source === "uploaded"
+ ? projectOutput({
+ input,
+ compact: {
+ family: font.family,
+ source: font.source,
+ assetCount: font.assets.length,
+ },
+ expanded: () => ({ assets: font.assets }),
+ })
+ : projectOutput({
+ input,
+ compact: { family: font.family, source: font.source },
+ expanded: () => ({
+ stack: font.stack,
+ description: font.description,
+ }),
+ })
+ ),
+ cursor: input.cursor,
+ limit: input.limit,
+ filters: { includeSystem: input.includeSystem },
+ verbose: input.verbose,
+ });
+ return {
+ uploaded: items.filter((font) => font.source === "uploaded"),
+ system: items.filter((font) => font.source === "system"),
+ ...pagination,
+ };
};
diff --git a/packages/project-build/src/runtime/instances.ts b/packages/project-build/src/runtime/instances.ts
index fa2e671eb3..0ccda3ebe0 100644
--- a/packages/project-build/src/runtime/instances.ts
+++ b/packages/project-build/src/runtime/instances.ts
@@ -3556,9 +3556,9 @@ export const listTextInstances = (
instanceId?: string;
mode?: "text" | "expression" | "all";
contains?: string;
- maxValueLength?: number;
- } = {}
+ } & PaginatedOutputInput = {}
) => {
+ const compactValueLength = 160;
const rootInstanceIds = getPageFilteredRootInstanceIds(state, input);
const pageInstanceIds =
rootInstanceIds === undefined
@@ -3566,16 +3566,40 @@ export const listTextInstances = (
: new Set(
getInstanceDepths(getRequiredInstances(state), rootInstanceIds).keys()
);
- return {
- texts: serializeTextNodes({
- instances: getRequiredInstances(state).values(),
- rootInstanceIds: pageInstanceIds,
+ const texts = serializeTextNodes({
+ instances: getRequiredInstances(state).values(),
+ rootInstanceIds: pageInstanceIds,
+ instanceId: input.instanceId,
+ mode: input.mode,
+ contains: input.contains,
+ });
+ const { items, ...pagination } = paginateOutput({
+ items: texts.map((text) => {
+ const { value, ...summary } = text;
+ const valuePreview = value.slice(0, compactValueLength);
+ return projectOutput({
+ input,
+ compact: {
+ ...summary,
+ valuePreview,
+ valueLength: value.length,
+ truncated: valuePreview.length < value.length,
+ },
+ expanded: () => ({ value }),
+ });
+ }),
+ cursor: input.cursor,
+ limit: input.limit,
+ filters: {
+ pageId: input.pageId,
+ pagePath: input.pagePath,
instanceId: input.instanceId,
mode: input.mode,
contains: input.contains,
- maxValueLength: input.maxValueLength,
- }),
- };
+ },
+ verbose: input.verbose,
+ });
+ return { texts: items, ...pagination };
};
type InstanceInspection = ReturnType<typeof serializeInstanceSummary> & {
diff --git a/packages/project-build/src/runtime/mutation.test.ts b/packages/project-build/src/runtime/mutation.test.ts
index f55e6fe915..73d12bf622 100644
--- a/packages/project-build/src/runtime/mutation.test.ts
+++ b/packages/project-build/src/runtime/mutation.test.ts
@@ -1,5 +1,9 @@
import { expect, test } from "vitest";
-import { createRuntimeMutation } from "./mutation";
+import { createDefaultPages } from "../shared/pages-utils";
+import {
+ createRuntimeMutation,
+ createRuntimeMutationAccumulator,
+} from "./mutation";
test("creates mutation result and marks noop from payload", () => {
expect(
@@ -24,3 +28,52 @@ test("creates mutation result and marks noop from payload", () => {
}).noop
).toBe(false);
});
+
+test("stages mutations against the latest state and combines their contract", () => {
+ const accumulator = createRuntimeMutationAccumulator({
+ pages: createDefaultPages({ rootInstanceId: "body" }),
+ });
+
+ expect(
+ accumulator.stage(
+ createRuntimeMutation({
+ payload: [
+ {
+ namespace: "pages",
+ patches: [{ op: "replace", path: ["homePageId"], value: "next" }],
+ },
+ ],
+ result: { first: true },
+ invalidatesNamespaces: ["pages"],
+ })
+ )
+ ).toEqual({ first: true });
+ expect(accumulator.state.pages?.homePageId).toBe("next");
+
+ accumulator.stage(
+ createRuntimeMutation({
+ payload: [
+ {
+ namespace: "pages",
+ patches: [{ op: "replace", path: ["homePageId"], value: "last" }],
+ },
+ ],
+ result: {},
+ invalidatesNamespaces: ["pages"],
+ })
+ );
+
+ expect(accumulator.complete({ done: true })).toMatchObject({
+ result: { done: true },
+ invalidatesNamespaces: ["pages"],
+ payload: [
+ {
+ namespace: "pages",
+ patches: [
+ { op: "replace", path: ["homePageId"], value: "next" },
+ { op: "replace", path: ["homePageId"], value: "last" },
+ ],
+ },
+ ],
+ });
+});
diff --git a/packages/project-build/src/runtime/mutation.ts b/packages/project-build/src/runtime/mutation.ts
index be3d534adc..71d68a6051 100644
--- a/packages/project-build/src/runtime/mutation.ts
+++ b/packages/project-build/src/runtime/mutation.ts
@@ -1,5 +1,7 @@
import type { BuilderNamespace } from "../contracts/namespaces";
import type { BuilderPatchChange } from "../contracts/patch";
+import type { BuilderState } from "../state/builder-state";
+import { applyBuilderPatchTransactions } from "../state/patch";
export type BuilderRuntimeMutation<
Result extends Record<string, unknown> = Record<string, unknown>,
@@ -28,3 +30,51 @@ export const createRuntimeMutation = <
invalidatesNamespaces,
noop: payload.length === 0,
});
+
+export const createRuntimeMutationAccumulator = (
+ initialState: BuilderState
+) => {
+ let state = initialState;
+ const changes = new Map<BuilderNamespace, BuilderPatchChange>();
+ const invalidatesNamespaces = new Set<BuilderNamespace>();
+
+ const stage = <Result extends Record<string, unknown>>(
+ mutation: BuilderRuntimeMutation<Result>
+ ) => {
+ for (const change of mutation.payload) {
+ const accumulated = changes.get(change.namespace);
+ if (accumulated === undefined) {
+ changes.set(change.namespace, {
+ namespace: change.namespace,
+ patches: [...change.patches],
+ });
+ } else {
+ accumulated.patches.push(...change.patches);
+ }
+ }
+ for (const namespace of mutation.invalidatesNamespaces) {
+ invalidatesNamespaces.add(namespace);
+ }
+ if (mutation.payload.length > 0) {
+ state = applyBuilderPatchTransactions(state, [
+ { id: "runtime-mutation-stage", payload: mutation.payload },
+ ]).state;
+ }
+ return mutation.result;
+ };
+
+ const complete = <Result extends Record<string, unknown>>(result: Result) =>
+ createRuntimeMutation({
+ payload: Array.from(changes.values()),
+ result,
+ invalidatesNamespaces: Array.from(invalidatesNamespaces),
+ });
+
+ return {
+ get state() {
+ return state;
+ },
+ stage,
+ complete,
+ };
+};
diff --git a/packages/project-build/src/runtime/output-schemas.ts b/packages/project-build/src/runtime/output-schemas.ts
index 5f6fbe6357..8be9e4a9fb 100644
--- a/packages/project-build/src/runtime/output-schemas.ts
+++ b/packages/project-build/src/runtime/output-schemas.ts
@@ -16,8 +16,12 @@ import { builderNamespaces } from "../contracts/namespaces";
import { builderPatchSchema } from "../contracts/patch";
import { marketplaceProduct } from "../shared/marketplace";
import { auditResult } from "./audit";
+import { bindingVerificationResult } from "./binding-verification";
import { insertCollectionResult } from "./collection";
-import { componentInsertResult } from "./component-insert-contract";
+import {
+ componentInsertResult,
+ fragmentInsertResult,
+} from "./component-insert-contract";
import { expressionWarningSchema } from "./expression-validation";
const looseObject = <Shape extends z.ZodRawShape>(shape: Shape) =>
@@ -135,7 +139,10 @@ const textMatch = looseObject({
component: z.string(),
label: z.string().optional(),
mode: z.enum(["text", "expression"]),
- value: z.string(),
+ valuePreview: z.string(),
+ value: z.string().optional(),
+ valueLength: z.number().int().nonnegative(),
+ truncated: z.boolean(),
});
const declaration = looseObject({
instanceId: id,
@@ -159,7 +166,8 @@ const token = looseObject({
});
const cssVariable = looseObject({
name: z.string(),
- value: z.string(),
+ value: z.string().optional(),
+ valueLength: z.number().int().nonnegative(),
scope: z.string(),
usageCount: z.number().int().optional(),
});
@@ -167,7 +175,8 @@ const variable = looseObject({
id,
name: z.string(),
scopeInstanceId: id.optional(),
- value: dataSourceVariableValue,
+ valueType: z.string(),
+ value: dataSourceVariableValue.optional(),
});
const resource = looseObject({
id,
@@ -223,18 +232,16 @@ const uploadedFontAsset = looseObject({
const uploadedFont = looseObject({
family: z.string(),
source: z.literal("uploaded"),
- assets: z.array(uploadedFontAsset),
+ assetCount: z.number().int().nonnegative(),
+ assets: z.array(uploadedFontAsset).optional(),
});
const systemFont = looseObject({
family: z.string(),
source: z.literal("system"),
- stack: stringArray,
- description: z.string(),
+ stack: stringArray.optional(),
+ description: z.string().optional(),
});
-const fragmentInsertResult = componentInsertResult.extend({
- parentInstanceId: id.optional(),
-});
const instanceIdsResult = looseObject({ instanceIds: stringArray });
const pageIdResult = looseObject({ pageId: id });
const folderIdResult = looseObject({ folderId: id });
@@ -268,11 +275,19 @@ const resourceMutationResult = looseObject({
dataSourceId: id.optional(),
warnings: expressionWarnings,
});
+const retainedRuntimeBehavior = looseObject({
+ instanceId: id,
+ responsibility: z.string(),
+});
+const unsupportedRuntimeConversion = looseObject({
+ behavior: z.string(),
+ reason: z.string(),
+});
export const runtimeOutputSchemas = {
"pages.list": looseObject({
pages: z.array(pageSummary),
- folders: z.array(folder).optional(),
+ ...outputPage,
}),
"pages.get": pageDetails,
"pages.getByPath": z.union([
@@ -295,7 +310,7 @@ export const runtimeOutputSchemas = {
"projectSettings.get": looseObject({
meta: looseObject(projectMeta.shape),
compiler: looseObject(compilerSettings.shape),
- redirects: z.array(redirect),
+ redirects: z.array(redirect).optional(),
}),
"projectSettings.update": looseObject({ updated: z.boolean() }),
"projectSettings.getMarketplaceProduct": looseObject({
@@ -304,19 +319,28 @@ export const runtimeOutputSchemas = {
"projectSettings.updateMarketplaceProduct": looseObject({
updated: z.boolean(),
}),
- "redirects.list": looseObject({ redirects: z.array(redirect) }),
+ "redirects.list": looseObject({
+ redirects: z.array(redirect),
+ ...outputPage,
+ }),
"redirects.create": looseObject({ old: z.string() }),
"redirects.update": looseObject({ old: z.string() }),
"redirects.delete": looseObject({ old: z.string() }),
"redirects.setAll": looseObject({ count: z.number().int() }),
- "breakpoints.list": looseObject({ breakpoints: z.array(breakpoint) }),
+ "breakpoints.list": looseObject({
+ breakpoints: z.array(breakpoint),
+ ...outputPage,
+ }),
"breakpoints.create": breakpointIdResult,
"breakpoints.update": breakpointIdResult,
"breakpoints.delete": breakpointIdResult,
"pages.delete": pageIdResult,
"pages.duplicate": pageIdResult,
"pages.copy": pageIdResult,
- "pageTemplates.list": looseObject({ templates: z.array(pageTemplate) }),
+ "pageTemplates.list": looseObject({
+ templates: z.array(pageTemplate),
+ ...outputPage,
+ }),
"pageTemplates.create": looseObject({ templateId: id, rootInstanceId: id }),
"pageTemplates.update": templateIdResult,
"pageTemplates.delete": templateIdResult,
@@ -325,7 +349,7 @@ export const runtimeOutputSchemas = {
"pageTemplates.createPage": pageIdResult,
"folders.list": looseObject({
folders: z.array(folder),
- pages: z.array(pageSummary).optional(),
+ ...outputPage,
}),
"folders.create": folderIdResult,
"folders.update": folderIdResult,
@@ -357,11 +381,30 @@ export const runtimeOutputSchemas = {
"project.search": looseObject({
query: z.string(),
scopes: stringArray,
- total: z.number().int(),
truncated: z.boolean(),
matches: z.array(looseObject({ kind: z.string() })),
+ ...outputPage,
}),
"project.audit": auditResult,
+ "project.verifyBindings": bindingVerificationResult,
+ "runtimeUi.integrate": looseObject({
+ created: looseObject({
+ variableIds: stringArray,
+ resources: z.array(
+ looseObject({ resourceId: id, dataSourceId: id.optional() })
+ ),
+ instanceIds: stringArray,
+ rootInstanceIds: stringArray,
+ propIds: stringArray,
+ }),
+ editableStructure: looseObject({
+ type: z.enum(["fragment", "collection"]),
+ usesCollection: z.boolean(),
+ }),
+ retainedBehavior: z.array(retainedRuntimeBehavior),
+ unsupportedConversions: z.array(unsupportedRuntimeConversion),
+ warnings: expressionWarnings,
+ }),
"instances.insertComponent": componentInsertResult,
"instances.insertCollection": insertCollectionResult.extend({
warnings: expressionWarnings.optional(),
@@ -403,7 +446,10 @@ export const runtimeOutputSchemas = {
propIds: stringArray,
warnings: expressionWarnings.optional(),
}),
- "instances.listTexts": looseObject({ texts: z.array(textMatch) }),
+ "instances.listTexts": looseObject({
+ texts: z.array(textMatch),
+ ...outputPage,
+ }),
"instances.updateText": looseObject({
instanceId: id,
childIndex: z.number().int(),
@@ -474,7 +520,10 @@ export const runtimeOutputSchemas = {
}),
"styleSources.duplicate": looseObject({ styleSourceId: id }),
"styleSources.convertLocalToToken": looseObject({ styleSourceId: id }),
- "cssVariables.list": looseObject({ vars: z.array(cssVariable) }),
+ "cssVariables.list": looseObject({
+ vars: z.array(cssVariable),
+ ...outputPage,
+ }),
"cssVariables.define": looseObject({ names: stringArray }),
"cssVariables.delete": looseObject({
names: stringArray,
@@ -490,7 +539,10 @@ export const runtimeOutputSchemas = {
styleKeys: stringArray,
propIds: stringArray,
}),
- "variables.list": looseObject({ variables: z.array(variable) }),
+ "variables.list": looseObject({
+ variables: z.array(variable),
+ ...outputPage,
+ }),
"variables.create": dataSourceIdResult,
"variables.update": dataSourceIdResult,
"variables.delete": dataSourceIdResult,
@@ -498,7 +550,10 @@ export const runtimeOutputSchemas = {
dataSourceIds: stringArray,
deletedCount: z.number().int(),
}),
- "resources.list": looseObject({ resources: z.array(resource) }),
+ "resources.list": looseObject({
+ resources: z.array(resource),
+ ...outputPage,
+ }),
"resources.create": resourceMutationResult,
"resources.update": resourceMutationResult.partial({ warnings: true }),
"resources.replaceText": looseObject({
@@ -525,8 +580,12 @@ export const runtimeOutputSchemas = {
"fonts.list": looseObject({
uploaded: z.array(uploadedFont),
system: z.array(systemFont),
+ ...outputPage,
+ }),
+ "assets.findUsage": looseObject({
+ usages: z.array(assetUsage),
+ ...outputPage,
}),
- "assets.findUsage": looseObject({ usages: z.array(assetUsage) }),
"assets.update": assetIdResult,
"assets.setImageDescriptions": looseObject({
updated: z.array(looseObject({ assetId: id, decorative: z.boolean() })),
diff --git a/packages/project-build/src/runtime/output.ts b/packages/project-build/src/runtime/output.ts
index ebffd20289..1f723f7de8 100644
--- a/packages/project-build/src/runtime/output.ts
+++ b/packages/project-build/src/runtime/output.ts
@@ -54,7 +54,7 @@ const parseCursor = (
export const paginateOutput = <Item, Filters extends object>({
items,
cursor,
- limit = 50,
+ limit = 20,
filters,
verbose,
invalidCursorMessage = "Invalid pagination cursor",
diff --git a/packages/project-build/src/runtime/page-copy.test.tsx b/packages/project-build/src/runtime/page-copy.test.tsx
index 5c05bc48cf..e615244e11 100644
--- a/packages/project-build/src/runtime/page-copy.test.tsx
+++ b/packages/project-build/src/runtime/page-copy.test.tsx
@@ -1176,6 +1176,11 @@ describe("insert page copy", () => {
meta: { description: `"Description"` },
},
],
+ detail: "compact",
+ total: 1,
+ returnedCount: 1,
+ nextCursor: null,
+ filters: {},
});
});
diff --git a/packages/project-build/src/runtime/page-copy.ts b/packages/project-build/src/runtime/page-copy.ts
index c71e0b4b39..02b39d58cc 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 { paginateOutput, type PaginatedOutputInput } from "./output";
import { webstudioDataNamespaces } from "../contracts/namespaces";
import { throwBuilderRuntimeError } from "./errors";
import { createRuntimeMutation } from "./mutation";
@@ -1040,19 +1041,28 @@ export const reorderPageTemplates = (
});
};
-export const listPageTemplates = (state: Pick<BuilderState, "pages">) => {
+export const listPageTemplates = (
+ state: Pick<BuilderState, "pages">,
+ input: PaginatedOutputInput = {}
+) => {
const pages = getRequiredPages(state);
+ const { items, ...pagination } = paginateOutput({
+ items: Array.from(pages.pageTemplates?.values() ?? []).map((template) => ({
+ id: template.id,
+ name: template.name,
+ title: template.title,
+ rootInstanceId: template.rootInstanceId,
+ systemDataSourceId: template.systemDataSourceId,
+ meta: template.meta,
+ })),
+ cursor: input.cursor,
+ limit: input.limit,
+ filters: {},
+ verbose: input.verbose,
+ });
return {
- templates: Array.from(pages.pageTemplates?.values() ?? []).map(
- (template) => ({
- id: template.id,
- name: template.name,
- title: template.title,
- rootInstanceId: template.rootInstanceId,
- systemDataSourceId: template.systemDataSourceId,
- meta: template.meta,
- })
- ),
+ templates: items,
+ ...pagination,
};
};
diff --git a/packages/project-build/src/runtime/pages.ts b/packages/project-build/src/runtime/pages.ts
index 8ba9c5a243..000c645a14 100644
--- a/packages/project-build/src/runtime/pages.ts
+++ b/packages/project-build/src/runtime/pages.ts
@@ -45,6 +45,7 @@ import {
} from "./errors";
import { getNamedExpressionValidationIssues } from "./expression-validation";
import { runtimeGeneratedIdInput } from "./generated-id-input";
+import { paginateOutput, type PaginatedOutputInput } from "./output";
import {
collectExclusiveInstanceIds,
createInstanceCleanupPayload,
@@ -346,12 +347,19 @@ export const canDropPageTarget = (dropTarget: PageDropTarget, pages: Pages) => {
export const listPages = (
state: Pick<BuilderState, "pages">,
- input: { includeFolders?: boolean } = {}
+ input: PaginatedOutputInput = {}
) => {
const pages = getSerializedPages(state);
+ const { items, ...pagination } = paginateOutput({
+ items: pages.pages.map((page) => serializePageSummary(pages, page)),
+ cursor: input.cursor,
+ limit: input.limit,
+ filters: {},
+ verbose: input.verbose,
+ });
return {
- pages: pages.pages.map((page) => serializePageSummary(pages, page)),
- folders: input.includeFolders === true ? pages.folders : undefined,
+ pages: items,
+ ...pagination,
};
};
@@ -412,21 +420,25 @@ export const getPageByPath = (
export const listFolders = (
state: Pick<BuilderState, "pages">,
- input: { includePages?: boolean } = {}
+ input: PaginatedOutputInput = {}
) => {
const pages = getSerializedPages(state);
- return {
- folders: pages.folders.map((folder) => ({
+ const { items, ...pagination } = paginateOutput({
+ items: pages.folders.map((folder) => ({
id: folder.id,
name: folder.name,
slug: folder.slug,
parentFolderId: findParentFolderId(pages.folders, folder.id),
children: folder.children,
})),
- pages:
- input.includePages === true
- ? pages.pages.map((page) => serializePageSummary(pages, page))
- : undefined,
+ cursor: input.cursor,
+ limit: input.limit,
+ filters: {},
+ verbose: input.verbose,
+ });
+ return {
+ folders: items,
+ ...pagination,
};
};
@@ -805,6 +817,27 @@ const pageMetaExpressionFields = [
"content",
] as const satisfies readonly (keyof PageMetaPatchInput)[];
+export const listPageMetadataExpressions = (
+ page: Pick<Page, "title" | "meta">
+) => {
+ const expressions: Array<{ path: string[]; expression: string }> = [
+ { path: ["title"], expression: page.title },
+ ];
+ for (const field of pageMetaExpressionFields) {
+ const expression = page.meta[field];
+ if (typeof expression === "string") {
+ expressions.push({ path: ["meta", field], expression });
+ }
+ }
+ for (const [index, item] of (page.meta.custom ?? []).entries()) {
+ expressions.push({
+ path: ["meta", "custom", String(index), "content"],
+ expression: item.content,
+ });
+ }
+ return expressions;
+};
+
export const pageExpressionFieldHint =
'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.';
diff --git a/packages/project-build/src/runtime/project-settings.test.ts b/packages/project-build/src/runtime/project-settings.test.ts
index 4e7512c7fc..85b75f9b3f 100644
--- a/packages/project-build/src/runtime/project-settings.test.ts
+++ b/packages/project-build/src/runtime/project-settings.test.ts
@@ -137,6 +137,10 @@ describe("project settings runtime", () => {
expect(getProjectSettings(createState())).toEqual({
meta: { siteName: "Existing site", faviconAssetId: "old-asset" },
compiler: { atomicStyles: true },
+ });
+ expect(getProjectSettings(createState(), { verbose: true })).toEqual({
+ meta: { siteName: "Existing site", faviconAssetId: "old-asset" },
+ compiler: { atomicStyles: true },
redirects: [{ old: "/old", new: "/new", status: "301" }],
});
});
@@ -396,6 +400,11 @@ describe("redirect runtime", () => {
test("lists redirects", () => {
expect(listRedirects(createState())).toEqual({
redirects: [{ old: "/old", new: "/new", status: "301" }],
+ detail: "compact",
+ total: 1,
+ returnedCount: 1,
+ nextCursor: null,
+ filters: {},
});
});
@@ -534,6 +543,11 @@ describe("breakpoint runtime", () => {
{ id: "base", label: "Base" },
{ id: "desktop", label: "Desktop", minWidth: 1024 },
],
+ detail: "compact",
+ total: 2,
+ returnedCount: 2,
+ nextCursor: null,
+ filters: {},
});
});
diff --git a/packages/project-build/src/runtime/project-settings.ts b/packages/project-build/src/runtime/project-settings.ts
index 11a1d7549b..1673755317 100644
--- a/packages/project-build/src/runtime/project-settings.ts
+++ b/packages/project-build/src/runtime/project-settings.ts
@@ -17,7 +17,11 @@ import {
validateProjectAuth,
} from "../contracts/project-settings";
import type { BuilderState } from "../state/builder-state";
-import { hasReachedBreakpointLimit, isBaseBreakpoint } from "./breakpoints";
+import {
+ hasReachedBreakpointLimit,
+ isBaseBreakpoint,
+ isBaseWidthBreakpoint,
+} from "./breakpoints";
import type { BuilderRuntimeContext } from "./context";
import {
getZodValidationIssueOptions,
@@ -26,6 +30,12 @@ import {
} from "./errors";
import { runtimeGeneratedIdInput } from "./generated-id-input";
import { createRuntimeMutation } from "./mutation";
+import {
+ paginateOutput,
+ projectOutput,
+ type OutputDetailInput,
+ type PaginatedOutputInput,
+} from "./output";
import { getRequiredPages } from "./pages";
import {
marketplaceProduct,
@@ -147,15 +157,16 @@ const validateProjectMetaUpdate = (
};
export const getProjectSettings = (
- state: Pick<BuilderState, "pages" | "projectSettings">
+ state: Pick<BuilderState, "pages" | "projectSettings">,
+ input: OutputDetailInput = {}
) => {
const pages = getRequiredPages(state);
const settings = getRequiredProjectSettings(state);
- return {
- meta: settings.meta,
- compiler: settings.compiler,
- redirects: pages.redirects ?? [],
- };
+ return projectOutput({
+ input,
+ compact: { meta: settings.meta, compiler: settings.compiler },
+ expanded: () => ({ redirects: pages.redirects ?? [] }),
+ });
};
const pushObjectFieldPatches = ({
@@ -263,9 +274,28 @@ export const getMarketplaceProduct = (
return { marketplaceProduct: state.marketplaceProduct };
};
-export const listRedirects = (state: Pick<BuilderState, "pages">) => ({
- redirects: getRequiredPages(state).redirects ?? [],
-});
+const paginateProjectSettingItems = <Item>(
+ items: readonly Item[],
+ input: PaginatedOutputInput
+) =>
+ paginateOutput({
+ items,
+ cursor: input.cursor,
+ limit: input.limit,
+ filters: {},
+ verbose: input.verbose,
+ });
+
+export const listRedirects = (
+ state: Pick<BuilderState, "pages">,
+ input: PaginatedOutputInput = {}
+) => {
+ const { items, ...pagination } = paginateProjectSettingItems(
+ getRequiredPages(state).redirects ?? [],
+ input
+ );
+ return { redirects: items, ...pagination };
+};
export const redirectStatusInput = z.enum(["301", "302"]);
@@ -550,9 +580,16 @@ export const setRedirects = (
});
};
-export const listBreakpoints = (state: Pick<BuilderState, "breakpoints">) => ({
- breakpoints: Array.from(getRequiredBreakpoints(state).values()),
-});
+export const listBreakpoints = (
+ state: Pick<BuilderState, "breakpoints">,
+ input: PaginatedOutputInput = {}
+) => {
+ const { items, ...pagination } = paginateProjectSettingItems(
+ Array.from(getRequiredBreakpoints(state).values()),
+ input
+ );
+ return { breakpoints: items, ...pagination };
+};
export const breakpointFieldsInput = z.object({
id: runtimeGeneratedIdInput,
@@ -599,14 +636,10 @@ export const createBreakpoint = (
return throwBuilderRuntimeError("CONFLICT", "Breakpoint already exists");
}
const value = parseBreakpoint({ ...input, id: breakpointId });
- const canHaveOnlyOneBaseBreakpoint =
- value.condition === undefined && isBaseBreakpoint(value);
+ const canHaveOnlyOneBaseBreakpoint = isBaseWidthBreakpoint(value);
if (
canHaveOnlyOneBaseBreakpoint &&
- Array.from(breakpoints.values()).some(
- (breakpoint) =>
- breakpoint.condition === undefined && isBaseBreakpoint(breakpoint)
- )
+ Array.from(breakpoints.values()).some(isBaseWidthBreakpoint)
) {
return throwBuilderRuntimeError(
"CONFLICT",
@@ -642,7 +675,7 @@ export const updateBreakpoint = (
if (current === undefined) {
return throwBuilderRuntimeError("NOT_FOUND", "Breakpoint not found");
}
- if (current.condition === undefined && isBaseBreakpoint(current)) {
+ if (isBaseWidthBreakpoint(current)) {
return throwBuilderRuntimeError(
"BAD_REQUEST",
"Base breakpoint cannot be updated"
@@ -659,7 +692,7 @@ export const updateBreakpoint = (
}
}
const value = parseBreakpoint(nextBreakpoint as Breakpoint);
- if (value.condition === undefined && isBaseBreakpoint(value)) {
+ if (isBaseWidthBreakpoint(value)) {
return throwBuilderRuntimeError(
"BAD_REQUEST",
"Breakpoint cannot be changed into the base breakpoint"
@@ -692,11 +725,7 @@ export const deleteBreakpoint = (
return throwBuilderRuntimeError("NOT_FOUND", "Breakpoint not found");
}
const breakpoint = breakpoints.get(input.breakpointId);
- if (
- breakpoint !== undefined &&
- breakpoint.condition === undefined &&
- isBaseBreakpoint(breakpoint)
- ) {
+ if (breakpoint !== undefined && isBaseWidthBreakpoint(breakpoint)) {
return throwBuilderRuntimeError(
"BAD_REQUEST",
"Base breakpoint cannot be deleted"
diff --git a/packages/project-build/src/runtime/props.ts b/packages/project-build/src/runtime/props.ts
index 61eae173ec..6f28e49b3d 100644
--- a/packages/project-build/src/runtime/props.ts
+++ b/packages/project-build/src/runtime/props.ts
@@ -260,32 +260,38 @@ export const propValueInput = z
addExpressionIssues(context, getPropValueErrors(value), ["value"]);
});
+export const dataPropBindingInput = z.discriminatedUnion("type", [
+ 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() }),
+]);
+
+const actionPropBindingInput = z.object({
+ type: z.literal("action"),
+ value: z.array(
+ z.object({
+ type: z.literal("execute"),
+ args: z.array(z.string()),
+ code: z.string(),
+ })
+ ),
+});
+
export const propBindingInput = z
.object({
propId: runtimeGeneratedIdInput,
instanceId: z.string(),
name: z.string(),
binding: z.discriminatedUnion("type", [
- 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({
- type: z.literal("action"),
- value: z.array(
- z.object({
- type: z.literal("execute"),
- args: z.array(z.string()),
- code: z.string(),
- })
- ),
- }),
+ ...dataPropBindingInput.options,
+ actionPropBindingInput,
]),
})
.superRefine((value, context) => {
diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.ts
index 25d8e6bc4f..5a00e0944e 100644
--- a/packages/project-build/src/runtime/registry.test.ts
+++ b/packages/project-build/src/runtime/registry.test.ts
@@ -4,6 +4,7 @@ import {
toInputJsonSchemaObject,
type Assets,
type InputJsonSchema,
+ type Instance,
} from "@webstudio-is/sdk";
import { runtimeOperationContracts } from "../contracts/builder-runtime";
import { getRuntimeGeneratedInputPaths } from "../contracts/input-schema";
@@ -29,6 +30,7 @@ import {
} from "./instances";
import { listDataVariables, listResources } from "./data";
import { listFonts } from "./fonts";
+import { listAssets } from "./assets";
import { bindProps, deleteProps, updateProps } from "./props";
import type { BuilderState } from "../state/builder-state";
import type { SemanticValidationIssue } from "./errors";
@@ -37,6 +39,7 @@ import {
expectRuntimeValidationError,
state,
} from "./runtime.test-fixtures";
+import { createResourceCollectionIntegrationFixture } from "./runtime-ui.test-fixture";
const hasDirectInputProperty = (
schema: InputJsonSchema | undefined,
@@ -67,6 +70,53 @@ const mutationOperationIds = runtimeOperationContracts
.filter((contract) => contract.kind === "mutation")
.map((contract) => contract.id);
+const paginatedReadOperationIds = [
+ "pages.list",
+ "redirects.list",
+ "breakpoints.list",
+ "pageTemplates.list",
+ "folders.list",
+ "instances.list",
+ "instances.listTexts",
+ "styles.getDeclarations",
+ "designTokens.list",
+ "cssVariables.list",
+ "variables.list",
+ "resources.list",
+ "assets.list",
+ "fonts.list",
+] as const;
+
+const maxCompactListBytes = 16 * 1024;
+
+test.each(paginatedReadOperationIds)(
+ "%s uses the shared paginated compact/verbose contract",
+ (operationId) => {
+ const operation = getBuilderRuntimeOperation(operationId);
+ expect(hasDirectInputProperty(operation.inputJsonSchema, "cursor")).toBe(
+ true
+ );
+ expect(hasDirectInputProperty(operation.inputJsonSchema, "limit")).toBe(
+ true
+ );
+ expect(hasDirectInputProperty(operation.inputJsonSchema, "verbose")).toBe(
+ true
+ );
+ for (const property of [
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ]) {
+ expect(
+ hasDirectInputProperty(operation.outputJsonSchema, property),
+ `${operationId} output is missing ${property}`
+ ).toBe(true);
+ }
+ }
+);
+
const getMutationResult = (operation: unknown): unknown => {
expect(operation).toHaveProperty("result");
return (operation as { result: unknown }).result;
@@ -245,23 +295,18 @@ test("validates structured runtime operation results", () => {
describe("builder runtime pages", () => {
test("lists pages and folders from shared state", () => {
- expect(listPages(state, { includeFolders: true })).toMatchObject({
+ expect(listPages(state)).toMatchObject({
pages: [
{ id: "home", path: "", isHome: true, parentFolderId: "root" },
{ id: "post", path: "/blog/post", parentFolderId: "blog" },
],
- folders: [
- { id: "root", children: ["home", "blog"] },
- { id: "blog", children: ["post"] },
- ],
});
- expect(listFolders(state, { includePages: true })).toMatchObject({
+ expect(listFolders(state)).toMatchObject({
folders: [
{ id: "root", parentFolderId: undefined },
{ id: "blog", parentFolderId: "root" },
],
- pages: [{ id: "home" }, { id: "post" }],
});
});
@@ -338,6 +383,56 @@ describe("builder runtime pages", () => {
});
describe("builder runtime read families", () => {
+ test("keeps representative high-volume compact lists within budget", () => {
+ const sourceInstance = state.instances.get("heading")!;
+ const sourceAsset = state.assets.get("asset")!;
+ const sourceToken = state.styleSources.get("token")!;
+ const largeState: BuilderState = {
+ ...state,
+ instances: new Map(
+ Array.from({ length: 100 }, (_, index) => {
+ const id = `instance-${index}`;
+ return [id, { ...sourceInstance, id, label: `Item ${index}` }];
+ })
+ ),
+ assets: new Map(
+ Array.from({ length: 100 }, (_, index) => {
+ const id = `asset-${index}`;
+ return [
+ id,
+ {
+ ...sourceAsset,
+ id,
+ name: `${id}.png`,
+ description: `Verbose description ${"detail ".repeat(100)}`,
+ },
+ ];
+ })
+ ),
+ styleSources: new Map(
+ Array.from({ length: 100 }, (_, index) => {
+ const id = `token-${index}`;
+ return [id, { ...sourceToken, id, name: `Token ${index}` }];
+ })
+ ),
+ styles: new Map(),
+ styleSourceSelections: new Map(),
+ };
+
+ const outputs = [
+ listInstances(largeState),
+ listAssets(largeState),
+ listDesignTokens(largeState),
+ ];
+
+ for (const output of outputs) {
+ expect(output.returnedCount).toBe(20);
+ expect(Buffer.byteLength(JSON.stringify(output))).toBeLessThanOrEqual(
+ maxCompactListBytes
+ );
+ }
+ });
+
test("keeps instance lists compact and paginates verbose expansion", () => {
const instances: BuilderState["instances"] = new Map(state.instances);
const largeState: BuilderState = {
@@ -424,7 +519,15 @@ describe("builder runtime read families", () => {
);
expect(listTextInstances(state, { contains: "Hello" })).toMatchObject({
- texts: [{ instanceId: "heading", childIndex: 0, value: "Hello" }],
+ texts: [
+ {
+ instanceId: "heading",
+ childIndex: 0,
+ valuePreview: "Hello",
+ valueLength: 5,
+ truncated: false,
+ },
+ ],
});
});
@@ -1083,16 +1186,95 @@ describe("builder runtime read families", () => {
tokens: [{ id: "token", styles: { color: expect.any(Object) } }],
});
expect(listCssVariables(state, { withUsage: true })).toMatchObject({
- vars: [{ name: "--brand-color", scope: "heading", usageCount: 1 }],
+ vars: [
+ {
+ name: "--brand-color",
+ scope: "heading",
+ usageCount: 1,
+ valueLength: expect.any(Number),
+ },
+ ],
});
+ expect(
+ listCssVariables(state, { withUsage: true, verbose: true })
+ ).toMatchObject({ vars: [{ value: expect.any(String) }] });
expect(listDataVariables(state)).toMatchObject({
- variables: [{ id: "variable", scopeInstanceId: "heading" }],
+ variables: [
+ {
+ id: "variable",
+ scopeInstanceId: "heading",
+ valueType: expect.any(String),
+ },
+ ],
+ });
+ expect(listDataVariables(state, { verbose: true })).toMatchObject({
+ variables: [{ value: expect.any(Object) }],
});
expect(listResources(state)).toMatchObject({
resources: [{ id: "resource", dataSourceId: "resourceDataSource" }],
});
});
+ test("compact list records are bounded subsets of verbose records", () => {
+ const assertions = [
+ [
+ listCssVariables(state, { withUsage: true }),
+ listCssVariables(state, { withUsage: true, verbose: true }),
+ ],
+ [listDataVariables(state), listDataVariables(state, { verbose: true })],
+ ] as const;
+
+ for (const [compact, verbose] of assertions) {
+ const { detail: _compactDetail, ...compactResult } = compact;
+ const { detail: _verboseDetail, ...verboseResult } = verbose;
+ expect(verboseResult).toMatchObject(compactResult);
+ expect(JSON.stringify(compact).length).toBeLessThan(
+ JSON.stringify(verbose).length
+ );
+ expect(verbose.total).toBe(compact.total);
+ expect(verbose.nextCursor).toBe(compact.nextCursor);
+ }
+
+ const instances = new Map<string, Instance>(state.instances);
+ const heading = instances.get("heading");
+ if (heading === undefined || heading.type !== "instance") {
+ throw new Error("Expected heading fixture");
+ }
+ instances.set("heading", {
+ ...heading,
+ children: [{ type: "text", value: "x".repeat(400) }],
+ });
+ const compactText = listTextInstances({ ...state, instances });
+ const verboseText = listTextInstances(
+ { ...state, instances },
+ { verbose: true }
+ );
+ const { detail: _compactDetail, ...compactTextResult } = compactText;
+ const { detail: _verboseDetail, ...verboseTextResult } = verboseText;
+ expect(verboseTextResult).toMatchObject(compactTextResult);
+ expect(compactText.texts[0]).toMatchObject({
+ valueLength: 400,
+ truncated: true,
+ });
+ expect(JSON.stringify(compactText).length).toBeLessThan(
+ JSON.stringify(verboseText).length
+ );
+ });
+
+ test("cursor traversal preserves page ordering without duplication", () => {
+ const first = listPages(state, { limit: 1 });
+ const second = listPages(state, {
+ limit: 1,
+ cursor: first.nextCursor ?? undefined,
+ });
+
+ expect([...first.pages, ...second.pages].map((page) => page.id)).toEqual([
+ "home",
+ "post",
+ ]);
+ expect(second.nextCursor).toBeNull();
+ });
+
test("lists uploaded font families separately from system font stacks", () => {
const assets: Assets = new Map(state.assets);
assets.set("font", {
@@ -1116,6 +1298,24 @@ describe("builder runtime read families", () => {
{
family: "Acme Sans",
source: "uploaded",
+ assetCount: 1,
+ },
+ ],
+ system: [],
+ detail: "compact",
+ total: 1,
+ returnedCount: 1,
+ nextCursor: null,
+ filters: { includeSystem: false },
+ });
+
+ expect(
+ listFonts(fontState, { includeSystem: false, verbose: true })
+ ).toMatchObject({
+ uploaded: [
+ {
+ family: "Acme Sans",
+ assetCount: 1,
assets: [
{
assetId: "font",
@@ -1127,7 +1327,7 @@ describe("builder runtime read families", () => {
],
},
],
- system: [],
+ detail: "verbose",
});
expect(
@@ -1880,6 +2080,7 @@ describe("builder runtime registry", () => {
["pageTransfer.insert", {}],
["pageTree.move", {}],
["pageTree.reparentOrphans", "invalid"],
+ ["runtimeUi.integrate", {}],
["instances.insertComponent", { parentInstanceId: "body" }],
["instances.insertCollection", { parentInstanceId: "body" }],
["instances.insertFragment", { parentInstanceId: "body" }],
@@ -2052,6 +2253,7 @@ describe("builder runtime registry", () => {
"folders.create",
{ name: "Docs", slug: "docs", parentFolderId: "root" },
],
+ ["folders.delete", { folderId: "blog" }],
[
"pageTemplates.create",
{
@@ -2060,6 +2262,7 @@ describe("builder runtime registry", () => {
meta: { description: '"Reusable article"' },
},
],
+ ["projectSettings.update", { meta: { siteName: "Updated project" } }],
["redirects.create", { old: "/legacy", new: "/new" }],
["breakpoints.create", { label: "Tablet", maxWidth: 768 }],
[
@@ -2079,6 +2282,22 @@ describe("builder runtime registry", () => {
"instances.clone",
{ sourceInstanceId: "heading", targetParentInstanceId: "body" },
],
+ [
+ "instances.insertComponent",
+ { parentInstanceId: "body", component: "ws:element", tag: "div" },
+ ],
+ [
+ "runtimeUi.integrate",
+ {
+ ...createResourceCollectionIntegrationFixture().input,
+ retainedBehavior: [],
+ },
+ ],
+ [
+ "instances.fillGrid",
+ { parentInstanceId: "body", totalCells: 3, breakpointId: "base" },
+ ],
+ ["pageTree.reparentOrphans", {}],
[
"instances.duplicateAfterItself",
{ sourceInstanceId: "heading", parentInstanceId: "body" },
@@ -2207,9 +2426,28 @@ describe("builder runtime registry", () => {
["assets.replace", { fromAssetId: "asset", toAssetId: "next" }],
]);
+ const mutationIds = new Set(mutationOperationIds);
+ for (const manifest of builderRuntimeCutoverManifests) {
+ const familyMutationIds = manifest.operationIds.filter((id) =>
+ mutationIds.has(id)
+ );
+ if (familyMutationIds.length > 0) {
+ expect(
+ familyMutationIds.some((id) => inputs.has(id)),
+ `${manifest.family} has no caller-state immutability fixture`
+ ).toBe(true);
+ }
+ }
+
for (const [id, input] of inputs) {
const before = structuredClone(state);
- executeBuilderRuntimeOperation({ id, state, input, context });
+ let nextId = 0;
+ executeBuilderRuntimeOperation({
+ id,
+ state,
+ input,
+ context: { createId: () => `runtime-id-${++nextId}` },
+ });
expect(state).toEqual(before);
}
});
diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.ts
index b528776a9d..9a493ffb17 100644
--- a/packages/project-build/src/runtime/registry.ts
+++ b/packages/project-build/src/runtime/registry.ts
@@ -4,8 +4,7 @@ import {
type BuilderNamespace,
} from "../contracts/namespaces";
import type { BuilderApiCapability } from "../contracts/permissions";
-import { paginatedOutputInputSchema } from "./output";
-import { getExpressionWarnings } from "./expression-validation";
+import { outputDetailInputSchema, paginatedOutputInputSchema } from "./output";
import {
getInputSchemaMetadata,
isHiddenPublicApiInputField,
@@ -14,6 +13,7 @@ import { instanceFilterInput, type InputJsonSchema } from "@webstudio-is/sdk";
import { builderRuntimeContext, type BuilderRuntimeContext } from "./context";
import { z } from "zod";
import * as assets from "./assets";
+import * as bindingVerification from "./binding-verification";
import * as components from "./components";
import * as collection from "./collection";
import * as data from "./data";
@@ -25,6 +25,7 @@ import * as pageCopy from "./page-copy";
import * as pages from "./pages";
import * as projectSettings from "./project-settings";
import * as props from "./props";
+import * as runtimeUi from "./runtime-ui";
import * as search from "./search";
import * as audit from "./audit";
import * as styles from "./styles";
@@ -37,6 +38,10 @@ import {
} from "./output-schemas";
import type { BuilderRuntimeMutation } from "./mutation";
import { listFragmentExpressions } from "./fragment";
+import {
+ bindExpressionInput,
+ getScopedExpressionWarnings,
+} from "./expression-scope";
export type BuilderRuntimeOperation<
Id extends string = string,
@@ -144,54 +149,6 @@ const parseOperationInput = <Schema extends z.ZodTypeAny>(
return throwInvalidOperationInput(result.error, inputJsonSchema);
};
-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 getScopedExpressionWarnings = (
- state: BuilderState,
- instanceId: string,
- path: string[],
- expression: string,
- allowAssignment = false,
- additionalVariables: readonly string[] = []
-) => {
- if (state.instances === undefined || state.dataSources === undefined) {
- return [];
- }
- const availableVariables = new Set(
- data
- .findAvailableVariables({
- startingInstanceId: instanceId,
- instances: state.instances,
- dataSources: state.dataSources,
- })
- .map(({ name }) => name)
- );
- for (const name of additionalVariables) {
- availableVariables.add(name);
- }
- return getExpressionWarnings({
- expression,
- availableVariables,
- allowAssignment,
- path,
- instanceId,
- });
-};
-
const getScopedPropWarnings = ({
state,
instanceId,
@@ -222,7 +179,7 @@ const withExpressionWarnings = <
Mutation extends { result: Record<string, unknown> },
>(
mutation: Mutation,
- warnings: ReturnType<typeof getExpressionWarnings>
+ warnings: ReturnType<typeof getScopedExpressionWarnings>
) =>
warnings.length === 0
? mutation
@@ -373,10 +330,14 @@ const pageCopyNamespaces = [
] as const;
const emptyInput = z.object({});
-const pageListInput = z.object({ includeFolders: z.boolean().optional() });
+const pageListInput = z.object({
+ ...paginatedOutputInputSchema.shape,
+});
const pageGetInput = z.object({ pageId: z.string() });
const pageGetByPathInput = z.object({ path: z.string() });
-const folderListInput = z.object({ includePages: z.boolean().optional() });
+const folderListInput = z.object({
+ ...paginatedOutputInputSchema.shape,
+});
const instanceListInput = instanceFilterInput.extend({
pageId: z.string().optional(),
pagePath: z.string().optional(),
@@ -408,7 +369,7 @@ const textListInput = z.object({
instanceId: z.string().optional(),
mode: z.enum(["text", "expression", "all"]).optional(),
contains: z.string().optional(),
- maxValueLength: z.number().int().nonnegative().optional(),
+ ...paginatedOutputInputSchema.shape,
});
const styleDeclarationsListInput = z.object({
instanceIds: z.array(z.string()).optional(),
@@ -433,17 +394,23 @@ const designTokenListInput = z.object({
const cssVariableListInput = z.object({
filter: z.string().optional(),
withUsage: z.boolean().optional(),
+ ...paginatedOutputInputSchema.shape,
});
const scopedInstanceListInput = z.object({
scopeInstanceId: z.string().optional(),
+ ...paginatedOutputInputSchema.shape,
});
+const paginatedListInput = paginatedOutputInputSchema;
const assetListInput = z.object({
type: z.enum(["image", "font"]).optional(),
sort: z.enum(["name", "size", "createdAt", "usage"]).optional(),
withUsage: z.boolean().optional(),
...paginatedOutputInputSchema.shape,
});
-const assetUsageInput = z.object({ assetId: z.string() });
+const assetUsageInput = z.object({
+ assetId: z.string(),
+ ...paginatedOutputInputSchema.shape,
+});
export const builderRuntimeOperations = [
runtimeOperation(
@@ -536,8 +503,8 @@ export const builderRuntimeOperations = [
"projectSettings.get",
api("get-project-settings", "getProjectSettings"),
readContract(["pages", "projectSettings"]),
- emptyInput,
- ({ state }) => projectSettings.getProjectSettings(state)
+ outputDetailInputSchema,
+ ({ state, input }) => projectSettings.getProjectSettings(state, input)
),
runtimeOperation(
"projectSettings.update",
@@ -572,8 +539,8 @@ export const builderRuntimeOperations = [
"redirects.list",
api("list-redirects", "listRedirects"),
readContract(["pages"]),
- emptyInput,
- ({ state }) => projectSettings.listRedirects(state)
+ paginatedListInput,
+ ({ state, input }) => projectSettings.listRedirects(state, input)
),
runtimeOperation(
"redirects.create",
@@ -623,8 +590,8 @@ export const builderRuntimeOperations = [
"breakpoints.list",
api("list-breakpoints", "listBreakpoints"),
readContract(["breakpoints"]),
- emptyInput,
- ({ state }) => projectSettings.listBreakpoints(state)
+ paginatedListInput,
+ ({ state, input }) => projectSettings.listBreakpoints(state, input)
),
runtimeOperation(
"breakpoints.create",
@@ -694,8 +661,8 @@ export const builderRuntimeOperations = [
"pageTemplates.list",
api("list-page-templates", "listPageTemplates"),
readContract(["pages"]),
- emptyInput,
- ({ state }) => pageCopy.listPageTemplates(state)
+ paginatedListInput,
+ ({ state, input }) => pageCopy.listPageTemplates(state, input)
),
runtimeOperation(
"pageTemplates.create",
@@ -902,6 +869,24 @@ export const builderRuntimeOperations = [
audit.auditInput,
({ state, input, context }) => audit.audit(state, input, context)
),
+ runtimeOperation(
+ "project.verifyBindings",
+ api("verify-bindings", "verifyBindings"),
+ readContract(["pages", "instances", "props", "resources", "dataSources"]),
+ bindingVerification.bindingVerificationInput,
+ ({ state, input }) => bindingVerification.verifyBindings(state, input)
+ ),
+ runtimeOperation(
+ "runtimeUi.integrate",
+ api("integrate-runtime-ui", "integrateRuntimeUi"),
+ mutationContract({
+ readNamespaces: components.componentInsertReadNamespaces,
+ writeNamespaces: components.componentInsertReadNamespaces,
+ }),
+ runtimeUi.integrateRuntimeUiInput,
+ ({ state, input, context }) =>
+ runtimeUi.integrateRuntimeUi(state, input, context)
+ ),
runtimeOperation(
"instances.insertComponent",
api("insert-component", "insertComponent"),
@@ -1921,6 +1906,12 @@ export type BuilderRuntimeOperationResult<Id extends string> =
: never
: never;
+export type BuilderRuntimeMutationOperationId = {
+ [Id in BuilderRuntimeOperationId]: BuilderRuntimeOperationResult<Id> extends BuilderRuntimeMutation
+ ? Id
+ : never;
+}[BuilderRuntimeOperationId];
+
const builderRuntimeOperationById: ReadonlyMap<
string,
BuilderRuntimeOperation
diff --git a/packages/project-build/src/runtime/runtime-ui.test-fixture.ts b/packages/project-build/src/runtime/runtime-ui.test-fixture.ts
new file mode 100644
index 0000000000..53ad80f98f
--- /dev/null
+++ b/packages/project-build/src/runtime/runtime-ui.test-fixture.ts
@@ -0,0 +1,99 @@
+import type { Instance, Prop } from "@webstudio-is/sdk";
+import type { BuilderState } from "../state/builder-state";
+import { state } from "./runtime.test-fixtures";
+
+export const createResourceCollectionIntegrationFixture = () => {
+ const instances = new Map<string, Instance>(state.instances);
+ instances.set("results-controller", {
+ type: "instance",
+ id: "results-controller",
+ component: "HtmlEmbed",
+ children: [],
+ });
+ instances.set("body", {
+ ...instances.get("body")!,
+ children: [
+ ...instances.get("body")!.children,
+ { type: "id" as const, value: "results-controller" },
+ ],
+ });
+ const props = new Map<string, Prop>(state.props);
+ props.set("results-controller-code", {
+ id: "results-controller-code",
+ instanceId: "results-controller",
+ name: "code",
+ type: "string",
+ value: "window.resultsController?.mount()",
+ });
+
+ return {
+ state: { ...state, instances, props } satisfies BuilderState,
+ input: {
+ parentInstanceId: "body",
+ variables: [
+ {
+ name: "ResultsLabel",
+ value: { type: "string" as const, value: "Search results" },
+ },
+ ],
+ resources: [
+ {
+ resource: {
+ name: "Search results",
+ method: "get" as const,
+ url: "https://api.example.com/results",
+ headers: [],
+ },
+ dataSourceName: "SearchResults",
+ exposeAsDataSource: true,
+ },
+ ],
+ structure: {
+ type: "collection" as const,
+ data: { type: "expression" as const, value: "SearchResults.data" },
+ itemFragment: {
+ children: [{ type: "id" as const, value: "result-card" }],
+ instances: [
+ {
+ type: "instance" as const,
+ id: "result-card",
+ component: "Text",
+ tag: "article",
+ children: [
+ { type: "expression" as const, value: "collectionItem.title" },
+ ],
+ },
+ ],
+ props: [],
+ dataSources: [],
+ resources: [],
+ styleSources: [],
+ styleSourceSelections: [],
+ styles: [],
+ breakpoints: [],
+ assets: [],
+ },
+ },
+ bindings: [
+ {
+ target: { type: "insertedRoot" as const, index: 0 },
+ name: "aria-label",
+ binding: { type: "expression" as const, value: "ResultsLabel" },
+ },
+ ],
+ retainedBehavior: [
+ {
+ instanceId: "results-controller",
+ responsibility: "Keyboard navigation and result activation",
+ },
+ ],
+ unsupportedConversions: [
+ {
+ behavior: "Third-party analytics callback",
+ reason:
+ "The callback contract is external and must remain script-owned.",
+ },
+ ],
+ },
+ };
+};
diff --git a/packages/project-build/src/runtime/runtime-ui.test.ts b/packages/project-build/src/runtime/runtime-ui.test.ts
new file mode 100644
index 0000000000..8693279353
--- /dev/null
+++ b/packages/project-build/src/runtime/runtime-ui.test.ts
@@ -0,0 +1,233 @@
+import { describe, expect, test } from "vitest";
+import { applyBuilderPatchTransactions } from "../state/patch";
+import type { BuilderRuntimeMutation } from "./mutation";
+import { executeBuilderRuntimeOperation } from "./registry";
+import { createResourceCollectionIntegrationFixture } from "./runtime-ui.test-fixture";
+
+const createContext = () => {
+ let id = 0;
+ return { createId: () => `runtime-ui-${++id}` };
+};
+
+describe("runtimeUi.integrate", () => {
+ test("plans one editable resource-backed Collection transaction", () => {
+ const fixture = createResourceCollectionIntegrationFixture();
+ const originalController = structuredClone(
+ fixture.state.instances!.get("results-controller")
+ );
+ const mutation = executeBuilderRuntimeOperation({
+ id: "runtimeUi.integrate",
+ state: fixture.state,
+ input: fixture.input,
+ context: createContext(),
+ }) as BuilderRuntimeMutation<{
+ created: Record<string, unknown>;
+ editableStructure: Record<string, unknown>;
+ retainedBehavior: unknown[];
+ unsupportedConversions: unknown[];
+ warnings: unknown[];
+ }>;
+
+ expect(mutation).toMatchObject({
+ kind: "mutation",
+ noop: false,
+ result: {
+ editableStructure: { type: "collection", usesCollection: true },
+ warnings: [],
+ retainedBehavior: [
+ {
+ instanceId: "results-controller",
+ responsibility: "Keyboard navigation and result activation",
+ },
+ ],
+ unsupportedConversions: [
+ expect.objectContaining({
+ behavior: "Third-party analytics callback",
+ }),
+ ],
+ },
+ });
+ expect(
+ new Set(mutation.payload.map(({ namespace }) => namespace)).size
+ ).toBe(mutation.payload.length);
+ expect(mutation.invalidatesNamespaces).toContain("pages");
+
+ // A normal dry-run returns this mutation without applying it.
+ expect(fixture.state.resources?.size).toBe(1);
+ expect(fixture.state.instances!.get("results-controller")).toEqual(
+ originalController
+ );
+
+ const { state: integrated } = applyBuilderPatchTransactions(fixture.state, [
+ { id: "integrate-runtime-ui", payload: mutation.payload },
+ ]);
+ expect(integrated.instances!.get("results-controller")).toEqual(
+ originalController
+ );
+ expect(integrated.resources?.size).toBe(2);
+ expect(
+ Array.from(integrated.dataSources!.values()).map(({ name }) => name)
+ ).toEqual(expect.arrayContaining(["ResultsLabel", "SearchResults"]));
+
+ const collection = Array.from(integrated.instances!.values()).find(
+ ({ component }) => component === "ws:collection"
+ );
+ expect(collection).toBeDefined();
+ expect(integrated.instances!.get("body")?.children).toContainEqual({
+ type: "id",
+ value: collection?.id,
+ });
+ expect(
+ Array.from(integrated.props!.values()).find(
+ ({ instanceId, name }) =>
+ instanceId === collection?.id && name === "aria-label"
+ )
+ ).toMatchObject({
+ type: "expression",
+ value: expect.stringContaining("$ws$dataSource$"),
+ });
+ expect(
+ Array.from(integrated.props!.values()).find(
+ ({ instanceId, name }) =>
+ instanceId === collection?.id && name === "data"
+ )
+ ).toMatchObject({
+ type: "expression",
+ value: expect.stringContaining("$ws$dataSource$"),
+ });
+ });
+
+ test("rejects new script fragments and missing retained behavior", () => {
+ const fixture = createResourceCollectionIntegrationFixture();
+ expect(() =>
+ executeBuilderRuntimeOperation({
+ id: "runtimeUi.integrate",
+ state: fixture.state,
+ input: {
+ ...fixture.input,
+ retainedBehavior: [
+ { instanceId: "missing-script", responsibility: "Unknown" },
+ ],
+ },
+ context: createContext(),
+ })
+ ).toThrow(/Retained behavior instance/);
+
+ expect(() =>
+ executeBuilderRuntimeOperation({
+ id: "runtimeUi.integrate",
+ state: fixture.state,
+ input: {
+ ...fixture.input,
+ structure: {
+ type: "fragment",
+ fragment: {
+ ...fixture.input.structure.itemFragment,
+ instances: [
+ {
+ type: "instance",
+ id: "new-script",
+ component: "HtmlEmbed",
+ children: [],
+ },
+ ],
+ },
+ },
+ },
+ context: createContext(),
+ })
+ ).toThrow(/cannot create HtmlEmbed scripts/);
+
+ expect(() =>
+ executeBuilderRuntimeOperation({
+ id: "runtimeUi.integrate",
+ state: fixture.state,
+ input: {
+ ...fixture.input,
+ structure: {
+ type: "fragment",
+ fragment: {
+ ...fixture.input.structure.itemFragment,
+ instances: [
+ {
+ type: "instance",
+ id: "manual-collection",
+ component: "@webstudio-is/sdk-components-react:Collection",
+ children: [],
+ },
+ ],
+ },
+ },
+ },
+ context: createContext(),
+ })
+ ).toThrow(/Use structure\.type "collection"/);
+ });
+
+ test("does not expose action-script bindings", () => {
+ const fixture = createResourceCollectionIntegrationFixture();
+ const operation = executeBuilderRuntimeOperation;
+ expect(() =>
+ operation({
+ id: "runtimeUi.integrate",
+ state: fixture.state,
+ input: {
+ ...fixture.input,
+ bindings: [
+ {
+ target: { type: "insertedRoot", index: 0 },
+ name: "onClick",
+ binding: {
+ type: "action",
+ value: [{ type: "execute", args: [], code: "doSomething()" }],
+ },
+ },
+ ],
+ },
+ context: createContext(),
+ })
+ ).toThrow(/Operation input is invalid/);
+ });
+
+ test("inserts ordinary fragments and validates existing binding targets", () => {
+ const fixture = createResourceCollectionIntegrationFixture();
+ const structure = {
+ type: "fragment" as const,
+ fragment: fixture.input.structure.itemFragment,
+ };
+
+ const mutation = executeBuilderRuntimeOperation({
+ id: "runtimeUi.integrate",
+ state: fixture.state,
+ input: { ...fixture.input, structure, resources: [], variables: [] },
+ context: createContext(),
+ }) as BuilderRuntimeMutation<{ editableStructure: { type: string } }>;
+
+ expect(mutation.result.editableStructure).toEqual({
+ type: "fragment",
+ usesCollection: false,
+ });
+ expect(mutation.result).toMatchObject({
+ created: { rootInstanceIds: [expect.any(String)] },
+ });
+
+ expect(() =>
+ executeBuilderRuntimeOperation({
+ id: "runtimeUi.integrate",
+ state: fixture.state,
+ input: {
+ ...fixture.input,
+ structure,
+ bindings: [
+ {
+ target: { type: "existing", instanceId: "missing" },
+ name: "title",
+ binding: { type: "expression", value: "ResultsLabel" },
+ },
+ ],
+ },
+ context: createContext(),
+ })
+ ).toThrow(/Binding target instance "missing" not found/);
+ });
+});
diff --git a/packages/project-build/src/runtime/runtime-ui.ts b/packages/project-build/src/runtime/runtime-ui.ts
new file mode 100644
index 0000000000..a2d3f0e171
--- /dev/null
+++ b/packages/project-build/src/runtime/runtime-ui.ts
@@ -0,0 +1,332 @@
+import { collectionComponent } from "@webstudio-is/sdk";
+import { z } from "zod";
+import type { BuilderState } from "../state/builder-state";
+import * as collection from "./collection";
+import * as components from "./components";
+import type { BuilderRuntimeContext } from "./context";
+import * as data from "./data";
+import { throwBuilderRuntimeError } from "./errors";
+import {
+ bindExpressionInput,
+ getScopedExpressionWarnings,
+} from "./expression-scope";
+import { listFragmentExpressions } from "./fragment";
+import { createRuntimeMutationAccumulator } from "./mutation";
+import * as props from "./props";
+import type { ExpressionWarning } from "./expression-validation";
+
+const retainedBehaviorInput = z.object({
+ instanceId: z
+ .string()
+ .describe("Existing script-owning instance that remains unchanged."),
+ responsibility: z
+ .string()
+ .min(1)
+ .describe("Runtime behavior retained by the existing instance."),
+});
+
+const unsupportedConversionInput = z.object({
+ behavior: z.string().min(1),
+ reason: z
+ .string()
+ .min(1)
+ .describe("Why this behavior cannot be represented safely in editable UI."),
+});
+
+const variableInput = z.object({
+ name: data.dataVariableCreateInput.shape.name,
+ value: data.dataVariableCreateInput.shape.value,
+});
+
+const resourceInput = z.object({
+ resource: data.resourceCreateInput.shape.resource,
+ dataSourceName: data.resourceCreateInput.shape.dataSourceName,
+ exposeAsDataSource: data.resourceCreateInput.shape.exposeAsDataSource,
+});
+
+const fragmentStructureInput = z.object({
+ type: z.literal("fragment"),
+ fragment: components.insertFragmentInput.shape.fragment,
+ conflictResolution: components.insertFragmentInput.shape.conflictResolution,
+ contentMode: components.insertFragmentInput.shape.contentMode,
+ mode: components.insertFragmentInput.shape.mode,
+ insertIndex: components.insertFragmentInput.shape.insertIndex,
+});
+
+const collectionStructureInput = z.object({
+ type: z.literal("collection"),
+ data: collection.insertCollectionInput.shape.data,
+ itemFragment: collection.insertCollectionInput.shape.itemFragment,
+ mode: collection.insertCollectionInput.shape.mode,
+ insertIndex: collection.insertCollectionInput.shape.insertIndex,
+});
+
+const bindingTargetInput = z.discriminatedUnion("type", [
+ z.object({ type: z.literal("existing"), instanceId: z.string() }),
+ z.object({
+ type: z.literal("insertedRoot"),
+ index: z.number().int().nonnegative().default(0),
+ }),
+]);
+
+const bindingInput = z.object({
+ target: bindingTargetInput,
+ name: z.string(),
+ binding: props.dataPropBindingInput.describe(
+ "Data binding only. Script actions are intentionally unsupported by runtime-ui integration."
+ ),
+});
+
+export const integrateRuntimeUiInput = z
+ .object({
+ parentInstanceId: z.string(),
+ variables: z.array(variableInput).default([]),
+ resources: z.array(resourceInput).default([]),
+ structure: z.discriminatedUnion("type", [
+ fragmentStructureInput,
+ collectionStructureInput,
+ ]),
+ bindings: z.array(bindingInput).default([]),
+ retainedBehavior: z.array(retainedBehaviorInput).default([]),
+ unsupportedConversions: z.array(unsupportedConversionInput).default([]),
+ })
+ .describe(
+ "Atomically integrate data-backed editable UI while retaining existing script-owned behavior. This operation stores declarative Webstudio data and never evaluates scripts."
+ );
+
+type IntegrationInput = z.infer<typeof integrateRuntimeUiInput>;
+
+const getRequiredInstances = (state: BuilderState) => {
+ if (state.instances === undefined) {
+ return throwBuilderRuntimeError("BAD_REQUEST", "Instances are missing");
+ }
+ return state.instances;
+};
+
+const assertIntegrationTargets = (
+ state: BuilderState,
+ input: IntegrationInput
+) => {
+ const instances = getRequiredInstances(state);
+ if (instances.has(input.parentInstanceId) === false) {
+ return throwBuilderRuntimeError("NOT_FOUND", "Parent instance not found");
+ }
+ for (const behavior of input.retainedBehavior) {
+ if (instances.has(behavior.instanceId) === false) {
+ return throwBuilderRuntimeError(
+ "NOT_FOUND",
+ `Retained behavior instance "${behavior.instanceId}" not found`
+ );
+ }
+ }
+ for (const binding of input.bindings) {
+ if (
+ binding.target.type === "existing" &&
+ instances.has(binding.target.instanceId) === false
+ ) {
+ return throwBuilderRuntimeError(
+ "NOT_FOUND",
+ `Binding target instance "${binding.target.instanceId}" not found`
+ );
+ }
+ }
+ const fragment =
+ input.structure.type === "fragment"
+ ? input.structure.fragment
+ : input.structure.itemFragment;
+ if (
+ input.structure.type === "fragment" &&
+ fragment.instances.some(
+ (instance) =>
+ instance.component === collectionComponent ||
+ instance.component.endsWith(":Collection")
+ )
+ ) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ 'Do not place a Collection component inside a generic fragment. Use structure.type "collection" with data and itemFragment so Webstudio creates the Collection parameters and bindings.'
+ );
+ }
+ if (
+ fragment.instances.some((instance) => instance.component === "HtmlEmbed")
+ ) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "Editable runtime UI cannot create HtmlEmbed scripts. Keep existing script behavior in retainedBehavior and insert only editable presentational components."
+ );
+ }
+};
+
+const getBindingInstanceId = ({
+ target,
+ rootInstanceIds,
+}: {
+ target: z.infer<typeof bindingTargetInput>;
+ rootInstanceIds: readonly string[];
+}) => {
+ if (target.type === "existing") {
+ return target.instanceId;
+ }
+ const instanceId = rootInstanceIds[target.index];
+ if (instanceId === undefined) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ `Inserted root index ${target.index} does not exist`
+ );
+ }
+ return instanceId;
+};
+
+export const integrateRuntimeUi = (
+ state: BuilderState,
+ input: IntegrationInput,
+ context: BuilderRuntimeContext
+) => {
+ assertIntegrationTargets(state, input);
+ const accumulator = createRuntimeMutationAccumulator(state);
+
+ const variableIds = input.variables.map((variable) =>
+ String(
+ accumulator.stage(
+ data.createDataVariable(
+ accumulator.state,
+ {
+ ...variable,
+ scopeInstanceId: input.parentInstanceId,
+ },
+ context
+ )
+ ).dataSourceId
+ )
+ );
+
+ const warnings: ExpressionWarning[] = [];
+ const resources = input.resources.map((resource) => {
+ const result = accumulator.stage(
+ data.createResource(
+ accumulator.state,
+ {
+ ...resource,
+ scopeInstanceId: input.parentInstanceId,
+ },
+ context
+ )
+ );
+ warnings.push(...result.warnings);
+ return {
+ resourceId: result.resourceId,
+ ...(result.dataSourceId === undefined
+ ? {}
+ : { dataSourceId: result.dataSourceId }),
+ };
+ });
+
+ if (input.structure.type === "collection") {
+ for (const entry of listFragmentExpressions(input.structure.itemFragment)) {
+ warnings.push(
+ ...getScopedExpressionWarnings(
+ accumulator.state,
+ input.parentInstanceId,
+ ["structure", "itemFragment", ...entry.path],
+ entry.expression,
+ entry.allowAssignment,
+ ["collectionItem", "collectionItemKey", ...entry.variables]
+ )
+ );
+ }
+ }
+
+ let structureResult: {
+ instanceIds: string[];
+ rootInstanceIds: string[];
+ };
+ if (input.structure.type === "collection") {
+ structureResult = accumulator.stage(
+ components.insertCollection(
+ accumulator.state,
+ {
+ parentInstanceId: input.parentInstanceId,
+ data: input.structure.data,
+ itemFragment: input.structure.itemFragment,
+ mode: input.structure.mode,
+ insertIndex: input.structure.insertIndex,
+ },
+ context
+ )
+ );
+ } else {
+ structureResult = accumulator.stage(
+ components.insertFragment(
+ accumulator.state,
+ {
+ parentInstanceId: input.parentInstanceId,
+ fragment: input.structure.fragment,
+ conflictResolution: input.structure.conflictResolution,
+ contentMode: input.structure.contentMode,
+ mode: input.structure.mode,
+ insertIndex: input.structure.insertIndex,
+ },
+ context
+ )
+ );
+ }
+
+ const resolvedBindings = input.bindings.map((binding, index) => {
+ const instanceId = getBindingInstanceId({
+ target: binding.target,
+ rootInstanceIds: structureResult.rootInstanceIds,
+ });
+ if (binding.binding.type === "expression") {
+ warnings.push(
+ ...getScopedExpressionWarnings(
+ accumulator.state,
+ instanceId,
+ ["bindings", String(index), "binding", "value"],
+ binding.binding.value
+ )
+ );
+ }
+ return {
+ instanceId,
+ name: binding.name,
+ binding:
+ binding.binding.type === "expression"
+ ? {
+ ...binding.binding,
+ value: bindExpressionInput(
+ accumulator.state,
+ instanceId,
+ binding.binding.value
+ ),
+ }
+ : binding.binding,
+ };
+ });
+ const propIds =
+ resolvedBindings.length === 0
+ ? []
+ : accumulator.stage(
+ props.bindProps(
+ accumulator.state,
+ { bindings: resolvedBindings },
+ context
+ )
+ ).propIds;
+
+ return accumulator.complete({
+ created: {
+ variableIds,
+ resources,
+ instanceIds: structureResult.instanceIds,
+ rootInstanceIds: structureResult.rootInstanceIds,
+ propIds,
+ },
+ editableStructure: {
+ type: input.structure.type,
+ usesCollection: input.structure.type === "collection",
+ },
+ retainedBehavior: input.retainedBehavior,
+ unsupportedConversions: input.unsupportedConversions,
+ warnings,
+ });
+};
diff --git a/packages/project-build/src/runtime/search.ts b/packages/project-build/src/runtime/search.ts
index f5bb543c72..03a0a49aeb 100644
--- a/packages/project-build/src/runtime/search.ts
+++ b/packages/project-build/src/runtime/search.ts
@@ -3,6 +3,7 @@ import { isLiteralExpression, type StyleDecl } from "@webstudio-is/sdk";
import { hasTopLevelJsonLdContext } from "@webstudio-is/sdk/runtime";
import { validateJsonLdWithSchemaOrg } from "@webstudio-is/sdk/schema-org";
import { ariaAttributes, ariaRoles } from "@webstudio-is/html-data";
+import { validateSelector } from "@webstudio-is/css-data";
import * as bcp47 from "bcp-47";
import type { BuilderState } from "../state/builder-state";
import { throwBuilderRuntimeError } from "./errors";
@@ -10,10 +11,11 @@ import { computeExpression } from "./data";
import { listAssets } from "./assets";
import { listCssVariables, listDesignTokens } from "./styles";
import { getInstanceDepths } from "./instances";
-import { isBaseBreakpoint } from "./breakpoints";
+import { isBaseWidthBreakpoint } from "./breakpoints";
import { findSerializedPageByInput, getSerializedPages } from "./pages";
import { validatePageSelector } from "./page-selector";
import { hasAccessibleName, isDynamicPropType } from "./accessibility-analysis";
+import { paginateOutput, paginatedOutputInputSchema } from "./output";
const projectLookupScope = z.enum([
"instances",
@@ -38,7 +40,7 @@ export const projectSearchInput = z
scopes: z.array(projectLookupScope).min(1).optional(),
pageId: z.string().optional(),
pagePath: z.string().optional(),
- limit: z.number().int().min(1).max(200).optional(),
+ ...paginatedOutputInputSchema.shape,
})
.strict()
.superRefine(validatePageSelector);
@@ -616,11 +618,37 @@ export const analyzeProject = (
(declaration) => declaration.breakpointId
)
);
- for (const breakpoint of state.breakpoints.values()) {
+ for (const declaration of state.styles.values()) {
if (
- breakpoint.condition === undefined &&
- isBaseBreakpoint(breakpoint)
+ declaration.state !== undefined &&
+ validateSelector(declaration.state).success === false
) {
+ matches.push({
+ kind: "style",
+ issue: "invalid-style-state-selector",
+ styleSourceId: declaration.styleSourceId,
+ breakpointId: declaration.breakpointId,
+ stateSelector: declaration.state,
+ styleProperty: declaration.property,
+ message:
+ "Style state selector is not safely scoped to its element and may generate invalid or escaping CSS.",
+ });
+ }
+ if (state.breakpoints.has(declaration.breakpointId) === false) {
+ matches.push({
+ kind: "style",
+ issue: "orphan-style-breakpoint",
+ styleSourceId: declaration.styleSourceId,
+ breakpointId: declaration.breakpointId,
+ stateSelector: declaration.state,
+ styleProperty: declaration.property,
+ message:
+ "Style declaration references a breakpoint that no longer exists and therefore cannot render.",
+ });
+ }
+ }
+ for (const breakpoint of state.breakpoints.values()) {
+ if (isBaseWidthBreakpoint(breakpoint)) {
continue;
}
if (breakpointIdsWithDeclarations.has(breakpoint.id) === false) {
@@ -1461,7 +1489,7 @@ export const analyzeProject = (
}
}
- const limit = input.limit ?? 50;
+ const limit = input.limit ?? 20;
return {
query: input.query,
scopes: [...scopes],
@@ -1474,4 +1502,28 @@ export const analyzeProject = (
export const searchProject = (
state: Parameters<typeof analyzeProject>[0],
input: z.infer<typeof projectSearchInput>
-) => ({ ...analyzeProject(state, input), query: input.query });
+) => {
+ const result = analyzeProject(state, {
+ ...input,
+ limit: Number.MAX_SAFE_INTEGER,
+ });
+ const { items, ...pagination } = paginateOutput({
+ items: result.matches,
+ cursor: input.cursor,
+ limit: input.limit,
+ filters: {
+ query: input.query,
+ scopes: input.scopes,
+ pageId: input.pageId,
+ pagePath: input.pagePath,
+ },
+ verbose: input.verbose,
+ });
+ return {
+ query: input.query,
+ scopes: result.scopes,
+ matches: items,
+ truncated: pagination.nextCursor !== null,
+ ...pagination,
+ };
+};
diff --git a/packages/project-build/src/runtime/styles.test.ts b/packages/project-build/src/runtime/styles.test.ts
index 549381df52..554c08490c 100644
--- a/packages/project-build/src/runtime/styles.test.ts
+++ b/packages/project-build/src/runtime/styles.test.ts
@@ -13,7 +13,11 @@ import {
type StyleSourceSelections,
type Styles,
} from "@webstudio-is/sdk";
-import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";
+import {
+ createRegularStyleSheet,
+ type StyleProperty,
+ type StyleValue,
+} from "@webstudio-is/css-engine";
import {
collectCssVariableReferences,
createCssVariableDeletePayload,
@@ -987,6 +991,150 @@ const instance = (id: string): Instance => ({
});
describe("runtime style operations", () => {
+ test.each([":hover, body", ":hover > div", "body:hover"])(
+ "rejects state selectors that escape the styled element: %s",
+ (state) => {
+ expect(
+ styleUpdateInput.safeParse({
+ instanceId: "box",
+ property: "color",
+ value: { type: "keyword", value: "red" },
+ state,
+ })
+ ).toMatchObject({ success: false });
+ expect(
+ styleDeleteInput.safeParse({
+ instanceId: "box",
+ property: "color",
+ state,
+ })
+ ).toMatchObject({ success: false });
+ expect(
+ designTokenCreateInput.safeParse({
+ name: "Primary",
+ declarations: [
+ {
+ property: "color",
+ value: { type: "keyword", value: "red" },
+ state,
+ },
+ ],
+ })
+ ).toMatchObject({ success: false });
+ }
+ );
+
+ test("preserves an editable compound state through mutation and generated CSS", () => {
+ const state = ":hover:focus-visible";
+ const mutation = updateStyleDeclarations(
+ {
+ breakpoints: runtimeBreakpoints,
+ instances: toMap([instance("box")]),
+ styles: new Map(),
+ styleSources: sources([local("local")]),
+ styleSourceSelections: new Map([
+ ["box", { instanceId: "box", values: ["local"] }],
+ ]),
+ },
+ {
+ updates: [
+ {
+ instanceId: "box",
+ property: "borderTopColor",
+ value: { type: "keyword", value: "currentcolor" },
+ state,
+ },
+ ],
+ },
+ { createId }
+ );
+ const patch = mutation.payload
+ .find((change) => change.namespace === "styles")
+ ?.patches.at(0);
+ if (patch === undefined || patch.op === "remove") {
+ throw new Error("Expected a style declaration patch");
+ }
+ const declaration = patch.value as StyleDecl;
+
+ expect(declaration).toMatchObject({
+ property: "borderTopColor",
+ state,
+ breakpointId: "desktop",
+ });
+
+ const sheet = createRegularStyleSheet();
+ const rule = sheet.addNestingRule(".box");
+ rule.setDeclaration({
+ breakpoint: declaration.breakpointId,
+ selector: declaration.state ?? "",
+ property: declaration.property,
+ value: declaration.value,
+ });
+ expect(rule.toString({ breakpoint: "desktop" })).toContain(
+ ".box:hover:focus-visible {\n border-top-color: currentcolor\n}"
+ );
+ });
+
+ test("rejects declarations for unknown breakpoints", () => {
+ expect(() =>
+ updateStyleDeclarations(
+ {
+ breakpoints: runtimeBreakpoints,
+ instances: toMap([instance("box")]),
+ styles: new Map(),
+ styleSources: sources([local("local")]),
+ styleSourceSelections: new Map([
+ ["box", { instanceId: "box", values: ["local"] }],
+ ]),
+ },
+ {
+ updates: [
+ {
+ instanceId: "box",
+ property: "color",
+ value: { type: "keyword", value: "red" },
+ breakpoint: "missing",
+ },
+ ],
+ },
+ { createId }
+ )
+ ).toThrow("Breakpoint not found");
+ });
+
+ test("does not treat a custom condition as the base breakpoint", () => {
+ const mutation = updateStyleDeclarations(
+ {
+ breakpoints: toMap<Breakpoint>([
+ {
+ id: "dark",
+ label: "Dark",
+ condition: "(prefers-color-scheme: dark)",
+ },
+ { id: "base", label: "Base" },
+ ]),
+ instances: toMap([instance("box")]),
+ styles: new Map(),
+ styleSources: sources([local("local")]),
+ styleSourceSelections: new Map([
+ ["box", { instanceId: "box", values: ["local"] }],
+ ]),
+ },
+ {
+ updates: [
+ {
+ instanceId: "box",
+ property: "color",
+ value: { type: "keyword", value: "red" },
+ },
+ ],
+ },
+ { createId }
+ );
+
+ expect(mutation.result.styleKeys).toEqual(["local:base:color:"]);
+ });
+
test("update styles uses the project base breakpoint when omitted", () => {
const mutation = updateStyleDeclarations(
{
diff --git a/packages/project-build/src/runtime/styles.ts b/packages/project-build/src/runtime/styles.ts
index 167d093f92..5045a26a34 100644
--- a/packages/project-build/src/runtime/styles.ts
+++ b/packages/project-build/src/runtime/styles.ts
@@ -1,7 +1,7 @@
import { z } from "zod";
import { nanoid } from "nanoid";
import deepEqual from "fast-deep-equal";
-import { camelCaseProperty } from "@webstudio-is/css-data";
+import { camelCaseProperty, validateSelector } from "@webstudio-is/css-data";
import { styleValue, toValue, type StyleValue } from "@webstudio-is/css-engine";
import {
getStyleDeclKey,
@@ -37,7 +37,7 @@ import { createRuntimeMutation } from "./mutation";
import { serializeStyleDeclarations } from "./style-utils";
import { createPropValue } from "./props";
import { getStyleSourceStylesSignature } from "./style-copy";
-import { isBaseBreakpoint } from "./breakpoints";
+import { isBaseWidthBreakpoint } from "./breakpoints";
export const serializeDesignTokens = ({
styleSources,
@@ -243,17 +243,32 @@ const normalizeStyleProperty = (property: unknown): StyleDecl["property"] =>
const getBaseBreakpointId = (breakpoints: Breakpoints | undefined) => {
const breakpoint = Array.from(breakpoints?.values() ?? []).find(
- isBaseBreakpoint
+ isBaseWidthBreakpoint
);
return breakpoint?.id ?? DEFAULT_BREAKPOINT_ID;
};
-const withDefaultBreakpoint = <Input extends { breakpoint?: string }>(
+const withValidatedBreakpoint = <Input extends { breakpoint?: string }>(
input: Input,
- breakpoint: string
+ breakpoints: Breakpoints | undefined
): Input => ({
...input,
- breakpoint: input.breakpoint ?? breakpoint,
+ breakpoint:
+ input.breakpoint === undefined
+ ? getBaseBreakpointId(breakpoints)
+ : breakpoints !== undefined && breakpoints.has(input.breakpoint) === false
+ ? throwBuilderRuntimeError("NOT_FOUND", "Breakpoint not found")
+ : input.breakpoint,
+});
+
+const styleStateInput = z.string().superRefine((state, context) => {
+ const result = validateSelector(state);
+ if (result.success === false) {
+ context.addIssue({
+ code: "custom",
+ message: result.error,
+ });
+ }
});
export const styleUpdateInput = z.object({
@@ -261,7 +276,7 @@ export const styleUpdateInput = z.object({
property: z.string(),
value: z.unknown(),
breakpoint: z.string().optional(),
- state: z.string().optional(),
+ state: styleStateInput.optional(),
listed: z.boolean().optional(),
createLocalIfMissing: z.boolean().optional(),
});
@@ -270,7 +285,7 @@ export const styleDeleteInput = z.object({
instanceId: z.string(),
property: z.string(),
breakpoint: z.string().optional(),
- state: z.string().optional(),
+ state: styleStateInput.optional(),
});
const jsonArrayStringInput = (value: unknown) => {
@@ -1116,7 +1131,7 @@ export const designTokenStyleInput = z.object({
property: z.string(),
value: z.unknown(),
breakpoint: z.string().optional(),
- state: z.string().optional(),
+ state: styleStateInput.optional(),
});
type DesignTokenStyleInput = z.input<typeof designTokenStyleInput>;
@@ -3144,7 +3159,7 @@ export const updateStyleDeclarations = (
const { payload, styleKeys, missingLocalStyleSourceInstanceIds } =
createStyleDeclarationUpdatePayload({
updates: input.updates.map((update) =>
- withDefaultBreakpoint(update, getBaseBreakpointId(state.breakpoints))
+ withValidatedBreakpoint(update, state.breakpoints)
),
styleSources: styleState.styleSources,
styleSourceSelections: styleState.styleSourceSelections.values(),
@@ -3182,7 +3197,7 @@ export const deleteStyleDeclarations = (
);
const { payload, styleKeys } = createStyleDeclarationDeletePayload({
deletions: input.deletions.map((deletion) =>
- withDefaultBreakpoint(deletion, getBaseBreakpointId(state.breakpoints))
+ withValidatedBreakpoint(deletion, state.breakpoints)
),
styleSources: styleState.styleSources,
styleSourceSelections: styleState.styleSourceSelections.values(),
@@ -3220,7 +3235,7 @@ export const updateSelectedStyleDeclarations = (
return throwBuilderRuntimeError("BAD_REQUEST", "Style source is locked");
}
return {
- ...withDefaultBreakpoint(update, getBaseBreakpointId(state.breakpoints)),
+ ...withValidatedBreakpoint(update, state.breakpoints),
styleSource,
};
});
@@ -3264,7 +3279,7 @@ export const deleteSelectedStyleDeclarations = (
}
const { payload, styleKeys } = createSelectedStyleDeclarationDeletePayload({
deletions: input.deletions.map((deletion) =>
- withDefaultBreakpoint(deletion, getBaseBreakpointId(state.breakpoints))
+ withValidatedBreakpoint(deletion, state.breakpoints)
),
styles: styleState.styles.values(),
});
@@ -3339,7 +3354,7 @@ export const listCssVariables = (
input: {
filter?: string;
withUsage?: boolean;
- } = {}
+ } & PaginatedOutputInput = {}
) => {
if (state.props === undefined) {
return throwBuilderRuntimeError(
@@ -3348,13 +3363,32 @@ export const listCssVariables = (
);
}
const styleState = getRequiredStyleState(state);
- return serializeCssVariables({
+ const serialized = serializeCssVariables({
styles: styleState.styles.values(),
props: state.props.values(),
styleSourceSelections: styleState.styleSourceSelections.values(),
filter: input.filter,
withUsage: input.withUsage,
});
+ const { items, ...pagination } = paginateOutput({
+ items: serialized.vars.map((variable) =>
+ projectOutput({
+ input,
+ compact: {
+ name: variable.name,
+ scope: variable.scope,
+ usageCount: variable.usageCount,
+ valueLength: variable.value.length,
+ },
+ expanded: () => ({ value: variable.value }),
+ })
+ ),
+ cursor: input.cursor,
+ limit: input.limit,
+ filters: { filter: input.filter, withUsage: input.withUsage },
+ verbose: input.verbose,
+ });
+ return { vars: items, ...pagination };
};
export const defineCssVariables = (
@@ -3545,10 +3579,7 @@ export const createDesignTokens = (
...token,
styles: undefined,
declarations: createDesignTokenStyleInputs(token).map((declaration) =>
- withDefaultBreakpoint(
- declaration,
- getBaseBreakpointId(state.breakpoints)
- )
+ withValidatedBreakpoint(declaration, state.breakpoints)
),
})),
styleSources: new Map(styleState.styleSources),
@@ -3600,10 +3631,7 @@ export const createAttachedDesignTokens = (
...token,
styles: undefined,
declarations: createDesignTokenStyleInputs(token).map((declaration) =>
- withDefaultBreakpoint(
- declaration,
- getBaseBreakpointId(state.breakpoints)
- )
+ withValidatedBreakpoint(declaration, state.breakpoints)
),
})),
styleSources: nextStyleSources,
@@ -3654,7 +3682,7 @@ export const updateDesignTokenStyles = (
const { payload, styleKeys } = createDesignTokenStyleUpdatePayload({
designTokenId: input.designTokenId,
updates: input.updates.map((update) =>
- withDefaultBreakpoint(update, getBaseBreakpointId(state.breakpoints))
+ withValidatedBreakpoint(update, state.breakpoints)
),
styles: styleState.styles.values(),
});
@@ -3677,7 +3705,7 @@ export const deleteDesignTokenStyles = (
const { payload, styleKeys } = createDesignTokenStyleDeletePayload({
designTokenId: input.designTokenId,
deletions: input.deletions.map((deletion) =>
- withDefaultBreakpoint(deletion, getBaseBreakpointId(state.breakpoints))
+ withValidatedBreakpoint(deletion, state.breakpoints)
),
styles: styleState.styles.values(),
});
diff --git a/packages/project-build/src/state/adapters.test.ts b/packages/project-build/src/state/adapters.test.ts
index 44875a09ff..2d52ba7e75 100644
--- a/packages/project-build/src/state/adapters.test.ts
+++ b/packages/project-build/src/state/adapters.test.ts
@@ -2,12 +2,14 @@ import { expect, test } from "vitest";
import { serializePages } from "@webstudio-is/project-migrations/pages";
import { build, pages } from "./fixtures.test-utils";
import {
+ createBuilderBuildDataSnapshotFromState,
createBuilderStateFromBuildData,
createBuilderStateFromCompactBuild,
createBuilderStateFromSerializedSnapshot,
createBuilderStateFromSnapshot,
createSerializedBuilderStateSnapshotFromState,
createBuilderStateSnapshotFromState,
+ createSerializedBuilderBuildDataFromState,
createBuilderStateFromStores,
} from "./adapters";
@@ -129,6 +131,20 @@ test("serializes builder state into a persisted snapshot shape", () => {
expect(snapshot.props).toEqual(build.props);
});
+test("serializes builder state into detached array build data", () => {
+ const state = createBuilderStateFromSnapshot(build);
+ const snapshot = createBuilderBuildDataSnapshotFromState(state);
+
+ expect(snapshot.pages).toEqual(state.pages);
+ expect(snapshot.instances).toEqual(
+ Array.from(state.instances?.values() ?? [])
+ );
+ expect(snapshot.props).toEqual(Array.from(state.props?.values() ?? []));
+ expect(snapshot.instances?.[0]).not.toBe(
+ state.instances?.values().next().value
+ );
+});
+
test("serializes builder state into a JSON-safe persisted snapshot shape", () => {
const state = createBuilderStateFromSnapshot(build);
const snapshot = createSerializedBuilderStateSnapshotFromState(state);
@@ -136,3 +152,13 @@ test("serializes builder state into a JSON-safe persisted snapshot shape", () =>
expect(snapshot.pages).toEqual(serializePages(state.pages!));
expect(snapshot.instances).toEqual(build.instances);
});
+
+test("serializes complete build data with defaults for unloaded maps", () => {
+ const state = createBuilderStateFromSnapshot({ pages });
+ const buildData = createSerializedBuilderBuildDataFromState(state);
+
+ expect(buildData.pages).toEqual(serializePages(state.pages!));
+ expect(buildData.instances).toEqual([]);
+ expect(buildData.props).toEqual([]);
+ expect(buildData.breakpoints).toEqual([]);
+});
diff --git a/packages/project-build/src/state/adapters.ts b/packages/project-build/src/state/adapters.ts
index 46c39c86a5..16511fc7c0 100644
--- a/packages/project-build/src/state/adapters.ts
+++ b/packages/project-build/src/state/adapters.ts
@@ -266,6 +266,33 @@ export const createBuilderStateFromCompactBuild = (
build.projectSettings ?? createProjectSettingsFromPages(build.pages),
});
+export const createBuilderBuildDataSnapshotFromState = (
+ state: BuilderState
+): BuilderBuildDataSnapshot => {
+ const snapshot: BuilderBuildDataSnapshot = {};
+
+ for (const namespace of builderNamespaces) {
+ const value = state[namespace];
+ if (value === undefined) {
+ continue;
+ }
+ if (
+ namespace === "pages" ||
+ namespace === "projectSettings" ||
+ namespace === "marketplaceProduct"
+ ) {
+ (snapshot as Record<string, unknown>)[namespace] = structuredClone(value);
+ continue;
+ }
+ (snapshot as Record<string, unknown>)[namespace] = Array.from(
+ (value as Map<unknown, unknown>).values(),
+ (entry) => structuredClone(entry)
+ );
+ }
+
+ return snapshot;
+};
+
export const createBuilderStateSnapshotFromState = (
state: BuilderState
): BuilderStateSnapshot => {
@@ -303,3 +330,29 @@ export const createSerializedBuilderStateSnapshotFromState = (
}
return snapshot;
};
+
+const toMutableEntries = <Key, Value>(
+ entries: readonly (readonly [Key, Value])[] | undefined
+): [Key, Value][] => Array.from(entries ?? [], ([key, value]) => [key, value]);
+
+export const createSerializedBuilderBuildDataFromState = (
+ state: BuilderState
+) => {
+ const snapshot = createSerializedBuilderStateSnapshotFromState(state);
+ if (snapshot.pages === undefined) {
+ throw new Error("Builder state pages are missing.");
+ }
+ return {
+ pages: snapshot.pages,
+ breakpoints: toMutableEntries(snapshot.breakpoints),
+ styles: toMutableEntries(snapshot.styles),
+ styleSources: toMutableEntries(snapshot.styleSources),
+ styleSourceSelections: toMutableEntries(snapshot.styleSourceSelections),
+ props: toMutableEntries(snapshot.props),
+ instances: toMutableEntries(snapshot.instances),
+ dataSources: toMutableEntries(snapshot.dataSources),
+ resources: toMutableEntries(snapshot.resources),
+ marketplaceProduct: snapshot.marketplaceProduct,
+ projectSettings: snapshot.projectSettings,
+ };
+};
diff --git a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
index 39f149126d..8348e1348c 100644
--- a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
+++ b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
@@ -65,6 +65,7 @@ export const serverOnlyRouterOperationMetadata = {
items: {
type: "string",
enum: [
+ "designTokens",
"pages",
"folders",
"instances",
@@ -72,10 +73,9 @@ export const serverOnlyRouterOperationMetadata = {
"styles",
"styleSources",
"styleSourceSelections",
- "designTokens",
- "assets",
- "resources",
"variables",
+ "resources",
+ "assets",
"breakpoints",
"projectSettings",
"marketplaceProduct",
@@ -251,9 +251,22 @@ export const serverOnlyRouterOperationMetadata = {
permit: "view",
inputSchema: {
type: "object",
- properties: {},
+ properties: {
+ cursor: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
+ },
+ },
required: [],
- additionalProperties: true,
},
},
"publish.create": {
@@ -342,9 +355,22 @@ export const serverOnlyRouterOperationMetadata = {
permit: "view",
inputSchema: {
type: "object",
- properties: {},
+ properties: {
+ cursor: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
+ },
+ },
required: [],
- additionalProperties: true,
},
},
"domains.create": {
diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.ts
index 7422a2844b..6e07e9cb5c 100644
--- a/packages/protocol/src/builder-api/operation-docs.ts
+++ b/packages/protocol/src/builder-api/operation-docs.ts
@@ -47,7 +47,7 @@ const curatedPublicApiOperationDocumentation = [
description: "List site pages",
examples: [
"webstudio list-pages --json",
- "webstudio list-pages --include-folders --json",
+ "webstudio list-pages --cursor 50 --json",
],
},
{
@@ -243,7 +243,7 @@ const curatedPublicApiOperationDocumentation = [
description: "List page folders",
examples: [
"webstudio list-folders --json",
- "webstudio list-folders --include-pages --json",
+ "webstudio list-folders --cursor 50 --json",
],
},
{
@@ -293,7 +293,7 @@ const curatedPublicApiOperationDocumentation = [
{
command: "audit",
description:
- "Audit project accessibility, security, SEO, assets, and styles with structured severity, evidence, remediation, skipped checks, and visual follow-ups",
+ "Audit project accessibility, security, SEO, assets, styles, and optional Craft compatibility with structured severity, evidence, remediation, skipped checks, and visual follow-ups",
examples: [
"webstudio audit --json",
"webstudio audit --scopes accessibility,seo --json",
@@ -301,6 +301,17 @@ const curatedPublicApiOperationDocumentation = [
"webstudio audit --page-path /pricing --json",
'MCP tool: audit {"severities":["error","warning"]}',
'MCP tool: audit {"scopes":["accessibility"],"verbose":true}',
+ 'MCP tool: audit {"scopes":["craft"],"verbose":true}',
+ ],
+ },
+ {
+ command: "verify-bindings",
+ description:
+ "Statically verify persisted text, prop, resource, parameter, action, and page metadata bindings without resolving rendered values or executing external resources",
+ examples: [
+ "webstudio verify-bindings --json",
+ 'MCP tool: verify-bindings {"pagePath":"/pricing"}',
+ 'MCP tool: verify-bindings {"instanceId":"instance-id","limit":50}',
],
},
{
diff --git a/packages/protocol/src/builder-api/operations.test.ts b/packages/protocol/src/builder-api/operations.test.ts
index 8ca9dcdfaa..a329de759f 100644
--- a/packages/protocol/src/builder-api/operations.test.ts
+++ b/packages/protocol/src/builder-api/operations.test.ts
@@ -251,6 +251,26 @@ describe("public api operation catalog", () => {
expect(serverOnlyOperations.length).toBeGreaterThan(0);
});
+ test("classifies every public mutation by architectural owner", () => {
+ const mutations = publicApiOperations.filter(
+ (operation) => operation.method === "mutation"
+ );
+
+ expect(
+ mutations.every((operation) => operation.semanticOwner !== undefined)
+ ).toBe(true);
+ expect(getPublicApiOperation("apply-patch").semanticOwner).toBe(
+ "raw-build-patch"
+ );
+ expect(getPublicApiOperation("upload-asset").semanticOwner).toBe(
+ "local-side-effect"
+ );
+ expect(getPublicApiOperation("publish").semanticOwner).toBe(
+ "server-infrastructure"
+ );
+ expect(getPublicApiOperation("create-page").semanticOwner).toBe("runtime");
+ });
+
test("documents server-only namespace invalidation", () => {
expect(getPublicApiOperation("apply-patch").serverOnly).toBe(true);
expect(getPublicApiOperation("apply-patch").invalidatesNamespaces).toEqual(
diff --git a/packages/protocol/src/builder-api/operations.ts b/packages/protocol/src/builder-api/operations.ts
index 031149da48..af7816c0d6 100644
--- a/packages/protocol/src/builder-api/operations.ts
+++ b/packages/protocol/src/builder-api/operations.ts
@@ -16,6 +16,11 @@ export type {
} from "./runtime-contracts";
export type PublicApiOperationMethod = "query" | "mutation";
+export type PublicApiOperationOwner =
+ | "runtime"
+ | "raw-build-patch"
+ | "server-infrastructure"
+ | "local-side-effect";
export type PublicApiCommand =
(typeof publicApiOperationDocumentation)[number]["command"];
@@ -47,6 +52,7 @@ export type PublicApiOperation<Command extends string = string> = Omit<
examples: readonly string[];
localCapable: boolean;
serverOnly: boolean;
+ semanticOwner: PublicApiOperationOwner;
runtimeOperationId?: PublicRuntimeOperationId;
readNamespaces: readonly PublicApiOperationNamespace[];
writeNamespaces: readonly PublicApiOperationNamespace[];
@@ -108,6 +114,15 @@ const withDefaultPermit = <Operation extends PublicApiOperationInput>(
examples: documentation.examples,
localCapable: runtimeOperation !== undefined,
serverOnly: runtimeOperation === undefined,
+ semanticOwner:
+ runtimeOperation !== undefined
+ ? "runtime"
+ : operation.id === "build.patch"
+ ? "raw-build-patch"
+ : operation.id === "assets.upload" ||
+ operation.id === "assets.uploadMany"
+ ? "local-side-effect"
+ : "server-infrastructure",
runtimeOperationId: runtimeOperation?.id,
readNamespaces: runtimeOperation?.readNamespaces ?? [],
writeNamespaces: runtimeOperation?.writeNamespaces ?? [],
diff --git a/packages/protocol/src/mcp-client.test.ts b/packages/protocol/src/mcp-client.test.ts
index 236496945b..80743f2ed9 100644
--- a/packages/protocol/src/mcp-client.test.ts
+++ b/packages/protocol/src/mcp-client.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from "vitest";
import {
agentClients,
createAgentClientConfiguration,
+ createAgentQuickstart,
createAgentShareUrl,
createAgentSetupCommand,
defaultAgentServerCommand,
@@ -55,6 +56,26 @@ describe("agent connection configuration", () => {
);
expect(defaultAgentServerCommand).toBe("npx -y webstudio@latest mcp");
});
+
+ test.each(agentClients)(
+ "generates the same complete %s quickstart",
+ (client) => {
+ const quickstart = createAgentQuickstart({
+ client,
+ shareUrl: "https://example.com/?authToken=secret&mode=design",
+ });
+
+ expect(quickstart.setupCommand).toContain(
+ `npx -y webstudio@latest connect ${client}`
+ );
+ expect(quickstart.completion).toEqual({
+ connection: quickstart.configuration.hint,
+ firstRead:
+ "Ask your agent to use Webstudio MCP and list the project pages.",
+ });
+ expect(quickstart.configuration.client).toBe(client);
+ }
+ );
});
test("creates a minimal revocable Builder share URL", () => {
diff --git a/packages/protocol/src/mcp-client.ts b/packages/protocol/src/mcp-client.ts
index 730efc3578..53c8361e06 100644
--- a/packages/protocol/src/mcp-client.ts
+++ b/packages/protocol/src/mcp-client.ts
@@ -1,27 +1,52 @@
-export const agentClients = ["claude", "codex", "cursor", "vscode"] as const;
-export type AgentClient = (typeof agentClients)[number];
-
export const defaultAgentServerCommand = "npx -y webstudio@latest mcp";
export const agentServerName = "webstudio";
-export const agentClientTargets = {
- claude: {
+export const agentClientDefinitions = [
+ {
+ client: "claude",
+ format: "json",
+ label: "Claude Code",
path: ".mcp.json",
rootKey: "mcpServers",
hint: "Restart Claude Code in this directory and approve the webstudio server.",
},
- cursor: {
+ {
+ client: "codex",
+ format: "toml",
+ label: "Codex",
+ path: "~/.codex/config.toml",
+ hint: "Restart Codex so it loads the webstudio MCP server.",
+ },
+ {
+ client: "cursor",
+ format: "json",
+ label: "Cursor",
path: ".cursor/mcp.json",
rootKey: "mcpServers",
hint: "Reload Cursor and enable the webstudio server in MCP settings.",
},
- vscode: {
+ {
+ client: "vscode",
+ format: "json",
+ label: "VS Code",
path: ".vscode/mcp.json",
rootKey: "servers",
extraServerFields: { type: "stdio" },
hint: "Reload VS Code and start the webstudio server from the MCP view.",
},
-} as const;
+] as const;
+
+export type AgentClient = (typeof agentClientDefinitions)[number]["client"];
+export type AgentClientDefinition = (typeof agentClientDefinitions)[number];
+
+export const agentClients = agentClientDefinitions.map(({ client }) => client);
+
+export const getAgentClientDefinition = <Client extends AgentClient>(
+ client: Client
+) =>
+ agentClientDefinitions.find(
+ (definition) => definition.client === client
+ ) as Extract<(typeof agentClientDefinitions)[number], { client: Client }>;
export const parseAgentServerCommand = (serverCommand: string) => {
const [command, ...args] = serverCommand.trim().split(/\s+/);
@@ -49,17 +74,19 @@ export const createAgentClientConfiguration = (
client: AgentClient,
serverCommand = defaultAgentServerCommand
) => {
- if (client === "codex") {
+ const target = getAgentClientDefinition(client);
+ if (target.format === "toml") {
return {
client,
- path: "~/.codex/config.toml",
+ label: target.label,
+ path: target.path,
content: createCodexAgentSnippet(serverCommand),
- hint: "Restart Codex so it loads the webstudio MCP server.",
+ hint: target.hint,
};
}
- const target = agentClientTargets[client];
return {
client,
+ label: target.label,
path: target.path,
content: `${JSON.stringify(
{
@@ -80,18 +107,43 @@ export const createAgentClientConfiguration = (
const quoteShellArgument = (value: string) =>
`'${value.replaceAll("'", `'"'"'`)}'`;
+export const createAgentQuickstart = ({
+ client,
+ shareUrl,
+ serverCommand = defaultAgentServerCommand,
+}: {
+ client: AgentClient;
+ shareUrl?: string;
+ serverCommand?: string;
+}) => {
+ const configuration = createAgentClientConfiguration(client, serverCommand);
+ return {
+ client,
+ label: configuration.label,
+ configuration,
+ completion: {
+ connection: configuration.hint,
+ firstRead:
+ "Ask your agent to use Webstudio MCP and list the project pages.",
+ },
+ setupCommand:
+ shareUrl === undefined
+ ? undefined
+ : [
+ `npx -y webstudio@latest init --link ${quoteShellArgument(shareUrl)} --json`,
+ "npx -y webstudio@latest sync",
+ `npx -y webstudio@latest connect ${client}`,
+ ].join(" && "),
+ };
+};
+
export const createAgentSetupCommand = ({
client,
shareUrl,
}: {
client: AgentClient;
shareUrl: string;
-}) =>
- [
- `npx -y webstudio@latest init --link ${quoteShellArgument(shareUrl)} --json`,
- "npx -y webstudio@latest sync",
- `npx -y webstudio@latest connect ${client}`,
- ].join(" && ");
+}) => createAgentQuickstart({ client, shareUrl }).setupCommand ?? "";
export const createAgentShareUrl = ({
builderUrl,
diff --git a/packages/protocol/src/schema.test.ts b/packages/protocol/src/schema.test.ts
index b3fa8ef7fd..bdd7eac2da 100644
--- a/packages/protocol/src/schema.test.ts
+++ b/packages/protocol/src/schema.test.ts
@@ -13,6 +13,8 @@ import {
stagedUploadProjectIdHeader,
buildPatchNamespaces,
buildPatchTransaction,
+ getPublicBuildIncludes,
+ publicBuildIncludes,
} from "./schema";
import { createPublishedProjectBundleFixture } from "./fixtures";
@@ -204,4 +206,21 @@ describe("project bundle contract", () => {
}).success
).toBe(false);
});
+
+ test("maps every builder namespace to a supported public build include", () => {
+ const includes = getPublicBuildIncludes(builderNamespaces);
+
+ expect(includes).toContain("projectSettings");
+ expect(includes).toContain("marketplaceProduct");
+ expect(includes).toContain("folders");
+ expect(includes).toContain("variables");
+ expect(includes).not.toContain("dataSources");
+ expect(publicBuildIncludes).toContain("designTokens");
+ expect(
+ includes.every((include) => publicBuildIncludes.includes(include))
+ ).toBe(true);
+ expect(new Set(publicBuildIncludes)).toEqual(
+ new Set([...includes, "designTokens"])
+ );
+ });
});
diff --git a/packages/protocol/src/schema.ts b/packages/protocol/src/schema.ts
index fa2d365e15..a40fb397dd 100644
--- a/packages/protocol/src/schema.ts
+++ b/packages/protocol/src/schema.ts
@@ -101,6 +101,34 @@ export const checkProjectBuildPermissionInput = z.object({
});
export const buildPatchNamespaces = builderNamespaces;
+type BuilderNamespace = (typeof builderNamespaces)[number];
+export type PublicBuildInclude =
+ | Exclude<BuilderNamespace, "dataSources">
+ | "folders"
+ | "variables"
+ | "designTokens";
+
+export const getPublicBuildIncludes = (
+ namespaces: readonly BuilderNamespace[]
+): PublicBuildInclude[] => [
+ ...new Set(
+ namespaces.flatMap((namespace): PublicBuildInclude[] => {
+ if (namespace === "pages") {
+ return ["pages", "folders"];
+ }
+ if (namespace === "dataSources") {
+ return ["variables"];
+ }
+ return [namespace];
+ })
+ ),
+];
+
+export const publicBuildIncludes = [
+ "designTokens",
+ ...getPublicBuildIncludes(builderNamespaces),
+] as const satisfies readonly [PublicBuildInclude, ...PublicBuildInclude[]];
+
export type BuildPatchPath = Array<string | number>;
export type BuildPatch =
| { op: "add"; path: BuildPatchPath; value: unknown }