diff --git a/apps/builder/app/builder/features/style-panel/property-label.test.tsx b/apps/builder/app/builder/features/style-panel/property-label.test.tsx index 0ddb96f619..f8706179e7 100644 --- a/apps/builder/app/builder/features/style-panel/property-label.test.tsx +++ b/apps/builder/app/builder/features/style-panel/property-label.test.tsx @@ -2,11 +2,111 @@ import { act } from "react-dom/test-utils"; import { afterEach, expect, test } from "vitest"; import { userEvent } from "@vitest/browser/context"; import { TooltipProvider } from "@webstudio-is/design-system"; +import { createDefaultPages } from "@webstudio-is/project-build"; +import { getTagStyleId } from "@webstudio-is/sdk"; +import { + selectInstance, + $selectedInstanceSelector, + $selectedPageId, + $selectedStyleSources, + $selectedStyleState, + $temporaryTagStyleId, +} from "~/shared/nano-states"; +import { + $breakpoints, + $instances, + $pages, + $styleSources, +} from "~/shared/sync/data-stores"; +import type { ComputedStyleDecl } from "~/shared/style-object-model"; import { createAssetManagerTestRenderer } from "~/builder/shared/asset-manager/test-utils"; -import { PropertyInlineLabel } from "./property-label"; +import { PropertyInfo, PropertyInlineLabel } from "./property-label"; const renderer = createAssetManagerTestRenderer(); -afterEach(renderer.cleanup); +afterEach(() => { + renderer.cleanup(); + selectInstance(undefined); + $selectedPageId.set(undefined); + $pages.set(undefined); + $instances.set(new Map()); + $styleSources.set(new Map()); + $breakpoints.set(new Map()); + $selectedStyleSources.set(new Map()); + $selectedStyleState.set(undefined); + $temporaryTagStyleId.set(undefined); +}); + +test("nested source badge keeps a valid ancestor selection and is cascaded", async () => { + const pages = createDefaultPages({ rootInstanceId: "container" }); + $pages.set(pages); + $selectedPageId.set(pages.homePageId); + $instances.set( + new Map([ + [ + "container", + { + type: "instance" as const, + id: "container", + component: "Box", + children: [{ type: "id" as const, value: "heading" }], + }, + ], + [ + "heading", + { + type: "instance" as const, + id: "heading", + component: "Heading", + children: [], + }, + ], + ]) + ); + const tagStyleId = getTagStyleId("div"); + $styleSources.set( + new Map([[tagStyleId, { type: "tag", id: tagStyleId, tag: "div" }]]) + ); + $breakpoints.set(new Map([["base", { id: "base", label: "Base" }]])); + selectInstance(["heading", "container"]); + const value = { type: "keyword", value: "red" } as const; + const styles: ComputedStyleDecl[] = [ + { + property: "color", + source: { + name: "remote", + instanceId: "container", + styleSourceId: tagStyleId, + breakpointId: "base", + state: " h2:hover", + }, + cascadedValue: value, + computedValue: value, + usedValue: value, + }, + ]; + const container = renderer.render( + + ); + + const sourceButton = Array.from(container.querySelectorAll("button")).find( + (button) => button.textContent?.includes("div") + ); + expect(sourceButton).toBeDefined(); + await act(async () => userEvent.click(sourceButton!)); + + expect($selectedInstanceSelector.get()).toEqual(["container"]); + expect($selectedStyleSources.get().get("container")).toBe(tagStyleId); + expect($selectedStyleState.get()).toBe(" h2:hover"); + expect($temporaryTagStyleId.get()).toBe(tagStyleId); + expect(container.textContent).toContain("Cascaded:"); + $instances.set(new Map($instances.get())); + expect($selectedInstanceSelector.get()).toEqual(["container"]); +}); test("inline property labels offer keyboard-accessible information without a reset action", async () => { const container = renderer.render( diff --git a/apps/builder/app/builder/features/style-panel/property-label.tsx b/apps/builder/app/builder/features/style-panel/property-label.tsx index 1da60216fc..0b090bebe0 100644 --- a/apps/builder/app/builder/features/style-panel/property-label.tsx +++ b/apps/builder/app/builder/features/style-panel/property-label.tsx @@ -1,5 +1,6 @@ import { useStore } from "@nanostores/react"; import { useState, type ReactNode } from "react"; +import { ROOT_INSTANCE_ID } from "@webstudio-is/sdk"; import { AlertIcon, ResetIcon } from "@webstudio-is/icons"; import { toValue, type CssProperty } from "@webstudio-is/css-engine"; import { propertiesData } from "@webstudio-is/css-data"; @@ -159,7 +160,12 @@ export const PropertyInfo = ({ if (target === undefined) { return; } - selectInstance(target.instanceSelector); + const targetSelector = target.instanceSelector; + selectInstance( + targetSelector.length > 1 && targetSelector.at(-1) === ROOT_INSTANCE_ID + ? targetSelector.slice(0, -1) + : targetSelector + ); if (source.styleSourceId) { if (styleSources.get(source.styleSourceId)?.type === "tag") { $temporaryTagStyleId.set(source.styleSourceId); @@ -211,13 +217,15 @@ export const PropertyInfo = ({ selectedInstanceId !== undefined && (sourceColor === "remote" || sourceColor === "preset") ) { - const sourceInstances = styles - .filter((style) => style.source.name === sourceColor) - .map((style) => style.source.instanceId); + const matchingStyles = styles.filter( + (style) => style.source.name === sourceColor + ); if ( - sourceInstances.every( - (instanceId) => - instanceId !== undefined && instanceId !== selectedInstanceId + matchingStyles.every( + ({ source }) => + source.instanceId !== undefined && + source.instanceId !== selectedInstanceId && + source.state?.startsWith(" ") !== true ) ) { sourceLabel = sourceColor === "remote" ? "Inherited" : "Preset"; @@ -227,7 +235,9 @@ export const PropertyInfo = ({ : "Comes from a Webstudio component default on an ancestor element."; } else if ( sourceColor === "remote" && - sourceInstances.every((instanceId) => instanceId === selectedInstanceId) + matchingStyles.every( + ({ source }) => source.instanceId === selectedInstanceId + ) ) { sourceDescription = "Comes from another style source, breakpoint, or state on this element."; diff --git a/apps/builder/app/builder/features/style-panel/shared/model.tsx b/apps/builder/app/builder/features/style-panel/shared/model.tsx index fc563f17ee..9e5a582d7b 100644 --- a/apps/builder/app/builder/features/style-panel/shared/model.tsx +++ b/apps/builder/app/builder/features/style-panel/shared/model.tsx @@ -27,6 +27,7 @@ import { $propsIndex, $selectedBreakpoint, $selectedInstanceStates, + $selectedInstanceStatesByInstanceId, $selectedOrLastStyleSourceSelector, } from "~/shared/nano-states"; import { $breakpoints } from "~/shared/sync/data-stores"; @@ -233,6 +234,7 @@ export const $styleObjectModel = computed( $instanceComponents, $matchingBreakpoints, $selectedInstanceStates, + $selectedInstanceStatesByInstanceId, ], ( styles, @@ -242,7 +244,8 @@ export const $styleObjectModel = computed( instanceTags, instanceComponents, matchingBreakpoints, - matchingStates + matchingStates, + matchingStatesByInstanceId ): StyleObjectModel => { const tagStyleIds = new Map(); for (const source of styleSources.values()) { @@ -259,6 +262,7 @@ export const $styleObjectModel = computed( instanceComponents, matchingBreakpoints, matchingStates, + matchingStatesByInstanceId, }; } ); diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.test.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.test.tsx index de006a039d..f3924fd98c 100644 --- a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.test.tsx +++ b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.test.tsx @@ -190,6 +190,44 @@ test("describes Copy and keeps the style source menu width stable", () => { } }); +test("describes the supported selectors when Add more receives focus", () => { + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + try { + act(() => + root.render( + {}} + selectedItemSelector={undefined} + item={{ + id: "tag-style:button", + label: "button", + source: "tag", + disabled: false, + locked: false, + states: [], + }} + hasStyles={false} + states={[]} + /> + ) + ); + const input = document.querySelector( + "[role=menu] form input" + ); + expect(input).not.toBeNull(); + act(() => input?.focus()); + expect(document.querySelector("[role=menu]")?.textContent).toContain( + "Start with a tag, such as h2, h2:hover, or h2::before" + ); + } finally { + act(() => root.unmount()); + container.remove(); + } +}); + test("disables Copy when a source has no declarations", () => { const container = document.createElement("div"); document.body.appendChild(container); diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source-menu.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source-menu.tsx index 82c1eef47a..27cd1b1f65 100644 --- a/apps/builder/app/builder/features/style-panel/style-source/style-source-menu.tsx +++ b/apps/builder/app/builder/features/style-panel/style-source/style-source-menu.tsx @@ -124,6 +124,8 @@ const menuActionDescriptions = { unlock: "Allow style changes on this token again.", detach: "Remove this token from the element without deleting it.", delete: "Permanently delete this token and all its styles from the project.", + addMore: + "Use :hover or [data-state=open] to style this element in a state, and ::before to style its pseudo-element. Start with a tag, such as h2, h2:hover, or h2::before, to style nested elements.", } as const; type MenuAction = keyof typeof menuActionDescriptions; @@ -172,11 +174,13 @@ const getSelectorDescription = (selector: string | null | undefined) => { const SelectorCombobox = ({ existingSelectors, - allowDescendants, + onFocus, + onBlur, onSelect, }: { existingSelectors: string[]; - allowDescendants: boolean; + onFocus: () => void; + onBlur: () => void; onSelect: (selector: string) => void; }) => { const [value, setValue] = useState(""); @@ -184,10 +188,10 @@ const SelectorCombobox = ({ const handleSubmit = (selector: string) => { let normalizedSelector = selector; - let validation = validateSelector(normalizedSelector, { allowDescendants }); - if (validation.success === false && allowDescendants) { + let validation = validateSelector(normalizedSelector); + if (validation.success === false) { const tagSelector = ` ${selector}`; - const tagValidation = validateSelector(tagSelector, { allowDescendants }); + const tagValidation = validateSelector(tagSelector); if (tagValidation.success && tagValidation.type === "tag") { normalizedSelector = tagSelector; validation = tagValidation; @@ -202,14 +206,14 @@ const SelectorCombobox = ({ setValue(""); }; - const availableItems = allSelectors.filter( - (selector) => - (allowDescendants || tags.includes(selector) === false) && - existingSelectors.every((s) => s.trim() !== selector) + const availableItems = allSelectors.filter((selector) => + existingSelectors.every((s) => s.trim() !== selector) ); return (
event.stopPropagation()} onSubmit={(event) => { event.preventDefault(); @@ -271,13 +275,7 @@ type StyleSourceMenuProps = { }; export const StyleSourceMenu = (props: StyleSourceMenuProps) => { - const availableStates = - props.item.source === "tag" - ? props.states.filter( - ({ selector }) => - validateSelector(selector, { allowDescendants: false }).success - ) - : props.states; + const availableStates = props.states; const [highlightedSelector, setHighlightedSelector] = useState<{ selector: string; type: "state" | "pseudoElement" | "tag"; @@ -549,7 +547,11 @@ export const StyleSourceMenu = (props: StyleSourceMenuProps) => { existingSelectors={availableStates.map( (state) => state.selector )} - allowDescendants={props.item.source !== "tag"} + onFocus={() => { + setHighlightedSelector(undefined); + setHighlightedAction("addMore"); + }} + onBlur={() => setHighlightedAction(undefined)} onSelect={(selector) => props.onAddSelector?.(props.item.id, selector) } diff --git a/apps/builder/app/canvas/selected-instance-effects.test.ts b/apps/builder/app/canvas/selected-instance-effects.test.ts index 64f26b64ed..f8db668df4 100644 --- a/apps/builder/app/canvas/selected-instance-effects.test.ts +++ b/apps/builder/app/canvas/selected-instance-effects.test.ts @@ -6,11 +6,13 @@ import { $selectedInstanceOutline, $selectedInstanceOutlines, $selectedInstanceStates, + $selectedInstanceStatesByInstanceId, selectInstances, } from "~/shared/nano-states"; import { $instances, $styleSourceSelections, + $styleSources, $styles, } from "~/shared/sync/data-stores"; import { subscribeSelected } from "./selected-instance-effects"; @@ -95,9 +97,11 @@ beforeEach(() => { ]) ); $styleSourceSelections.set(new Map()); + $styleSources.set(new Map()); $styles.set(new Map()); $allSelectedInstanceSelectors.set([]); $selectedInstanceStates.set(new Set()); + $selectedInstanceStatesByInstanceId.set(new Map()); $selectedInstanceOutline.set(undefined); $selectedInstanceOutlines.set([]); document.body.innerHTML = ""; @@ -113,8 +117,10 @@ afterEach(() => { $instances.set(new Map()); $styles.set(new Map()); $styleSourceSelections.set(new Map()); + $styleSources.set(new Map()); $allSelectedInstanceSelectors.set([]); $selectedInstanceStates.set(new Set()); + $selectedInstanceStatesByInstanceId.set(new Map()); $selectedInstanceOutline.set(undefined); $selectedInstanceOutlines.set([]); }); @@ -173,6 +179,47 @@ describe("subscribeSelected", () => { expect($selectedInstanceStates.get()).toEqual(new Set()); }); + test("detects an active attribute condition on a nested global Tag style", () => { + const parent = document.createElement("div"); + parent.setAttribute(idAttribute, "box"); + parent.setAttribute(selectorIdAttribute, "box"); + const heading = document.createElement("h2"); + heading.setAttribute(idAttribute, "heading"); + heading.setAttribute(selectorIdAttribute, "heading,box"); + heading.setAttribute("data-state", "open"); + parent.appendChild(heading); + document.body.appendChild(parent); + const id = getTagStyleId("div"); + $styleSources.set(new Map([[id, { type: "tag", id, tag: "div" }]])); + $styles.set( + new Map([ + [ + "nested-tag-attribute", + { + styleSourceId: id, + breakpointId: "base", + state: " h2[ data-state = open ]", + property: "color", + value: { type: "keyword", value: "red" }, + }, + ], + ]) + ); + unsubscribe = subscribeSelected((callback) => callback()); + + selectInstances([["heading", "box"]]); + + expect($selectedInstanceStates.get()).toEqual( + new Set(["[ data-state = open ]"]) + ); + expect($selectedInstanceStatesByInstanceId.get()).toEqual( + new Map([ + ["heading", new Set(["[ data-state = open ]"])], + ["box", new Set()], + ]) + ); + }); + test("creates both outline stores for one selected instance", () => { createCanvasElement({ selector: "box,body", diff --git a/apps/builder/app/canvas/selected-instance-effects.ts b/apps/builder/app/canvas/selected-instance-effects.ts index c4565a6bad..0ef8afd512 100644 --- a/apps/builder/app/canvas/selected-instance-effects.ts +++ b/apps/builder/app/canvas/selected-instance-effects.ts @@ -8,6 +8,7 @@ import { } from "@webstudio-is/css-data"; import { selectorIdAttribute } from "@webstudio-is/react-sdk"; import { subscribeWindowResize } from "~/shared/dom-hooks"; +import { areSetsEqual } from "~/shared/collection-equality"; import { $isResizingCanvas, $selectedInstanceSizes, @@ -15,12 +16,16 @@ import { $stylesIndex, $propValuesByInstanceSelectorWithMemoryProps, $selectedInstanceStates, + $selectedInstanceStatesByInstanceId, $selectedStyleState, $allSelectedInstanceSelectors, type UnitSizes, type PropertySizes, } from "~/shared/nano-states"; -import { $styleSourceSelections } from "~/shared/sync/data-stores"; +import { + $styleSourceSelections, + $styleSources, +} from "~/shared/sync/data-stores"; import { getAllElementsBoundingBox, getVisibleElementsByInstanceSelector, @@ -288,44 +293,104 @@ const subscribeSelectedInstance = ( const { propertySizes, computedValues } = readComputedStyles(element); $selectedInstanceSizes.set({ unitSizes, propertySizes, computedValues }); - const availableStates = new Set(); - const instanceStyleSourceIds = new Set( - $styleSourceSelections.get().get(instanceId)?.values - ); - instanceStyleSourceIds.add(getTagStyleId(element.localName)); + const styleSourceSelections = $styleSourceSelections.get(); + const styleSources = $styleSources.get(); const styles = $styles.get(); - for (const styleDecl of styles.values()) { - if ( - instanceStyleSourceIds.has(styleDecl.styleSourceId) && - styleDecl.state - ) { - availableStates.add(styleDecl.state); + const matchingStatesByInstanceId = new Map>(); + const elementsByInstanceId = new Map(); + for ( + let ancestor: HTMLElement | null = element; + ancestor; + ancestor = ancestor.parentElement + ) { + const id = ancestor.getAttribute(selectorIdAttribute)?.split(",")[0]; + if (id) { + elementsByInstanceId.set(id, ancestor); } } - const activeStates = new Set(); - for (const state of availableStates) { - if ( - validateSelector(state, { allowDescendants: false }).success === false - ) { + for (const [index, id] of selectedInstanceSelector.entries()) { + const target = elementsByInstanceId.get(id); + if (!target) { continue; } - try { - // pseudo classes like :open or :current are not supported in .matches method - if (element.matches(state)) { - activeStates.add(state); + const ownSources = new Set(styleSourceSelections.get(id)?.values); + ownSources.add(getTagStyleId(target.localName)); + const ancestorSources = new Set(); + for (const ancestorId of selectedInstanceSelector.slice(index + 1)) { + for (const sourceId of styleSourceSelections.get(ancestorId)?.values ?? + []) { + ancestorSources.add(sourceId); } - } catch { - warnOnce(true, `state selector "${state}" is invalid`); } + for ( + let ancestor = target.parentElement; + ancestor; + ancestor = ancestor.parentElement + ) { + const sourceId = getTagStyleId(ancestor.localName); + if (styleSources.get(sourceId)?.type === "tag") { + ancestorSources.add(sourceId); + } + } + const availableStates = new Set(); + const activeStates = new Set(); + for (const styleDecl of styles.values()) { + if (!styleDecl.state) { + continue; + } + if (ownSources.has(styleDecl.styleSourceId)) { + availableStates.add(styleDecl.state); + } + if (ancestorSources.has(styleDecl.styleSourceId)) { + const validation = validateSelector(styleDecl.state); + if ( + validation.success && + validation.type === "tag" && + validation.tag.toLowerCase() === target.localName && + validation.condition + ) { + try { + if (target.matches(styleDecl.state.trim())) { + activeStates.add(validation.condition); + } + } catch { + warnOnce(true, `state selector "${styleDecl.state}" is invalid`); + } + } + } + } + for (const state of availableStates) { + if ( + validateSelector(state, { allowDescendants: false }).success === false + ) { + continue; + } + try { + // pseudo classes like :open or :current are not supported in .matches method + if (target.matches(state)) { + activeStates.add(state); + } + } catch { + warnOnce(true, `state selector "${state}" is invalid`); + } + } + matchingStatesByInstanceId.set(id, activeStates); } + const previousStates = $selectedInstanceStatesByInstanceId.get(); + if ( + previousStates.size !== matchingStatesByInstanceId.size || + [...matchingStatesByInstanceId].some(([id, states]) => { + const previous = previousStates.get(id); + return previous === undefined || !areSetsEqual(states, previous); + }) + ) { + $selectedInstanceStatesByInstanceId.set(matchingStatesByInstanceId); + } + const activeStates = + matchingStatesByInstanceId.get(instanceId) ?? new Set(); const selectedStates = $selectedInstanceStates.get(); - if ( - activeStates.size !== selectedStates.size || - Array.from(activeStates).some( - (state) => selectedStates.has(state) === false - ) - ) { + if (!areSetsEqual(activeStates, selectedStates)) { $selectedInstanceStates.set(activeStates); } }; diff --git a/apps/builder/app/canvas/shared/styles.test.ts b/apps/builder/app/canvas/shared/styles.test.ts index 849eede940..2c22df3484 100644 --- a/apps/builder/app/canvas/shared/styles.test.ts +++ b/apps/builder/app/canvas/shared/styles.test.ts @@ -228,20 +228,41 @@ describe("renderStateStyles", () => { }); }); - test("descendant tag styles preview on the matching tag", () => { + test.each([" h1", ' h2[a="123"]', " h2:hover", " h2::before"])( + "descendant tag styles preview on the matching tag: %s", + (state) => { + const sheet = createTestSheet(); + renderStateStyles({ + instanceStyles: { + instanceId: "box", + selectedState: state, + breakpoints: [{ id: "base", label: "Base" }], + styles: [createStyleDecl()], + }, + sheet, + transformValue: mockTransformValue, + toStyleValue: mockToStyleValue, + }); + expect(sheet.cssText).toContain(`:where([data-ws-id="box"])${state}`); + } + ); + + test("global Tag descendant preview keeps the saved selector specificity", () => { const sheet = createTestSheet(); renderStateStyles({ instanceStyles: { instanceId: "box", - selectedState: " h1", + selectedState: " h2:hover", breakpoints: [{ id: "base", label: "Base" }], - styles: [createStyleDecl()], + styles: [createStyleDecl({ styleSourceId: getTagStyleId("div") })], }, sheet, transformValue: mockTransformValue, toStyleValue: mockToStyleValue, }); - expect(sheet.cssText).toContain('[data-ws-id="box"] h1'); + expect(sheet.cssText).toContain( + ':where([data-ws-id="box"]):where(div) h2:hover' + ); }); test("Tag preview selectors stay below instance selectors at every breakpoint", () => { @@ -995,7 +1016,7 @@ test("ephemeral Tag state edits update and clean up the selected preview", () => expect( document.querySelector('style[data-webstudio="state-styles"]') ?.textContent - ).toContain('[data-ws-id="ephemeral-tag-test"] h1'); + ).toContain(':where([data-ws-id="ephemeral-tag-test"]) h1'); } finally { $ephemeralStyles.set([]); unsubscribeEphemeral(); diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.ts index a0cd405346..c79cf8227e 100644 --- a/apps/builder/app/canvas/shared/styles.ts +++ b/apps/builder/app/canvas/shared/styles.ts @@ -848,14 +848,19 @@ const getTagStatePreviewSelector = ( tag: string, state: string ) => - shouldSimulateState(state) - ? `:where(${selector}):is(${tag}, ${tag}${state})` - : `:where(${selector})${tag}${getStatePreviewSelector(state)}`; + state.startsWith(" ") + ? `:where(${selector}):where(${tag})${state}` + : shouldSimulateState(state) + ? `:where(${selector}):is(${tag}, ${tag}${state})` + : `:where(${selector})${tag}${getStatePreviewSelector(state)}`; -const getInstanceStatePreviewSelector = (selector: string, state: string) => - shouldSimulateState(state) - ? `${selector}:is(*, ${state})` - : `${selector}${getStatePreviewSelector(state)}`; +const getInstanceStatePreviewSelector = (selector: string, state: string) => { + if (shouldSimulateState(state)) { + return `${selector}:is(*, ${state})`; + } + const base = state.startsWith(" ") ? `:where(${selector})` : selector; + return `${base}${getStatePreviewSelector(state)}`; +}; const shouldRenderEphemeralTagState = ( styleDecl: StyleDecl, diff --git a/apps/builder/app/shared/nano-states/misc.ts b/apps/builder/app/shared/nano-states/misc.ts index 061e34ec66..8e18a8f70d 100644 --- a/apps/builder/app/shared/nano-states/misc.ts +++ b/apps/builder/app/shared/nano-states/misc.ts @@ -319,6 +319,9 @@ export const $selectedStyleSource = computed( * to display style values as remote */ export const $selectedInstanceStates = atom(new Set()); +export const $selectedInstanceStatesByInstanceId = atom( + new Map>() +); export const $hoveredInstanceSelector = atom( undefined diff --git a/apps/builder/app/shared/style-object-model.test.tsx b/apps/builder/app/shared/style-object-model.test.tsx index 0bd7eb1308..eef7ea0a39 100644 --- a/apps/builder/app/shared/style-object-model.test.tsx +++ b/apps/builder/app/shared/style-object-model.test.tsx @@ -1103,6 +1103,285 @@ test("tag token provides the source for an unstyled matching element", () => { ).toMatchObject({ styleSourceId: id, instanceId: "box" }); }); +test("shows the div's nested h2 color when h2 is selected", () => { + const model = createModel({ + css: "container { color: black; }", + jsx: ( + + + + ), + }); + const descendantStyle: StyleDecl = { + styleSourceId: "container", + breakpointId: "base", + state: " h2", + property: "color", + value: { type: "keyword", value: "purple" }, + }; + model.styles.set(getStyleDeclKey(descendantStyle), descendantStyle); + + expect( + getComputedStyleDecl({ + model, + instanceSelector: ["heading", "container"], + styleSourceId: "headingLocal", + property: "color", + }) + ).toMatchObject({ + cascadedValue: { type: "keyword", value: "purple" }, + usedValue: { type: "keyword", value: "purple" }, + source: { + instanceId: "container", + styleSourceId: "container", + state: " h2", + }, + }); + + for (const state of ['[a="123"]', ":hover", "::before"]) { + const scopedStyle: StyleDecl = { + ...descendantStyle, + state: ` h2${state}`, + value: { type: "keyword", value: "green" }, + }; + model.styles.set(getStyleDeclKey(scopedStyle), scopedStyle); + expect( + getComputedStyleDecl({ + model, + instanceSelector: ["heading", "container"], + styleSourceId: "headingLocal", + state, + property: "color", + }).usedValue + ).toEqual({ type: "keyword", value: "green" }); + } + + model.styleSourceSelections.set("heading", { + instanceId: "heading", + values: ["headingToken"], + }); + const headingStyle: StyleDecl = { + ...descendantStyle, + styleSourceId: "headingToken", + state: undefined, + value: { type: "keyword", value: "red" }, + }; + model.styles.set(getStyleDeclKey(headingStyle), headingStyle); + expect( + getComputedStyleDecl({ + model, + instanceSelector: ["heading", "container"], + property: "color", + }).usedValue + ).toEqual({ type: "keyword", value: "red" }); +}); + +test("keeps a descendant attribute state off its ancestor's inherited color", () => { + const model = createModel({ + css: "container { color: black; }", + jsx: ( + + + + ), + matchingStates: new Set(["[data-active]"]), + }); + model.matchingStatesByInstanceId = new Map([ + ["container", new Set()], + ["heading", new Set(["[data-active]"])], + ]); + const parentState: StyleDecl = { + styleSourceId: "container", + breakpointId: "base", + state: "[data-active]", + property: "color", + value: { type: "keyword", value: "red" }, + }; + const nestedState: StyleDecl = { + ...parentState, + state: " h2[data-active]", + property: "paddingTop", + value: { type: "unit", unit: "px", value: 10 }, + }; + for (const styleDecl of [parentState, nestedState]) { + model.styles.set(getStyleDeclKey(styleDecl), styleDecl); + } + expect( + getComputedStyleDecl({ + model, + instanceSelector: ["heading", "container"], + styleSourceId: "heading", + property: "color", + }).usedValue + ).toEqual({ type: "keyword", value: "black" }); + model.matchingStatesByInstanceId?.set( + "container", + new Set(["[data-active]"]) + ); + expect( + getComputedStyleDecl({ + model, + instanceSelector: ["heading", "container"], + styleSourceId: "heading", + property: "color", + }).usedValue + ).toEqual({ type: "keyword", value: "red" }); +}); + +test("matches saved nested tag casing and leading whitespace", () => { + const model = createModel({ + css: "", + jsx: ( + + + + ), + }); + const styleDecl: StyleDecl = { + styleSourceId: "container", + breakpointId: "base", + state: " H2", + property: "color", + value: { type: "keyword", value: "purple" }, + }; + model.styles.set(getStyleDeclKey(styleDecl), styleDecl); + expect( + getComputedStyleDecl({ + model, + instanceSelector: ["heading", "container"], + property: "color", + }) + ).toMatchObject({ + usedValue: { type: "keyword", value: "purple" }, + source: { state: " H2" }, + }); +}); + +test("shows nested global Tag color and lets an attached Token override it", () => { + const model = createModel({ + css: "", + jsx: ( + + + + ), + matchingBreakpoints: ["base", "small"], + }); + const id = getTagStyleId("div"); + model.tagStyleIds.set("div", id); + const globalStyle: StyleDecl = { + styleSourceId: id, + breakpointId: "base", + state: " h2:hover", + property: "color", + value: { type: "keyword", value: "purple" }, + }; + model.styles.set(getStyleDeclKey(globalStyle), globalStyle); + const selected = { + model, + instanceSelector: ["heading", "container"], + state: ":hover", + property: "color" as const, + }; + expect(getComputedStyleDecl(selected).usedValue).toEqual({ + type: "keyword", + value: "purple", + }); + const headingTagId = getTagStyleId("h2"); + model.tagStyleIds.set("h2", headingTagId); + const headingTagStyle: StyleDecl = { + ...globalStyle, + styleSourceId: headingTagId, + state: ":hover", + value: { type: "keyword", value: "red" }, + }; + model.styles.set(getStyleDeclKey(headingTagStyle), headingTagStyle); + expect(getComputedStyleDecl(selected).usedValue).toEqual({ + type: "keyword", + value: "red", + }); + const responsiveStyle: StyleDecl = { + ...globalStyle, + breakpointId: "small", + value: { type: "keyword", value: "green" }, + }; + model.styles.set(getStyleDeclKey(responsiveStyle), responsiveStyle); + expect(getComputedStyleDecl(selected).usedValue).toEqual({ + type: "keyword", + value: "green", + }); + const tokenStyle: StyleDecl = { + ...globalStyle, + styleSourceId: "headingToken", + state: ":hover", + value: { type: "keyword", value: "blue" }, + }; + model.styles.set(getStyleDeclKey(tokenStyle), tokenStyle); + expect(getComputedStyleDecl(selected).usedValue).toEqual({ + type: "keyword", + value: "blue", + }); +}); + +test("matches breakpoint and source order for nested Tag styles", () => { + const model = createModel({ + css: "", + jsx: ( + + + + + + ), + matchingBreakpoints: ["base", "small"], + }); + const innerStyle: StyleDecl = { + styleSourceId: "inner", + breakpointId: "base", + state: " h2", + property: "color", + value: { type: "keyword", value: "red" }, + }; + const outerStyle: StyleDecl = { + ...innerStyle, + styleSourceId: "outer", + breakpointId: "small", + value: { type: "keyword", value: "purple" }, + }; + model.styles.set(getStyleDeclKey(innerStyle), innerStyle); + model.styles.set(getStyleDeclKey(outerStyle), outerStyle); + + expect( + getComputedStyleDecl({ + model, + instanceSelector: ["heading", "inner", "outer"], + property: "color", + }).usedValue + ).toEqual({ type: "keyword", value: "purple" }); + + model.styles.delete(getStyleDeclKey(outerStyle)); + outerStyle.breakpointId = "base"; + model.styles.set(getStyleDeclKey(outerStyle), outerStyle); + expect( + getComputedStyleDecl({ + model, + instanceSelector: ["heading", "inner", "outer"], + property: "color", + }).usedValue + ).toEqual({ type: "keyword", value: "red" }); + + model.styleSourceSelections = new Map( + [...model.styleSourceSelections].reverse() + ); + expect( + getComputedStyleDecl({ + model, + instanceSelector: ["heading", "inner", "outer"], + property: "color", + }).usedValue + ).toEqual({ type: "keyword", value: "purple" }); +}); + test("selected tag token remains the source when an instance overrides it", () => { const model = createModel({ css: "local { color: blue; }", diff --git a/apps/builder/app/shared/style-object-model.ts b/apps/builder/app/shared/style-object-model.ts index 5515c325ae..7f8441a53a 100644 --- a/apps/builder/app/shared/style-object-model.ts +++ b/apps/builder/app/shared/style-object-model.ts @@ -7,6 +7,7 @@ import { parseCssVar, propertiesData, isPseudoElement, + validateSelector, } from "@webstudio-is/css-data"; import { type StyleValue, @@ -86,6 +87,7 @@ export type StyleObjectModel = { * all currently matching and ordered breakpointsgg */ matchingStates: Set; + matchingStatesByInstanceId?: Map>; }; export const getPresetStyleDeclKey = ({ @@ -121,6 +123,7 @@ export const getPresetStyleDeclKey = ({ const getCascadedValue = ({ model, instanceId, + ancestorIds = [], styleSourceId: selectedStyleSourceId, state: selectedState, property, @@ -128,6 +131,7 @@ const getCascadedValue = ({ }: { model: StyleObjectModel; instanceId: Instance["id"]; + ancestorIds?: Instance["id"][]; styleSourceId?: StyleDecl["styleSourceId"]; state?: StyleDecl["state"]; property: CssProperty; @@ -141,8 +145,10 @@ const getCascadedValue = ({ instanceTags, instanceComponents, matchingBreakpoints, - matchingStates, } = model; + const matchingStates = model.matchingStatesByInstanceId + ? (model.matchingStatesByInstanceId.get(instanceId) ?? new Set()) + : model.matchingStates; const tag = instanceTags.get(instanceId); const component = instanceComponents.get(instanceId); let selectedIndex = -1; @@ -204,69 +210,132 @@ const getCascadedValue = ({ // user styles const styleSourceIds = styleSourceSelections.get(instanceId)?.values ?? []; const tagStyleId = tag ? tagStyleIds.get(tag) : undefined; + const nestedStyles = new Map(); + if (tag && ancestorIds.length > 0) { + for (const declaration of styles.values()) { + if ( + declaration.property !== camelCaseProperty(property) || + !declaration.state?.startsWith(" ") + ) { + continue; + } + const selector = validateSelector(declaration.state); + if ( + selector.success && + selector.type === "tag" && + selector.tag.toLowerCase() === tag + ) { + nestedStyles.set( + getStyleDeclKey({ + ...declaration, + state: ` ${tag}${selector.condition}`, + }), + declaration + ); + } + } + } selectedStyleSourceId ??= styleSourceIds.at(-1); + const addDeclaration = ({ + styleSourceId, + breakpointId, + state, + sourceInstanceId, + }: { + styleSourceId: string; + breakpointId: string; + state?: string; + sourceInstanceId: string; + }) => { + const key = getStyleDeclKey({ + styleSourceId, + breakpointId, + state, + property: camelCaseProperty(property), + }); + const styleDecl = nestedStyles.get(key) ?? styles.get(key); + const isSelected = + sourceInstanceId === instanceId && + styleSourceId === selectedStyleSourceId && + state === selectedState; + if (isSelected) { + selectedIndex = styleDecl ? declaredValues.length : -1; + } + if (!styleDecl) { + if (isSelected && styleSourceId === tagStyleId) { + selectedTagStyleSource = undefined; + } + return; + } + const declarationSource: StyleValueSource = { + name: "remote", + instanceId: sourceInstanceId, + styleSourceId, + state: styleDecl.state, + breakpointId, + }; + if (isSelected && styleSourceId === tagStyleId) { + selectedTagStyleSource = declarationSource; + } + source = declarationSource; + declaredValues.push(styleDecl.value); + }; // Within each state, resolve all Tag breakpoints before instance styles. // Instance selectors then win over Tag selectors across breakpoints. + const ancestorIdSet = new Set(ancestorIds); for (const state of states) { - if (tagStyleId) { + if (tag) { + const descendantState = ` ${tag}${state ?? ""}`; for (const breakpointId of matchingBreakpoints) { - const key = getStyleDeclKey({ - styleSourceId: tagStyleId, - breakpointId, - state, - property: camelCaseProperty(property), - }); - const styleDecl = styles.get(key); - if (tagStyleId === selectedStyleSourceId && state === selectedState) { - selectedIndex = styleDecl ? declaredValues.length : -1; - selectedTagStyleSource = styleDecl - ? { - name: "remote", - instanceId, - styleSourceId: tagStyleId, - state, - breakpointId, - } - : undefined; + // Global Tag CSS follows breakpoint and source order. Within one + // source, the nested rule is emitted before the tag's own rule. + for (const [sourceTag, styleSourceId] of tagStyleIds) { + const ancestorId = ancestorIds.find( + (id) => instanceTags.get(id) === sourceTag + ); + if (ancestorId) { + addDeclaration({ + styleSourceId, + breakpointId, + state: descendantState, + sourceInstanceId: ancestorId, + }); + } + if (sourceTag === tag) { + addDeclaration({ + styleSourceId, + breakpointId, + state, + sourceInstanceId: instanceId, + }); + } } - if (styleDecl) { - source = { - name: "remote", - instanceId, - styleSourceId: tagStyleId, - state, - breakpointId, - }; - declaredValues.push(styleDecl.value); + } + // Attached Token and Local descendant rules follow the global Tag sheet. + for (const breakpointId of matchingBreakpoints) { + for (const [ancestorId, selection] of styleSourceSelections) { + if (!ancestorIdSet.has(ancestorId)) { + continue; + } + for (const ancestorSourceId of selection.values) { + addDeclaration({ + styleSourceId: ancestorSourceId, + breakpointId, + state: descendantState, + sourceInstanceId: ancestorId, + }); + } } } } for (const breakpointId of matchingBreakpoints) { for (const styleSourceId of styleSourceIds) { - const key = getStyleDeclKey({ + addDeclaration({ styleSourceId, breakpointId, state, - property: camelCaseProperty(property), + sourceInstanceId: instanceId, }); - const styleDecl = styles.get(key); - if ( - styleSourceId === selectedStyleSourceId && - state === selectedState - ) { - // reset selection from another state or breakpoint - selectedIndex = styleDecl ? declaredValues.length : -1; - } - if (styleDecl) { - source = { - name: "remote", - instanceId, - styleSourceId, - state, - breakpointId, - }; - declaredValues.push(styleDecl.value); - } } } } @@ -458,6 +527,7 @@ export const getComputedStyleDecl = ({ const cascaded = getCascadedValue({ model, instanceId: targetInstanceId, + ancestorIds: instanceSelector.slice(1), styleSourceId, state, property, @@ -589,8 +659,9 @@ export const getComputedStyleDecl = ({ const cascaded = getCascadedValue({ model, instanceId, + ancestorIds: instanceSelector.slice(index + 1), styleSourceId, - state, + state: index === 0 ? state : undefined, property, }); const inheritedCascadedValue = cascadedValue; diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.ts index 9c5a8be7c8..e30ef1f4ff 100644 --- a/apps/builder/app/shared/sync/sync-stores.ts +++ b/apps/builder/app/shared/sync/sync-stores.ts @@ -15,6 +15,7 @@ import { $dataSourceVariables, $dragAndDropState, $selectedInstanceStates, + $selectedInstanceStatesByInstanceId, $canvasIframeState, $uploadingFilesDataStore, $memoryProps, @@ -373,6 +374,10 @@ export const createObjectPool = () => { new NanostoresSyncObject("dragAndDropState", $dragAndDropState), new NanostoresSyncObject("ephemeralStyles", $ephemeralStyles), new NanostoresSyncObject("selectedInstanceStates", $selectedInstanceStates), + new NanostoresSyncObject( + "selectedInstanceStatesByInstanceId", + $selectedInstanceStatesByInstanceId + ), new NanostoresSyncObject("canvasIframeState", $canvasIframeState), new NanostoresSyncObject( "uploadingFilesDataStore", diff --git a/docs/university/foundations/states-and-selectors.md b/docs/university/foundations/states-and-selectors.md index 7c87aa0fc9..f89db0f150 100644 --- a/docs/university/foundations/states-and-selectors.md +++ b/docs/university/foundations/states-and-selectors.md @@ -45,16 +45,14 @@ States are CSS pseudo-classes that apply styles when a condition is true, such a ### Custom states -You can type any valid CSS pseudo-class into the Style Sources dropdown. If it's not in the predefined list, Webstudio will accept it as a custom selector. +Use **Add more** in a Tag, Token, or Local style source to enter a selector that is not in the list. {% hint style="info" %} -Custom states can target descendants while staying scoped to the selected instance. For example, `:hover .button` targets descendants with the [custom class](custom-classes-and-attributes.md) `button` while the selected instance is hovered, and `:hover > .icon` targets only direct children with the custom class `icon`. +Start with `:` or `[` to target the current source's element or its pseudo-elements. For example, `:hover` applies while the element is hovered, `[data-state=open]` applies when its attribute matches, and `::before` targets its pseudo-element. You can combine conditions, such as `[data-state=open]:hover`. -You can also select a descendant tag in a Local source or Token. For example, `p` targets paragraphs inside that instance. A [Tag style](tag-styles.md) targets one tag across the site instead. +Start with an HTML tag name to style that tag nested inside the current source's element. For example, `h2`, `h2:hover`, `h2[a="123"]`, and `h2::before` target nested headings. Quote numeric attribute values as in `a="123"`. A [Tag style](tag-styles.md) applies its nested tag selector across the site; a Token or Local source applies it only where that source is used. -Prefer [CSS variables for parent-child interactions](css-variables.md#parent-child-interactions). They keep each property on the child that uses it, can coordinate several children from one parent state, and do not couple the interaction to descendant classes or structure. Use a descendant custom state when the interaction specifically requires selector-based targeting. - -Start a custom state with a pseudo-class, pseudo-element, or attribute selector for the selected instance. You can then use a descendant (` `) or child (`>`) combinator. A tag name on its own is treated as a descendant selector. Selector lists, class or ID selectors at the start, and sibling combinators (`+` and `~`) are rejected because they can target elements outside the selected instance. +**Add more** accepts one nested tag with optional conditions. It does not accept multiple top-level selectors, direct class or ID selectors such as `.card` or `h2.card`, a second nested element, or combinators such as `>`, `+`, and `~`. For parent-child interactions, [CSS variables](css-variables.md#parent-child-interactions) let the parent change a value used by the child. {% endhint %} ## Pseudo-elements diff --git a/docs/university/foundations/tag-styles.md b/docs/university/foundations/tag-styles.md index 407b12c164..340f66227f 100644 --- a/docs/university/foundations/tag-styles.md +++ b/docs/university/foundations/tag-styles.md @@ -10,7 +10,7 @@ description: Set site-wide styles for HTML tags such as div, h1, and button. 1. Select an instance on the canvas, such as a `div`. 2. Open the **Style sources** field at the top of the Style panel. -3. Select `div` under **Tag style**. Its source appears first in the field. +3. Select `div` under **Tag**. Its source appears first in the field. 4. Select that source and set a style. The Tag style is saved when you add its first style. @@ -29,7 +29,7 @@ Open the Tag style's menu and choose a state such as `:hover` or `:focus-visible div Tag style menu with Copy above hover and focus-visible states -A Tag style targets its tag and state across the site. To style a descendant within one element instead, use a [custom state or selector](states-and-selectors.md#custom-states) on a Token or Local source. +A Tag style targets its tag and state across the site. In **Add more**, `:hover`, `[data-state=open]`, and `::before` target the Tag style's own element. Enter an HTML tag to target a nested element on every matching instance: `h2`, `h2:hover`, `h2[a="123"]`, and `h2::before` are supported. The same [selector forms](states-and-selectors.md#custom-states) work in Token and Local sources, where they apply only to instances using that source. ## Copy and paste diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.ts index 62e9f71b63..2d015691fc 100644 --- a/packages/cli/src/docs.generated.ts +++ b/packages/cli/src/docs.generated.ts @@ -2,7 +2,7 @@ // 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 --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 \n- MCP tool: import {"to":""}\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 `. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\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 \'\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call \'\'`. 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 values and ids across every Builder namespace without sending full project data to the model.\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- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\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 {}\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- Enter this workflow only when the user explicitly requests visual verification or opts in after being asked. Do not start preview, screenshots, diffs, OCR, or rendered audits automatically after a mutation.\n- `preview.status` reports whether generated output is `stale`. When no preview is running, `url`, `pid`, and `mode` are omitted. When present, `renderedProjectVersion` is the last project version materialized into the preview.\n- MCP preview and path-based screenshot tools select an available loopback port and return the preview URL. Do not pass `host` or `port`.\n- A managed `screenshot` or another `preview.start` refreshes stale generated output before capture.\n\n- After opt-in, use this so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Calling `preview.start` after a committed mutation restarts a stale iterative server so external browsers and HTTP clients receive the newly generated project.\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- The screenshot timeout bounds browser capture after the preview is ready. A timeout returns `SCREENSHOT_TIMEOUT`, resets the reusable browser session, and releases the shared preview lifecycle for cleanup.\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- When launcher metadata is available, Preview reuses a supported npm or pnpm launcher. Without launcher metadata, it uses npm when available and otherwise falls back to pnpm.\n- Unless `npm_config_cache` is already configured, npm uses the writable `.webstudio/preview/.npm-cache` directory.\n- For npm cache permission errors, unset `npm_config_cache` to use the preview-local cache, then retry. No cache deletion is required.\n- If dependency installation fails, check the reported package-manager path 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":""}\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` and `path` are plain values. Page `title` and metadata text fields contain expression source; quote fixed text as a JavaScript string literal inside the JSON string.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`. An unquoted word is a variable reference.\n- CLI flags such as `--title` treat values as fixed text. Add `--expressions` to `webstudio create-page` when passing expression source through these flags; quote any fixed text in the same call as a JavaScript string expression.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\"","status":200}}}\n- MCP tool: update-page {"pageId":"","values":{"meta":{"auth":{"method":"basic","login":"","password":""}}}}\n\nNotes:\n\n- For fixed page `title` and metadata text, quote the text as a JavaScript string literal inside the JSON string.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`. An unquoted word is a variable reference.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n- For `webstudio update-page`, add `--expressions` when page title or metadata flags contain expression source. Without it, those flags are fixed text.\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":"hello@example.com","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## Submit marketplace product\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"marketplace-thumbnail.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"","author":"Acme Studio","email":"hello@example.com","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: publish {"target":"production"}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nNotes:\n\n- Wait for the production publish to complete before submitting the product for review.\n- Submission requires complete, valid marketplace metadata.\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":"","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\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\nCLI `create-page-template` and `update-page-template` use fixed text flags by default. Add `--expressions` when passing expression source through title or metadata flags.\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"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":""}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":""}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"","targetTemplateId":"","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"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":"","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"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":"","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"","fragment":"

Product OS

"}\n- MCP tool: insert-component {"parentInstanceId":"","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"","component":"ResourceForm"}\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- Use lowercase HTML JSX such as `
` and ``. The internal `ws:` namespace is not HTML-tag shorthand.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"ResourceForm"`.\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 ``.\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":"","component":"ws:block"}\n- MCP tool: inspect-instance {"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 exactly one direct `ws:block-template` child. A missing or second template container makes the Content Block invalid. 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 implementation, inventory every editor-owned field and its intended control and write destination, whether or not the block uses MDX. Check that templates contain the required styling, but do not treat containment or a successful text edit as proof that the whole block is editable. Test every field through Content mode, inspect its saved project data or source file, reload, and restore the original value. Report passed, failed, or not tested for each field; missing or read-only required controls are unfinished requirements.\n- Use controls that match the content: a calendar for dates and an image picker for image replacement. Keep fixed punctuation and units out of directly bound value elements. Preserve stored types and wording: when reading time is already a complete string such as `4 min read`, bind that string directly rather than assuming it is a number.\n- For MDX-backed blocks, containment alone is not enough: the MDX body is editable through its source mapping, but the designed shell needs writable document-frontmatter bindings. Follow the binding recipe below rather than binding editable article fields to query results.\n\n## Store Content Block content in MDX\n\nCommands:\n\n- MCP tool: list-assets {"type":"file"}\n- MCP tool: upload-asset {"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\n- MCP tool: connect-content-block-source {"blockInstanceId":"","renderScope":"page:/articles/example","source":{"type":"asset","assetId":""}}\n- MCP tool: switch-content-block-source {"blockInstanceId":"","renderScope":"page:/articles/example","source":{"type":"asset","assetId":""}}\n- MCP tool: inspect-content-block-source {"blockInstanceId":"","renderScope":"page:/articles/example"}\n- MCP tool: edit-content-block-source {"blockInstanceId":"","renderScope":"page:/articles/example","source":"# Article title\\n\\nArticle body."}\n- MCP tool: update-content-block-frontmatter {"blockInstanceId":"","renderScope":"page:/articles/example","properties":{"title":"Article title","draft":false}}\n- MCP tool: reload-content-block-source {"blockInstanceId":"","renderScope":"page:/articles/example"}\n- MCP tool: migrate-content-block-template-references {"assetIds":[""],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\n- MCP tool: disconnect-content-block-source {"blockInstanceId":"","renderScope":"page:/articles/example"}\n\nNotes:\n\n- Create the local `.mdx` file under `.webstudio/assets` before calling `upload-asset`. Use the returned Asset ID when connecting it.\n- Use the Content Block source operations for connecting, switching, inspecting, editing, reloading, and disconnecting. Do not create or delete the `src` prop with generic prop tools; the source operations preserve the Body outlet and Content Block lifecycle.\n- `renderScope` accepts any non-empty stable key for one rendered occurrence. Use a page-based key for a direct Content Block and a distinct key for each repeated Collection occurrence. It does not load a page, route parameters, or resource results. Supply the concrete scoped values needed to resolve an expression through `variables`.\n- For a result-one Assets resource, preview the concrete query, then connect its persisted expression with the previewed item supplied as `variables`, for example `source:{"type":"expression","value":"post.data.id"}` and `variables:{"post":{"data":{"id":""}}}`.\n- Connecting replaces existing Body content. If the result returns `requiresConfirmation:true`, report that replacement to the user and repeat the same call with `confirmReplacement:true` only after approval.\n- Prefer Markdown for standard document content; it automatically uses a unique matching semantic template when one exists. Use lowercase JSX such as `
` or `` for HTML or SVG with authored properties that Markdown cannot express.\n- Verify that the Content Block has exactly one direct Templates container before connecting or editing MDX. Zero or multiple containers block materialization and publication.\n- Read the Content Block\'s Templates children before writing a custom reference. Use capitalized JSX such as `` for its stable **Name**, which is independent from the display label. A matching template wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block\'s Templates. JSX attributes accept quoted static values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported.\n- When explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants and retain template styles. A mismatched child structure replaces the root defaults, while each authored child still resolves through a matching template when possible. An explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, so adding a matching semantic or named template later updates existing MDX. Preserve unresolved names and report their diagnostics instead of deleting them.\n- When a template is renamed or deleted, use `migrate-content-block-template-references` to update a selected set of affected MDX files. The first call returns a plan. Report its changed-file, update, omission, and diagnostic counts, then repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its authored children; removing a self-closing reference removes the node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n- `edit-content-block-source` replaces the complete MDX source. Preserve frontmatter and unrelated source when making a bounded edit.\n- `update-content-block-frontmatter` replaces the complete frontmatter mapping. Inspect the current source first and include every property that must remain.\n- Store frontmatter images as exact `$ref` objects. Bind an editable Image source to the resolved `.src` with explicit `binding.mode:"readwrite"`; use `mode:"read"` for its alt binding to `.description`. Omitting the source mode leaves the image visible but not replaceable in Content mode.\n- Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.\n- Inspect every returned diagnostic. Invalid MDX is saved rather than silently repaired; preserve the source, report the source range, and fix only the requested or invalid part.\n- If an edit in a long-lived MCP session reports a conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly.\n\n## Make an MDX article header editable\n\nUse the resource only to select the connected source, for example `post.data.id`.\nBind article values inside the Content Block to its document parameter instead\nof `post.data.properties.*`. Inspect the block\'s variables first; `document` is\nthe default name, not a name to assume.\n\nThese commands target persistent designed instances inside the connected block.\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"","childIndex":0,"text":"document.frontmatter.title","mode":"expression","expressionBindingMode":"readwrite"}\n- MCP tool: update-text {"instanceId":"","childIndex":0,"text":"document.frontmatter.readingTime","mode":"expression","expressionBindingMode":"readwrite"}\n- MCP tool: bind-props {"bindings":[{"instanceId":"","name":"datetime","binding":{"type":"expression","value":"document.frontmatter.publishedAt","mode":"readwrite"}}]}\n\nNotes:\n\n- Create writable bindings explicitly; the default is read-only. Merely moving a heading or Link inside the Content Block does not make its query-bound text editable.\n- The MDX body uses its source mapping. Static designed content outside that body remains protected unless its text or supported props bind to writable frontmatter fields. Do not apply these generic instance tools to MDX-generated instances.\n- Use direct static paths. Property access is already safe. Fallbacks and formatted expressions, such as `document.frontmatter.title ?? "Untitled"`, remain read-only.\n- Keep every intended editable value in its own text element with a single direct read-write binding. For reading time, use three inline siblings: static `— `, the bound reading-time value, and static ` min read`. Preserve whitespace and the stored field type. Do not combine them into a template literal or concatenate strings, and do not put literal siblings inside the value element itself. Keep fixed wording protected in the designed shell.\n- Prefer component formatting controls, such as Date Time formatting with a directly bound date prop, over transforming the expression. Do not silently sacrifice editability for formatting or a fallback; explain unsupported cases and ask before making an intended editable field read-only.\n- A direct writable binding such as `document.frontmatter.author.name` can edit a shared author loaded through `../authors/acme.md#frontmatter`. The edit saves to the author file and affects every article using it; preserve the article\'s `$ref` marker.\n- Before handoff, inventory every article-owned field, including header text, author details, dates, reading time, categories, hero and inline image sources, alternative text, captions, links, and custom-component content. For each field, inspect its binding and source, edit it through the Content-mode UI, verify the saved MDX or referenced file, reload, and restore the test value. Record passed, failed, or not tested for each field. A correct preview, a successful MCP write, and one representative text edit do not prove the whole article is editable. Do not claim completion while required fields fail or remain untested.\n- Bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. Content mode\'s **Choose source** replaces the article\'s frontmatter image `$ref`; the resolved URL stays read-only. Verify selection, the saved reference, and reload instead of treating a missing write mode as a platform limitation. For alternative text bound to `.description`, use **Choose source → asset actions → Settings → Description** to edit shared Asset metadata. This affects every use of the Asset and is separate from replacing an article\'s image.\n\n## Make an article image replaceable in Content mode\n\nUse this for a persistent designed Image inside a connected Content Block,\nwith `featureImage: { $ref: "./images/hero.png" }` in its MDX frontmatter.\nRead the instance ID and document variable name before adapting the example.\n\nCommands:\n\n- MCP tool: bind-props {"bindings":[{"instanceId":"","name":"src","binding":{"type":"expression","value":"document.frontmatter.featureImage.src","mode":"readwrite"}},{"instanceId":"","name":"alt","binding":{"type":"expression","value":"document.frontmatter.featureImage.description","mode":"read"}}]}\n\nNotes:\n\n- The source mode must be explicit: the default `read` mode displays the image but prevents Content-mode replacement. Do not bind to query-result properties or add a fallback expression.\n- **Choose source** replaces the article\'s `featureImage.$ref`; the disabled resolved-URL input is expected. Do not store a resolved URL string or replace the shared Asset itself.\n- Shared alternative text is a separate action: **Choose source → asset actions → Settings → Description**. Its read-only binding does not require the image source binding to be read-only.\n- If the picker is missing or disabled, inspect the source mode, document scope, loaded reference, and permissions before claiming a product limitation.\n- Verify through Content mode with an approved temporary replacement. Check the saved `$ref`, unchanged unrelated MDX and original shared Asset, reload persistence, and restoration. If that test is not authorized, report it as not tested, not passed.\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":"","targetParentInstanceId":""}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":[""]}\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":"","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":"","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: bind-props {"bindings":[{"instanceId":"","name":"code","binding":{"type":"expression","value":"({ \'@context\': \'https://schema.org\', \'@type\': \'Article\', headline: post.title })"}}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- For fixed structured data, store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- For structured data containing runtime values, use `bind-props` with an expression that evaluates directly to an object or array. Do not call `JSON.stringify` or assemble JSON with string concatenation. Webstudio stores the expression as source text, evaluates it at runtime, and the `JsonLd` component validates and serializes the resulting value.\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":[""],"includeTokens":true}\n\n## Read global Tag styles\n\nCommands:\n\n- MCP tool: list-tag-styles {}\n- MCP tool: list-tag-styles {"tag":"button","verbose":true}\n\nNotes:\n\n- Tag styles apply across the project without being attached to an instance. Use `list-tag-styles` to read them; `get-styles` lists attached sources.\n- `list-design-tokens` does not include Tag styles.\n\n## Update a global Tag style\n\nCommands:\n\n- MCP tool: update-selected-styles {"updates":[{"instanceId":"","styleSourceId":"tag-style:button","property":"color","value":{"type":"keyword","value":"red"}}]}\n\nNotes:\n\n- Use `tag-style:` to create or edit a Tag style. The first update creates its style source; no instance attachment is saved.\n- Use `delete-selected-styles` with the same `instanceId`, `styleSourceId`, and `property` to remove a declaration.\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":"","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":[""],"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":{"--color-primary":"#2d3748","--color-accent":"#e53e3e","--space-card":"1.5rem"},"overwrite":true}\n\nNotes:\n\n- Define or overwrite multiple CSS variables atomically by including every name and value in one `vars` object.\n- Pass colors as CSS strings. Structured `hex` color components use normalized values from `0` to `1`, not `0` to `255`.\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":["--color-primary","--color-accent","--space-card"],"force":true}\n\nNotes:\n\n- Delete multiple CSS variables atomically by including every name in one `names` array. Destructive MCP calls still require the returned confirmation token before they commit.\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":""}\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":"","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays and objects.\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":"","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":""}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":""}\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":"","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":"","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":"","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"","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`. A query key with one value is a string; repeated values are an ordered array. For `?tag=red&tag=blue`, `system.search.tag` is `["red", "blue"]`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"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## Configure Form (Beta) through MCP\n\nUse the exact component id returned by `components.search` for **Form (Beta)**.\nAfter inserting its registered template, use the Form instance id for the\nForm-scoped Resource and Action settings.\n\nThe new Form\'s canonical component id is `ResourceForm`. The deprecated\nWebhook Form remains available in Builder for existing projects until the next\nrelease, but is omitted from MCP component discovery. `RemixForm` is deprecated\ncompatibility and should not be used for new projects. Always use registry\ndiscovery instead of assuming the display label is its component id.\n\nThe new Form has two modes derived from its Action array:\n\n- One or more connected Resources: the rendered action is\n `?__webstudio__=resources` and submission runs the Resource actions.\n- No connected Resources (`action: []`): the rendered action is\n `?__webstudio__=navigate` and submission updates URL query parameters through\n client-side navigation. Use this for search and filters with page Resources\n bound to `system.search`. Removing the last Action switches to Navigation mode.\n- For ordinary browser submission, insert an `Element` with `tag: "form"`.\n It has no managed action marker and retains native browser behavior.\n\nDo not write the `__webstudio__` marker as a project Action value: that prop holds\nResource selections, and the runtime derives the HTML action URL from it.\nVerify both modes through MCP in a real project: add Resource actions, remove\nall actions for a search/filter form, then reconnect them. Check the rendered\naction, query navigation without a full reload, and Resource execution. Also\nverify a plain form Element remains native. A saved project snapshot alone does\nnot prove these runtime behaviors.\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"","component":""}\n- MCP tool: create-resource {"resource":{"name":"Send submission","method":"post","url":"https://api.example.com/submit","headers":[],"body":"formData"},"scopeInstanceId":"","dataSourceName":"Send submission","exposeAsDataSource":true}\n- MCP tool: update-props {"updates":[{"instanceId":"","name":"action","type":"json","value":[{"dataSourceId":""}]}]}\n- MCP tool: update-resource {"resourceId":"","values":{"email":{"recipientMode":"visitor","visitorEmailField":"email","includeAttachments":true}}}\n- MCP tool: update-project-settings {"meta":{"emailSender":"Acme "}}\n\nNotes:\n\n- Use `update-props` with a JSON Action array to add, order, or remove destinations. The Action entries use `{ "dataSourceId": "..." }` and support up to ten Resources, matching the Builder control. Each connected Action runs in its configured order. An extra `enabled` key in older saved settings is ignored.\n- Create each destination Resource in the Form\'s scope so it can use `formData` and `browserInfo`. Set `exposeAsDataSource:true` to receive the data-source id used by the Action array. When a Resource uses Form-only parameters, it is kept out of page-load requests and runs with the Form submission.\n- `update-resource` accepts the same Email settings as the Builder: project, custom, or visitor recipients; sender; subject; body; and submitted-file attachments. Use expressions in string fields for dynamic values.\n- `update-project-settings` edits the project-wide Email recipients and Reply to. `update-props` also sets Form fields and Success redirect, while `bind-props` supplies dynamic expressions. `insert-component` uses the registered Form template, including its default contact fields and Email Actions. Set subject and body on each Email Resource.\n- MCP mutations update saved project configuration. To test real delivery, submit the Form in Preview or on a published test site and inspect the configured destinations.\n\n## Query Markdown assets\n\nCommands:\n\n- MCP tool: get-asset-field-catalog {}\n- MCP tool: validate-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","draft"],"operator":"ne","value":true}]},"limit":20}}\n- MCP tool: create-assets-resource {"name":"All assets","scopeInstanceId":"","dataSourceName":"assets"}\n- MCP tool: create-assets-resource {"name":"Published posts","scopeInstanceId":"","dataSourceName":"posts","query":{"result":"many","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"}],"limit":{"type":"literal","value":20},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["properties","excerpt"]]},"content":{"mode":"none"}}}\n- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"","dataSourceName":"post","query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body-ref"}}}\n- MCP tool: list-assets-resources {}\n- MCP tool: get-assets-resource {"resourceId":""}\n- MCP tool: update-assets-resource {"resourceId":"","values":{"query":null}}\n- MCP tool: preview-asset-query {"query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"]]},"content":{"mode":"markdown-body-ref"}}}\n\nNotes:\n\n- Choose `.mdx` connected to a Content Block when editors must edit article bodies visually in Content mode. Publishing downloads and compiles every reachable MDX article, so more articles can slow publishing. Choose `.md` with Markdown Embed when editing the source in Assets is enough; Content mode editors can still edit the Markdown file there, but not its body on the canvas. `.md` needs no per-article MDX compilation, though the publish runner still synchronizes Asset files for both formats and static generation may read Markdown bodies.\n- Read the field catalog before authoring unfamiliar queries. It includes dynamic schema-less frontmatter paths such as `properties.author.name`, observed types, optionality, and mixed-type state without downloading the source files.\n- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.\n- Every reachable Assets data source contributes to the shared published database. Keep one final resource per rendered query. Update an existing scoped resource rather than creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicates.\n- Keep bounded overview filters, limits, and offsets literal and add a deterministic ID tie-breaker to the sort. With `content.mode:"none"`, compilation can materialize the small overview result instead of retaining its output fields across every candidate document. Use runtime expressions only for genuinely dynamic values such as the detail slug.\n- Combine filters with `where.all` (AND) and `where.any` (OR), including nested groups. Filter values, limit, and offset on a saved resource may be Webstudio expressions evaluated at render time. Preview queries use concrete JSON values.\n- Query Markdown or MDX files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database retains metadata and a document reference, then fetches only the selected files from Asset storage at runtime; it does not embed their bodies. Filter and paginate before content is loaded.\n- `full` and bounded `range` continue to request embedded file bytes. Use them only when the caller requires the complete source or a byte range.\n- In Markdown or MDX, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. Deferred `markdown-body-ref` content resolves matching files against the document\'s folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.\n- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. It does not render Webstudio MDX elements; connect the `.mdx` file to a Content Block for that workflow.\n- Preview each query with concrete values before saving it. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes must not be summed and are not separate allowances. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A completed Markdown blog should include every source document without truncation, contain no embedded Markdown bodies, and retain only its intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files.\n- Use `result:"many"` for listings. It returns the ID-keyed map at `.data`, with `totalCount` and `hasMore` at `.meta`, and remains the default for existing queries. Bind a listing Collection to `posts.data`.\n- Use `result:"one"` for a unique detail route. It returns the selected item or `null` directly at `post.data`, always includes its `id`, and omits pagination. Bind components and page settings directly with expressions such as `post.data.properties.title`, `post.data.content.text`, and `post.data ? 200 : 404`. `result:"first"` and `result:"last"` also return a direct item or `null` but require explicit sorting.\n- Assets always executes a structured query. Omit `query` to use the default many-result query, which selects URL and optional image dimensions. Set `values.query:null` to restore it.\n- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.\n- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":""}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\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## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":""}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":""}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"","values":{"parentId":""}}\n- MCP tool: update-asset-folder {"folderId":"","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":""}\n- MCP tool: duplicate-asset-folder {"folderId":"","parentId":""}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":""}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\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- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\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- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"","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\nNotes:\n\n- Multi-file uploads return `uploaded`, `failed`, and `ambiguous` lists with the\n original input index. Retry only `failed` files. A forced upload in\n `ambiguous` may already be committed; inspect the Assets list before deciding\n whether to upload it again. Successful uploads remain committed.\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":""}\n- MCP tool: duplicate-asset {"assetId":"","folderId":""}\n- MCP tool: duplicate-asset {"assetId":"","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":""}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":""}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"","toAssetId":""}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":[""],"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 --json\n\n## Unpublish\n\nUnpublish completes without a publish job.\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 --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":[""]}\n- MCP tool: apply-patch {"baseVersion":"","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":"hello@example.com","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- webstudio search-project \'{"query":"pricing"}\'\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","namespaces":["resources"]}\n- MCP tool: search-project {"query":"Brand","namespaces":["styles","styleSources","styleSourceSelections"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"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":""}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- `search-project` is a standalone local-session command over every Builder namespace. It returns matching values with stable match ids, namespace paths, owning entities, references, and affected pages.\n- Use it when a value or id is known. Use list/get tools when the project structure or target is not known.\n- The command synchronizes its required Builder namespaces, then searches locally and returns only matches. Namespace filters limit values matched; related namespaces may still supply route and reference context, and synchronization is unchanged. This reduces data passed to the model, not the initial project-data synchronization.\n- Asset records and file metadata are searchable. Asset binary or document contents are not Builder namespace data and are not searched.\n- Values in recognized credential fields are excluded and counted in `excludedSensitiveValueCount`.\n- 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 =`\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":"","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":"","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":"","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\""}}}\n- MCP tool: update-resource {"resourceId":"","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"","toAssetId":""}\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":"","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":[""],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"","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":"","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"","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":"","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":"","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"","fragment":"{/_ collection content _/}"}\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":"","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"

{expression`collectionItem.title`}

"}\n- MCP tool: inspect-instance {"instanceId":"","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":"","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":"","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":"","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","taskScope":"structural-project-change","workflow":"authenticated-page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"","values":{"meta":{"auth":{"method":"basic","login":"","password":""}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"","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","taskScope":"visual-change","workflow":"design-input"}\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":"","fragment":"

Section copy

"}\n- MCP tool: update-styles {"updates":[{"instanceId":"","breakpoint":"","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {}\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- Ask whether the user wants visual verification unless they explicitly requested\n it. If they decline, stop after focused reads and a static audit. If they opt\n in, verify one familiar viewport inside every distinct Builder breakpoint\n range, 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 `workflow:"authenticated-page"`, 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 `workflow:"design-input"`, 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', + '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --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 \n- MCP tool: import {"to":""}\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 `. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\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 \'\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call \'\'`. 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 values and ids across every Builder namespace without sending full project data to the model.\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- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\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 {}\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- Enter this workflow only when the user explicitly requests visual verification or opts in after being asked. Do not start preview, screenshots, diffs, OCR, or rendered audits automatically after a mutation.\n- `preview.status` reports whether generated output is `stale`. When no preview is running, `url`, `pid`, and `mode` are omitted. When present, `renderedProjectVersion` is the last project version materialized into the preview.\n- MCP preview and path-based screenshot tools select an available loopback port and return the preview URL. Do not pass `host` or `port`.\n- A managed `screenshot` or another `preview.start` refreshes stale generated output before capture.\n\n- After opt-in, use this so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Calling `preview.start` after a committed mutation restarts a stale iterative server so external browsers and HTTP clients receive the newly generated project.\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- The screenshot timeout bounds browser capture after the preview is ready. A timeout returns `SCREENSHOT_TIMEOUT`, resets the reusable browser session, and releases the shared preview lifecycle for cleanup.\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- When launcher metadata is available, Preview reuses a supported npm or pnpm launcher. Without launcher metadata, it uses npm when available and otherwise falls back to pnpm.\n- Unless `npm_config_cache` is already configured, npm uses the writable `.webstudio/preview/.npm-cache` directory.\n- For npm cache permission errors, unset `npm_config_cache` to use the preview-local cache, then retry. No cache deletion is required.\n- If dependency installation fails, check the reported package-manager path 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":""}\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` and `path` are plain values. Page `title` and metadata text fields contain expression source; quote fixed text as a JavaScript string literal inside the JSON string.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`. An unquoted word is a variable reference.\n- CLI flags such as `--title` treat values as fixed text. Add `--expressions` to `webstudio create-page` when passing expression source through these flags; quote any fixed text in the same call as a JavaScript string expression.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\"","status":200}}}\n- MCP tool: update-page {"pageId":"","values":{"meta":{"auth":{"method":"basic","login":"","password":""}}}}\n\nNotes:\n\n- For fixed page `title` and metadata text, quote the text as a JavaScript string literal inside the JSON string.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`. An unquoted word is a variable reference.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n- For `webstudio update-page`, add `--expressions` when page title or metadata flags contain expression source. Without it, those flags are fixed text.\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":"hello@example.com","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## Submit marketplace product\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"marketplace-thumbnail.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"","author":"Acme Studio","email":"hello@example.com","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: publish {"target":"production"}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nNotes:\n\n- Wait for the production publish to complete before submitting the product for review.\n- Submission requires complete, valid marketplace metadata.\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":"","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\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\nCLI `create-page-template` and `update-page-template` use fixed text flags by default. Add `--expressions` when passing expression source through title or metadata flags.\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"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":""}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":""}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"","targetTemplateId":"","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"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":"","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"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":"","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"","fragment":"

Product OS

"}\n- MCP tool: insert-component {"parentInstanceId":"","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"","component":"ResourceForm"}\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- Use lowercase HTML JSX such as `
` and ``. The internal `ws:` namespace is not HTML-tag shorthand.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"ResourceForm"`.\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 ``.\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":"","component":"ws:block"}\n- MCP tool: inspect-instance {"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 exactly one direct `ws:block-template` child. A missing or second template container makes the Content Block invalid. 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 implementation, inventory every editor-owned field and its intended control and write destination, whether or not the block uses MDX. Check that templates contain the required styling, but do not treat containment or a successful text edit as proof that the whole block is editable. Test every field through Content mode, inspect its saved project data or source file, reload, and restore the original value. Report passed, failed, or not tested for each field; missing or read-only required controls are unfinished requirements.\n- Use controls that match the content: a calendar for dates and an image picker for image replacement. Keep fixed punctuation and units out of directly bound value elements. Preserve stored types and wording: when reading time is already a complete string such as `4 min read`, bind that string directly rather than assuming it is a number.\n- For MDX-backed blocks, containment alone is not enough: the MDX body is editable through its source mapping, but the designed shell needs writable document-frontmatter bindings. Follow the binding recipe below rather than binding editable article fields to query results.\n\n## Store Content Block content in MDX\n\nCommands:\n\n- MCP tool: list-assets {"type":"file"}\n- MCP tool: upload-asset {"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\n- MCP tool: connect-content-block-source {"blockInstanceId":"","renderScope":"page:/articles/example","source":{"type":"asset","assetId":""}}\n- MCP tool: switch-content-block-source {"blockInstanceId":"","renderScope":"page:/articles/example","source":{"type":"asset","assetId":""}}\n- MCP tool: inspect-content-block-source {"blockInstanceId":"","renderScope":"page:/articles/example"}\n- MCP tool: edit-content-block-source {"blockInstanceId":"","renderScope":"page:/articles/example","source":"# Article title\\n\\nArticle body."}\n- MCP tool: update-content-block-frontmatter {"blockInstanceId":"","renderScope":"page:/articles/example","properties":{"title":"Article title","draft":false}}\n- MCP tool: reload-content-block-source {"blockInstanceId":"","renderScope":"page:/articles/example"}\n- MCP tool: migrate-content-block-template-references {"assetIds":[""],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\n- MCP tool: disconnect-content-block-source {"blockInstanceId":"","renderScope":"page:/articles/example"}\n\nNotes:\n\n- Create the local `.mdx` file under `.webstudio/assets` before calling `upload-asset`. Use the returned Asset ID when connecting it.\n- Use the Content Block source operations for connecting, switching, inspecting, editing, reloading, and disconnecting. Do not create or delete the `src` prop with generic prop tools; the source operations preserve the Body outlet and Content Block lifecycle.\n- `renderScope` accepts any non-empty stable key for one rendered occurrence. Use a page-based key for a direct Content Block and a distinct key for each repeated Collection occurrence. It does not load a page, route parameters, or resource results. Supply the concrete scoped values needed to resolve an expression through `variables`.\n- For a result-one Assets resource, preview the concrete query, then connect its persisted expression with the previewed item supplied as `variables`, for example `source:{"type":"expression","value":"post.data.id"}` and `variables:{"post":{"data":{"id":""}}}`.\n- Connecting replaces existing Body content. If the result returns `requiresConfirmation:true`, report that replacement to the user and repeat the same call with `confirmReplacement:true` only after approval.\n- Prefer Markdown for standard document content; it automatically uses a unique matching semantic template when one exists. Use lowercase JSX such as `
` or `` for HTML or SVG with authored properties that Markdown cannot express.\n- Verify that the Content Block has exactly one direct Templates container before connecting or editing MDX. Zero or multiple containers block materialization and publication.\n- Read the Content Block\'s Templates children before writing a custom reference. Use capitalized JSX such as `` for its stable **Name**, which is independent from the display label. A matching template wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block\'s Templates. JSX attributes accept quoted static values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported.\n- When explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants and retain template styles. A mismatched child structure replaces the root defaults, while each authored child still resolves through a matching template when possible. An explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, so adding a matching semantic or named template later updates existing MDX. Preserve unresolved names and report their diagnostics instead of deleting them.\n- When a template is renamed or deleted, use `migrate-content-block-template-references` to update a selected set of affected MDX files. The first call returns a plan. Report its changed-file, update, omission, and diagnostic counts, then repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its authored children; removing a self-closing reference removes the node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n- `edit-content-block-source` replaces the complete MDX source. Preserve frontmatter and unrelated source when making a bounded edit.\n- `update-content-block-frontmatter` replaces the complete frontmatter mapping. Inspect the current source first and include every property that must remain.\n- Store frontmatter images as exact `$ref` objects. Bind an editable Image source to the resolved `.src` with explicit `binding.mode:"readwrite"`; use `mode:"read"` for its alt binding to `.description`. Omitting the source mode leaves the image visible but not replaceable in Content mode.\n- Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.\n- Inspect every returned diagnostic. Invalid MDX is saved rather than silently repaired; preserve the source, report the source range, and fix only the requested or invalid part.\n- If an edit in a long-lived MCP session reports a conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly.\n\n## Make an MDX article header editable\n\nUse the resource only to select the connected source, for example `post.data.id`.\nBind article values inside the Content Block to its document parameter instead\nof `post.data.properties.*`. Inspect the block\'s variables first; `document` is\nthe default name, not a name to assume.\n\nThese commands target persistent designed instances inside the connected block.\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"","childIndex":0,"text":"document.frontmatter.title","mode":"expression","expressionBindingMode":"readwrite"}\n- MCP tool: update-text {"instanceId":"","childIndex":0,"text":"document.frontmatter.readingTime","mode":"expression","expressionBindingMode":"readwrite"}\n- MCP tool: bind-props {"bindings":[{"instanceId":"","name":"datetime","binding":{"type":"expression","value":"document.frontmatter.publishedAt","mode":"readwrite"}}]}\n\nNotes:\n\n- Create writable bindings explicitly; the default is read-only. Merely moving a heading or Link inside the Content Block does not make its query-bound text editable.\n- The MDX body uses its source mapping. Static designed content outside that body remains protected unless its text or supported props bind to writable frontmatter fields. Do not apply these generic instance tools to MDX-generated instances.\n- Use direct static paths. Property access is already safe. Fallbacks and formatted expressions, such as `document.frontmatter.title ?? "Untitled"`, remain read-only.\n- Keep every intended editable value in its own text element with a single direct read-write binding. For reading time, use three inline siblings: static `— `, the bound reading-time value, and static ` min read`. Preserve whitespace and the stored field type. Do not combine them into a template literal or concatenate strings, and do not put literal siblings inside the value element itself. Keep fixed wording protected in the designed shell.\n- Prefer component formatting controls, such as Date Time formatting with a directly bound date prop, over transforming the expression. Do not silently sacrifice editability for formatting or a fallback; explain unsupported cases and ask before making an intended editable field read-only.\n- A direct writable binding such as `document.frontmatter.author.name` can edit a shared author loaded through `../authors/acme.md#frontmatter`. The edit saves to the author file and affects every article using it; preserve the article\'s `$ref` marker.\n- Before handoff, inventory every article-owned field, including header text, author details, dates, reading time, categories, hero and inline image sources, alternative text, captions, links, and custom-component content. For each field, inspect its binding and source, edit it through the Content-mode UI, verify the saved MDX or referenced file, reload, and restore the test value. Record passed, failed, or not tested for each field. A correct preview, a successful MCP write, and one representative text edit do not prove the whole article is editable. Do not claim completion while required fields fail or remain untested.\n- Bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. Content mode\'s **Choose source** replaces the article\'s frontmatter image `$ref`; the resolved URL stays read-only. Verify selection, the saved reference, and reload instead of treating a missing write mode as a platform limitation. For alternative text bound to `.description`, use **Choose source → asset actions → Settings → Description** to edit shared Asset metadata. This affects every use of the Asset and is separate from replacing an article\'s image.\n\n## Make an article image replaceable in Content mode\n\nUse this for a persistent designed Image inside a connected Content Block,\nwith `featureImage: { $ref: "./images/hero.png" }` in its MDX frontmatter.\nRead the instance ID and document variable name before adapting the example.\n\nCommands:\n\n- MCP tool: bind-props {"bindings":[{"instanceId":"","name":"src","binding":{"type":"expression","value":"document.frontmatter.featureImage.src","mode":"readwrite"}},{"instanceId":"","name":"alt","binding":{"type":"expression","value":"document.frontmatter.featureImage.description","mode":"read"}}]}\n\nNotes:\n\n- The source mode must be explicit: the default `read` mode displays the image but prevents Content-mode replacement. Do not bind to query-result properties or add a fallback expression.\n- **Choose source** replaces the article\'s `featureImage.$ref`; the disabled resolved-URL input is expected. Do not store a resolved URL string or replace the shared Asset itself.\n- Shared alternative text is a separate action: **Choose source → asset actions → Settings → Description**. Its read-only binding does not require the image source binding to be read-only.\n- If the picker is missing or disabled, inspect the source mode, document scope, loaded reference, and permissions before claiming a product limitation.\n- Verify through Content mode with an approved temporary replacement. Check the saved `$ref`, unchanged unrelated MDX and original shared Asset, reload persistence, and restoration. If that test is not authorized, report it as not tested, not passed.\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":"","targetParentInstanceId":""}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":[""]}\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":"","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":"","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: bind-props {"bindings":[{"instanceId":"","name":"code","binding":{"type":"expression","value":"({ \'@context\': \'https://schema.org\', \'@type\': \'Article\', headline: post.title })"}}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- For fixed structured data, store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- For structured data containing runtime values, use `bind-props` with an expression that evaluates directly to an object or array. Do not call `JSON.stringify` or assemble JSON with string concatenation. Webstudio stores the expression as source text, evaluates it at runtime, and the `JsonLd` component validates and serializes the resulting value.\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":[""],"includeTokens":true}\n\n## Read global Tag styles\n\nCommands:\n\n- MCP tool: list-tag-styles {}\n- MCP tool: list-tag-styles {"tag":"button","verbose":true}\n\nNotes:\n\n- Tag styles apply across the project without being attached to an instance. Use `list-tag-styles` to read them; `get-styles` lists attached sources.\n- `list-design-tokens` does not include Tag styles.\n\n## Update a global Tag style\n\nCommands:\n\n- MCP tool: update-selected-styles {"updates":[{"instanceId":"","styleSourceId":"tag-style:button","property":"color","value":{"type":"keyword","value":"red"}}]}\n- MCP tool: update-selected-styles {"updates":[{"instanceId":"","styleSourceId":"tag-style:div","state":" h2:hover","property":"color","value":{"type":"keyword","value":"red"}}]}\n\nNotes:\n\n- Use `tag-style:` to create or edit a Tag style. The first update creates its style source; no instance attachment is saved.\n- For a nested tag, set `state` to a space followed by the tag and optional condition, such as ` h2:hover`. The same selector forms work in Tag, Token, and Local styles.\n- Use `delete-selected-styles` with the same `instanceId`, `styleSourceId`, and `property` to remove a declaration.\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":"","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":[""],"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":{"--color-primary":"#2d3748","--color-accent":"#e53e3e","--space-card":"1.5rem"},"overwrite":true}\n\nNotes:\n\n- Define or overwrite multiple CSS variables atomically by including every name and value in one `vars` object.\n- Pass colors as CSS strings. Structured `hex` color components use normalized values from `0` to `1`, not `0` to `255`.\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":["--color-primary","--color-accent","--space-card"],"force":true}\n\nNotes:\n\n- Delete multiple CSS variables atomically by including every name in one `names` array. Destructive MCP calls still require the returned confirmation token before they commit.\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":""}\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":"","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays and objects.\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":"","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":""}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":""}\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":"","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":"","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":"","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"","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`. A query key with one value is a string; repeated values are an ordered array. For `?tag=red&tag=blue`, `system.search.tag` is `["red", "blue"]`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"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## Configure Form (Beta) through MCP\n\nUse the exact component id returned by `components.search` for **Form (Beta)**.\nAfter inserting its registered template, use the Form instance id for the\nForm-scoped Resource and Action settings.\n\nThe new Form\'s canonical component id is `ResourceForm`. The deprecated\nWebhook Form remains available in Builder for existing projects until the next\nrelease, but is omitted from MCP component discovery. `RemixForm` is deprecated\ncompatibility and should not be used for new projects. Always use registry\ndiscovery instead of assuming the display label is its component id.\n\nThe new Form has two modes derived from its Action array:\n\n- One or more connected Resources: the rendered action is\n `?__webstudio__=resources` and submission runs the Resource actions.\n- No connected Resources (`action: []`): the rendered action is\n `?__webstudio__=navigate` and submission updates URL query parameters through\n client-side navigation. Use this for search and filters with page Resources\n bound to `system.search`. Removing the last Action switches to Navigation mode.\n- For ordinary browser submission, insert an `Element` with `tag: "form"`.\n It has no managed action marker and retains native browser behavior.\n\nDo not write the `__webstudio__` marker as a project Action value: that prop holds\nResource selections, and the runtime derives the HTML action URL from it.\nVerify both modes through MCP in a real project: add Resource actions, remove\nall actions for a search/filter form, then reconnect them. Check the rendered\naction, query navigation without a full reload, and Resource execution. Also\nverify a plain form Element remains native. A saved project snapshot alone does\nnot prove these runtime behaviors.\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"","component":""}\n- MCP tool: create-resource {"resource":{"name":"Send submission","method":"post","url":"https://api.example.com/submit","headers":[],"body":"formData"},"scopeInstanceId":"","dataSourceName":"Send submission","exposeAsDataSource":true}\n- MCP tool: update-props {"updates":[{"instanceId":"","name":"action","type":"json","value":[{"dataSourceId":""}]}]}\n- MCP tool: update-resource {"resourceId":"","values":{"email":{"recipientMode":"visitor","visitorEmailField":"email","includeAttachments":true}}}\n- MCP tool: update-project-settings {"meta":{"emailSender":"Acme "}}\n\nNotes:\n\n- Use `update-props` with a JSON Action array to add, order, or remove destinations. The Action entries use `{ "dataSourceId": "..." }` and support up to ten Resources, matching the Builder control. Each connected Action runs in its configured order. An extra `enabled` key in older saved settings is ignored.\n- Create each destination Resource in the Form\'s scope so it can use `formData` and `browserInfo`. Set `exposeAsDataSource:true` to receive the data-source id used by the Action array. When a Resource uses Form-only parameters, it is kept out of page-load requests and runs with the Form submission.\n- `update-resource` accepts the same Email settings as the Builder: project, custom, or visitor recipients; sender; subject; body; and submitted-file attachments. Use expressions in string fields for dynamic values.\n- `update-project-settings` edits the project-wide Email recipients and Reply to. `update-props` also sets Form fields and Success redirect, while `bind-props` supplies dynamic expressions. `insert-component` uses the registered Form template, including its default contact fields and Email Actions. Set subject and body on each Email Resource.\n- MCP mutations update saved project configuration. To test real delivery, submit the Form in Preview or on a published test site and inspect the configured destinations.\n\n## Query Markdown assets\n\nCommands:\n\n- MCP tool: get-asset-field-catalog {}\n- MCP tool: validate-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","draft"],"operator":"ne","value":true}]},"limit":20}}\n- MCP tool: create-assets-resource {"name":"All assets","scopeInstanceId":"","dataSourceName":"assets"}\n- MCP tool: create-assets-resource {"name":"Published posts","scopeInstanceId":"","dataSourceName":"posts","query":{"result":"many","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"}],"limit":{"type":"literal","value":20},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["properties","excerpt"]]},"content":{"mode":"none"}}}\n- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"","dataSourceName":"post","query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body-ref"}}}\n- MCP tool: list-assets-resources {}\n- MCP tool: get-assets-resource {"resourceId":""}\n- MCP tool: update-assets-resource {"resourceId":"","values":{"query":null}}\n- MCP tool: preview-asset-query {"query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"]]},"content":{"mode":"markdown-body-ref"}}}\n\nNotes:\n\n- Choose `.mdx` connected to a Content Block when editors must edit article bodies visually in Content mode. Publishing downloads and compiles every reachable MDX article, so more articles can slow publishing. Choose `.md` with Markdown Embed when editing the source in Assets is enough; Content mode editors can still edit the Markdown file there, but not its body on the canvas. `.md` needs no per-article MDX compilation, though the publish runner still synchronizes Asset files for both formats and static generation may read Markdown bodies.\n- Read the field catalog before authoring unfamiliar queries. It includes dynamic schema-less frontmatter paths such as `properties.author.name`, observed types, optionality, and mixed-type state without downloading the source files.\n- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.\n- Every reachable Assets data source contributes to the shared published database. Keep one final resource per rendered query. Update an existing scoped resource rather than creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicates.\n- Keep bounded overview filters, limits, and offsets literal and add a deterministic ID tie-breaker to the sort. With `content.mode:"none"`, compilation can materialize the small overview result instead of retaining its output fields across every candidate document. Use runtime expressions only for genuinely dynamic values such as the detail slug.\n- Combine filters with `where.all` (AND) and `where.any` (OR), including nested groups. Filter values, limit, and offset on a saved resource may be Webstudio expressions evaluated at render time. Preview queries use concrete JSON values.\n- Query Markdown or MDX files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database retains metadata and a document reference, then fetches only the selected files from Asset storage at runtime; it does not embed their bodies. Filter and paginate before content is loaded.\n- `full` and bounded `range` continue to request embedded file bytes. Use them only when the caller requires the complete source or a byte range.\n- In Markdown or MDX, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. Deferred `markdown-body-ref` content resolves matching files against the document\'s folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.\n- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. It does not render Webstudio MDX elements; connect the `.mdx` file to a Content Block for that workflow.\n- Preview each query with concrete values before saving it. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes must not be summed and are not separate allowances. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A completed Markdown blog should include every source document without truncation, contain no embedded Markdown bodies, and retain only its intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files.\n- Use `result:"many"` for listings. It returns the ID-keyed map at `.data`, with `totalCount` and `hasMore` at `.meta`, and remains the default for existing queries. Bind a listing Collection to `posts.data`.\n- Use `result:"one"` for a unique detail route. It returns the selected item or `null` directly at `post.data`, always includes its `id`, and omits pagination. Bind components and page settings directly with expressions such as `post.data.properties.title`, `post.data.content.text`, and `post.data ? 200 : 404`. `result:"first"` and `result:"last"` also return a direct item or `null` but require explicit sorting.\n- Assets always executes a structured query. Omit `query` to use the default many-result query, which selects URL and optional image dimensions. Set `values.query:null` to restore it.\n- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.\n- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":""}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\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## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":""}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":""}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"","values":{"parentId":""}}\n- MCP tool: update-asset-folder {"folderId":"","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":""}\n- MCP tool: duplicate-asset-folder {"folderId":"","parentId":""}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":""}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\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- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\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- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"","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\nNotes:\n\n- Multi-file uploads return `uploaded`, `failed`, and `ambiguous` lists with the\n original input index. Retry only `failed` files. A forced upload in\n `ambiguous` may already be committed; inspect the Assets list before deciding\n whether to upload it again. Successful uploads remain committed.\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":""}\n- MCP tool: duplicate-asset {"assetId":"","folderId":""}\n- MCP tool: duplicate-asset {"assetId":"","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":""}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":""}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"","toAssetId":""}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":[""],"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 --json\n\n## Unpublish\n\nUnpublish completes without a publish job.\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 --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":[""]}\n- MCP tool: apply-patch {"baseVersion":"","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":"hello@example.com","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- webstudio search-project \'{"query":"pricing"}\'\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","namespaces":["resources"]}\n- MCP tool: search-project {"query":"Brand","namespaces":["styles","styleSources","styleSourceSelections"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"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":""}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- `search-project` is a standalone local-session command over every Builder namespace. It returns matching values with stable match ids, namespace paths, owning entities, references, and affected pages.\n- Use it when a value or id is known. Use list/get tools when the project structure or target is not known.\n- The command synchronizes its required Builder namespaces, then searches locally and returns only matches. Namespace filters limit values matched; related namespaces may still supply route and reference context, and synchronization is unchanged. This reduces data passed to the model, not the initial project-data synchronization.\n- Asset records and file metadata are searchable. Asset binary or document contents are not Builder namespace data and are not searched.\n- Values in recognized credential fields are excluded and counted in `excludedSensitiveValueCount`.\n- 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 =`\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":"","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":"","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":"","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\""}}}\n- MCP tool: update-resource {"resourceId":"","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"","toAssetId":""}\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":"","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":[""],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"","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":"","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"","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":"","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":"","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"","fragment":"{/_ collection content _/}"}\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":"","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"

{expression`collectionItem.title`}

"}\n- MCP tool: inspect-instance {"instanceId":"","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":"","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":"","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":"","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","taskScope":"structural-project-change","workflow":"authenticated-page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"","values":{"meta":{"auth":{"method":"basic","login":"","password":""}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"","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","taskScope":"visual-change","workflow":"design-input"}\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":"","fragment":"

Section copy

"}\n- MCP tool: update-styles {"updates":[{"instanceId":"","breakpoint":"","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {}\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- Ask whether the user wants visual verification unless they explicitly requested\n it. If they decline, stop after focused reads and a static audit. If they opt\n in, verify one familiar viewport inside every distinct Builder breakpoint\n range, 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 `workflow:"authenticated-page"`, 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 `workflow:"design-input"`, 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## Search project data\n\nRun `webstudio search-project \'{"query":"known value"}\'` to search all Builder\nnamespaces in the local project session. Narrow it with\n`{"query":"Brand","namespaces":["styleSources","styles"]}` when only specific\nnamespaces are relevant. Results contain the current value, stable match id,\nnamespace path, owning entity, resolved references, and affected pages.\n\nValues in recognized credential fields are excluded and reported in\n`excludedSensitiveValueCount`.\n\nThe command synchronizes its required Builder namespaces, then searches locally\nand returns only matches. Namespace filters limit values matched; related\nnamespaces may still supply route and reference context, and synchronization is\nunchanged. This reduces data sent to the model, not project synchronization. It\nsearches asset metadata, not asset binaries or document contents.\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 \'\'` or with the explicit form `webstudio mcp single-op-call \'\'`:\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[] }.\nAn Editor link with API access can patch text and editable props inside a\nContent Block. The server checks the complete batch before saving it. Pages,\nassets, component structure, and design changes still require Builder access.\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`, and `json`. Use `json`\nfor all arrays and objects, including tags, selected categories, and nested API\nfilter 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`,\n`system.search`. A query key with one value is a string; a repeated key is an\narray of values in their original order. For `?tag=red&tag=blue`,\n`system.search.tag` is `["red", "blue"]`; missing keys are absent.\n\nFor a saved Webhook Form on `/products/:slug`, a Resource URL can use\n`"https://api.example.com/products/" + system.params.slug + "/comments"`.\nOn `/products/chair?source=newsletter&tag=red&tag=blue`, use\n`system.search.source` for `"newsletter"` and `system.search.tag` for\n`["red", "blue"]` in a header or object body expression. A missing key stays\nabsent; use `system.search.source ?? "direct"` when a fallback is needed.\nThese values come from the page being submitted, including after navigation.\nFor a saved Webhook Form action, object body bindings are combined with the\nsubmitted fields; a submitted field wins when both use the same key.\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": { "type": "text", "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": diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.md index 3d34a6b6f5..20675c0689 100644 --- a/packages/cli/src/docs/api-use-cases.md +++ b/packages/cli/src/docs/api-use-cases.md @@ -675,10 +675,12 @@ Notes: Commands: - MCP tool: update-selected-styles {"updates":[{"instanceId":"","styleSourceId":"tag-style:button","property":"color","value":{"type":"keyword","value":"red"}}]} +- MCP tool: update-selected-styles {"updates":[{"instanceId":"","styleSourceId":"tag-style:div","state":" h2:hover","property":"color","value":{"type":"keyword","value":"red"}}]} Notes: - Use `tag-style:` to create or edit a Tag style. The first update creates its style source; no instance attachment is saved. +- For a nested tag, set `state` to a space followed by the tag and optional condition, such as ` h2:hover`. The same selector forms work in Tag, Token, and Local styles. - Use `delete-selected-styles` with the same `instanceId`, `styleSourceId`, and `property` to remove a declaration. ## Update local styles diff --git a/packages/css-data/src/selector-validation.test.ts b/packages/css-data/src/selector-validation.test.ts index 7e29038322..40bdaa9a16 100644 --- a/packages/css-data/src/selector-validation.test.ts +++ b/packages/css-data/src/selector-validation.test.ts @@ -2,6 +2,24 @@ import { describe, test, expect } from "vitest"; import { validateSelector } from "./selector-validation"; describe("validateSelector", () => { + test("reads the condition from one nested tag", () => { + expect(validateSelector(' h2[data-state="open"]:hover')).toMatchObject({ + success: true, + type: "tag", + tag: "h2", + condition: '[data-state="open"]:hover', + }); + expect(validateSelector(" h2[ data-state = open ]:hover")).toMatchObject({ + success: true, + type: "tag", + tag: "h2", + condition: "[ data-state = open ]:hover", + }); + expect(validateSelector(" h2:before")).toMatchObject({ + success: true, + type: "pseudo-element", + }); + }); test.each([ ":hover, body", "body:hover", @@ -30,20 +48,45 @@ describe("validateSelector", () => { "[data-state=open] [data-part=content]", ":hover > .icon", ":not(.disabled) > [aria-hidden=true]", - ])("accepts states targeting descendants: %s", (selector) => { - expect(validateSelector(selector).success).toBe(true); - }); - - test.each([" p", " button:hover", " a[aria-current=page]"])( - "accepts one descendant tag and its states: %s", + ])( + "keeps saved state descendants without accepting new ones: %s", (selector) => { - expect(validateSelector(selector)).toMatchObject({ - success: true, - type: "tag", - }); + expect( + validateSelector(selector, { allowLegacyStateDescendants: true }) + .success + ).toBe(true); + expect(validateSelector(selector).success).toBe(false); } ); + test.each([ + ":hover", + "[data-state=open]", + "::before", + " h2", + " h2:hover", + ' h2[a="123"]', + " h2::before", + ])( + "accepts a styled-element condition or one nested tag in Add more: %s", + (selector) => { + expect(validateSelector(selector).success).toBe(true); + } + ); + + test.each([ + " p", + " button:hover", + " a[aria-current=page]", + ' div[a="123"]', + " div::before", + ])("accepts one descendant tag and its states: %s", (selector) => { + expect(validateSelector(selector)).toMatchObject({ + success: true, + type: "tag", + }); + }); + test.each([" p strong", " .card", " #card", " p + span"])( "rejects unsupported descendant tag selectors: %s", (selector) => { diff --git a/packages/css-data/src/selector-validation.ts b/packages/css-data/src/selector-validation.ts index beffdd27fd..dd6aff6ffa 100644 --- a/packages/css-data/src/selector-validation.ts +++ b/packages/css-data/src/selector-validation.ts @@ -6,23 +6,27 @@ export type SelectorValidationResult = | { success: false; error: string } | { success: true; - type: "pseudo-class" | "pseudo-element" | "attribute" | "tag"; - }; + type: "pseudo-class" | "pseudo-element" | "attribute"; + } + | { success: true; type: "tag"; tag: string; condition: string }; /** * 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. Descendant and - * child selectors may follow that state because the CSS engine anchors the - * complete suffix to the generated instance selector. Selector lists, + * pseudo-elements, and attribute selectors may be compounded. New input accepts + * only a state on the styled element or one nested tag. Existing saved state + * descendants may be checked with allowLegacyStateDescendants. Selector lists, * unanchored selectors, and sibling combinators are rejected. * @param selector - The selector to validate (e.g., ":hover", "::before", "[data-state=open]") * @returns SelectorValidationResult with success status and type or error message */ export const validateSelector = ( selector: string, - { allowDescendants = true }: { allowDescendants?: boolean } = {} + { + allowDescendants = true, + allowLegacyStateDescendants = false, + }: { allowDescendants?: boolean; allowLegacyStateDescendants?: boolean } = {} ): SelectorValidationResult => { if (!selector || selector.trim() === "") { return { success: false, error: "Selector cannot be empty" }; @@ -44,7 +48,10 @@ export const validateSelector = ( } try { - const ast = csstree.parse(selector, { context: "selectorList" }); + const ast = csstree.parse(selector, { + context: "selectorList", + positions: isTagSelector, + }); if (ast.type !== "SelectorList" || ast.children.size !== 1) { return { success: false, @@ -68,6 +75,12 @@ export const validateSelector = ( error: "Selector must be one state scoped to the current element", }; } + if (allowLegacyStateDescendants === false && firstCombinatorIndex !== -1) { + return { + success: false, + error: "Invalid CSS selector syntax", + }; + } const stateNodes = selectorNodes.slice( 0, firstCombinatorIndex === -1 ? undefined : firstCombinatorIndex @@ -145,11 +158,30 @@ export const validateSelector = ( return { success: false, error: "Invalid pseudo-class" }; } + if ( + isTagSelector && + stateNodes[0]?.type === "TypeSelector" && + pseudoElementNames.length === 0 && + pseudoClassNames.length > 0 && + pseudoClassNames.every((name) => isKnownSelector(name, pseudoElements)) + ) { + // Keep the legacy single-colon pseudo-element classification. + return { success: true, type: "pseudo-element" }; + } + if (isTagSelector && stateNodes[0]?.type === "TypeSelector") { + return { + success: true, + type: "tag", + tag: stateNodes[0].name, + condition: selector.slice(stateNodes[0].loc?.end.offset), + }; + } + 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 - return { success: true, type: isTagSelector ? "tag" : "pseudo-element" }; + return { success: true, type: "pseudo-element" }; } if (pseudoClassNames.length > 0) { @@ -160,15 +192,11 @@ export const validateSelector = ( ) { return { success: true, type: "pseudo-element" }; } - return { success: true, type: isTagSelector ? "tag" : "pseudo-class" }; + return { success: true, type: "pseudo-class" }; } if (foundAttribute) { - return { success: true, type: isTagSelector ? "tag" : "attribute" }; - } - - if (isTagSelector) { - return { success: true, type: "tag" }; + return { success: true, type: "attribute" }; } // If we get here, something unexpected happened diff --git a/packages/css-engine/src/core/atomic.test.ts b/packages/css-engine/src/core/atomic.test.ts index 5335af9055..21e1ea3833 100644 --- a/packages/css-engine/src/core/atomic.test.ts +++ b/packages/css-engine/src/core/atomic.test.ts @@ -197,15 +197,15 @@ test("support descendant suffix", () => { }); expect(generateAtomic(sheet, { getKey: () => "" }).cssText) .toMatchInlineSnapshot(` -"@media all { - .c143pt9k:hover { - display: block - } - .cpdl2lp img:hover { - display: block - } -}" -`); + "@media all { + .c143pt9k:hover { + display: block + } + :where(.cpdl2lp) img:hover { + display: block + } + }" + `); }); test("generate prefixed and unprefixed in the same rule", () => { @@ -269,15 +269,15 @@ test("generate merged properties as single rule", () => { }); expect(generateAtomic(sheet, { getKey: () => "" }).cssText) .toMatchInlineSnapshot(` -"@media all { - .cdj9gv4 { - margin: auto - } - .c340vfr img { - margin: 10px - } -}" -`); + "@media all { + .cdj9gv4 { + margin: auto + } + :where(.c340vfr) img { + margin: 10px + } + }" + `); }); test("convert :local-link to [aria-current=page] selector", () => { diff --git a/packages/css-engine/src/core/rules.ts b/packages/css-engine/src/core/rules.ts index 4bbb77fdc5..e63266982d 100644 --- a/packages/css-engine/src/core/rules.ts +++ b/packages/css-engine/src/core/rules.ts @@ -263,7 +263,14 @@ export class NestingRule { if (nestedSelector === ":local-link") { nestedSelector = "[aria-current=page]"; } - const selector = this.#selector + this.#descendantSuffix + nestedSelector; + const isDescendant = + this.#descendantSuffix.startsWith(" ") || + nestedSelector.startsWith(" "); + const baseSelector = + isDescendant && this.#selector + ? `:where(${this.#selector})` + : this.#selector; + const selector = baseSelector + this.#descendantSuffix + nestedSelector; let style = styleBySelector.get(selector); if (style === undefined) { style = new Map(); diff --git a/packages/css-engine/src/core/style-sheet-regular.test.ts b/packages/css-engine/src/core/style-sheet-regular.test.ts index 83aa0da0cc..3b9977bb15 100644 --- a/packages/css-engine/src/core/style-sheet-regular.test.ts +++ b/packages/css-engine/src/core/style-sheet-regular.test.ts @@ -265,6 +265,23 @@ describe("mixin rule", () => { `); }); + test.each([' div[a="123"]', " div:hover", " div::before"])( + "keeps scoped tag selector specificity for %s", + (selector) => { + const sheet = createRegularStyleSheet(); + const rule = sheet.addNestingRule(".container"); + rule.setDeclaration({ + breakpoint: "base", + selector, + property: "color", + value: { type: "keyword", value: "red" }, + }); + expect(rule.toString({ breakpoint: "base" })).toContain( + `:where(.container)${selector} {` + ); + } + ); + test("invalidate cache after applying mixins", () => { const sheet = createRegularStyleSheet(); const rule = sheet.addNestingRule(".instance"); @@ -749,15 +766,15 @@ describe("Style Sheet Regular", () => { value: { type: "keyword", value: "auto" }, }); expect(sheet.cssText).toMatchInlineSnapshot(` -"@media all { - .instance:hover { - width: auto - } - .instance img:hover { - width: auto - } -}" -`); + "@media all { + .instance:hover { + width: auto + } + :where(.instance) img:hover { + width: auto + } + }" + `); }); }); @@ -800,15 +817,15 @@ test("generate merged properties as single rule", () => { unit: "px", }); expect(sheet.cssText).toMatchInlineSnapshot(` -"@media all { - instance { - margin: auto - } - instance img { - margin: 10px - } -}" -`); + "@media all { + instance { + margin: auto + } + :where(instance) img { + margin: 10px + } + }" + `); }); test("convert :local-link to [aria-current=page] selector", () => { diff --git a/packages/project-build/src/db/styles.test.ts b/packages/project-build/src/db/styles.test.ts index b82aac27f1..ca9ed6bd0a 100644 --- a/packages/project-build/src/db/styles.test.ts +++ b/packages/project-build/src/db/styles.test.ts @@ -66,4 +66,11 @@ test("rejects malformed state selectors before saving styles", () => { new Map([["valid", { ...style("color", "red"), state: ":hover" }]]) ).success ).toBe(true); + expect( + writableStyles.safeParse( + new Map([ + ["legacy", { ...style("color", "red"), state: ":hover .button" }], + ]) + ).success + ).toBe(true); }); diff --git a/packages/project-build/src/db/styles.ts b/packages/project-build/src/db/styles.ts index 543f5c8f2f..19c677b491 100644 --- a/packages/project-build/src/db/styles.ts +++ b/packages/project-build/src/db/styles.ts @@ -27,7 +27,8 @@ export const writableStyles = styles.refine((value) => parseGeneratedStyleDeclaration(style).errors.length === 0 && (style.state === undefined || style.state === "" || - validateSelector(style.state).success) + validateSelector(style.state, { allowLegacyStateDescendants: true }) + .success) ) ); diff --git a/packages/project-build/src/runtime/data-formats/token-css.test.ts b/packages/project-build/src/runtime/data-formats/token-css.test.ts index b06b13c547..2fe5838f9b 100644 --- a/packages/project-build/src/runtime/data-formats/token-css.test.ts +++ b/packages/project-build/src/runtime/data-formats/token-css.test.ts @@ -21,7 +21,21 @@ test("Tag style clipboard data accepts only a supported tag and its CSS selector parseTagStyleTransferData( '/* @webstudio/tag-style-css/v1 "button" */\n.ws-tag-style p { color: red; }' ).valid - ).toBe(false); + ).toBe(true); +}); + +test("Tag style clipboard data accepts one nested tag with a state", () => { + const parsed = parseTagStyleTransferData( + '/* @webstudio/tag-style-css/v1 "button" */\n.ws-tag-style h2:hover { color: red; }' + ); + expect(parsed.valid).toBe(true); + if (parsed.valid) { + expect(parsed.data.fragment.styles).toEqual( + expect.arrayContaining([ + expect.objectContaining({ state: " h2:hover", property: "color" }), + ]) + ); + } }); test("reads a CSS token with variables, states, breakpoints, images, and fonts", () => { diff --git a/packages/project-build/src/runtime/data-formats/token-css.ts b/packages/project-build/src/runtime/data-formats/token-css.ts index 1bce398335..c092601246 100644 --- a/packages/project-build/src/runtime/data-formats/token-css.ts +++ b/packages/project-build/src/runtime/data-formats/token-css.ts @@ -341,8 +341,9 @@ const parseStyleSourceTransferData = ( (kind === "tag" && style.selector !== ":root" && style.state !== undefined && - validateSelector(style.state, { allowDescendants: false }).success === - false) + validateSelector(style.state, { + allowLegacyStateDescendants: true, + }).success === false) ) ) { return { owned: true, valid: false }; diff --git a/packages/project-build/src/runtime/search.ts b/packages/project-build/src/runtime/search.ts index 5989b94dba..5c54b2ee19 100644 --- a/packages/project-build/src/runtime/search.ts +++ b/packages/project-build/src/runtime/search.ts @@ -648,7 +648,9 @@ export const analyzeProject = ( for (const declaration of state.styles.values()) { if ( declaration.state !== undefined && - validateSelector(declaration.state).success === false + validateSelector(declaration.state, { + allowLegacyStateDescendants: true, + }).success === false ) { matches.push({ kind: "style", diff --git a/packages/project-build/src/runtime/styles.test.ts b/packages/project-build/src/runtime/styles.test.ts index a8e0b0b473..ccdead2182 100644 --- a/packages/project-build/src/runtime/styles.test.ts +++ b/packages/project-build/src/runtime/styles.test.ts @@ -63,6 +63,7 @@ import { styleReplaceInput, styleUpdateDeclarationsInput, styleUpdateInput, + selectedStyleUpdateDeclarationsInput, defineCssVariables, deleteDesignTokenStyles, deleteSelectedStyleDeclarations, @@ -1102,31 +1103,43 @@ describe("runtime style operations", () => { "body:hover", ":hover + .tooltip", ":hover ~ .tooltip", - ])( - "rejects state selectors that escape the styled element when writing: %s", - (state) => { - expect( - styleUpdateInput.safeParse({ - instanceId: "box", - property: "color", - value: { type: "keyword", value: "red" }, - state, - }) - ).toMatchObject({ success: false }); - expect( - designTokenCreateInput.safeParse({ - name: "Primary", - declarations: [ - { - property: "color", - value: { type: "keyword", value: "red" }, - state, - }, - ], - }) - ).toMatchObject({ success: false }); - } - ); + ":hover .button", + ":hover > .icon", + ])("rejects unsupported state selectors when writing: %s", (state) => { + expect( + styleUpdateInput.safeParse({ + instanceId: "box", + property: "color", + value: { type: "keyword", value: "red" }, + state, + }) + ).toMatchObject({ success: false }); + expect( + designTokenCreateInput.safeParse({ + name: "Primary", + declarations: [ + { + property: "color", + value: { type: "keyword", value: "red" }, + state, + }, + ], + }) + ).toMatchObject({ success: false }); + expect( + selectedStyleUpdateDeclarationsInput.safeParse({ + updates: [ + { + instanceId: "box", + styleSourceId: "token", + property: "color", + value: { type: "keyword", value: "red" }, + state, + }, + ], + }) + ).toMatchObject({ success: false }); + }); test("accepts an invalid state as an existing declaration deletion coordinate", () => { expect( @@ -1146,60 +1159,15 @@ describe("runtime style operations", () => { ".box[data-state=open] > [data-part=content]", ], ])( - "preserves an editable descendant state through mutation and generated CSS: %s", + "preserves saved descendant states in generated CSS: %s", (state, generatedSelector) => { - expect( - styleUpdateInput.safeParse({ - instanceId: "box", - property: "borderTopColor", - value: { type: "keyword", value: "currentcolor" }, - state, - }) - ).toMatchObject({ success: true }); - - 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, + breakpoint: "desktop", + selector: state, + property: "borderTopColor", + value: { type: "keyword", value: "currentcolor" }, }); expect(rule.toString({ breakpoint: "desktop" })).toContain( `${generatedSelector} {\n border-top-color: currentcolor\n}` @@ -1680,30 +1648,34 @@ describe("runtime style operations", () => { ).toBe(false); }); - test("rejects a descendant selector on a tag token", () => { + test("accepts a nested tag selector on a global Tag style", () => { const id = getTagStyleId("button"); - expect(() => - updateSelectedStyleDeclarations( - { - breakpoints: runtimeBreakpoints, - instances: toMap([instance("button-instance")]), - styles: new Map(), - styleSources: new Map(), - styleSourceSelections: new Map(), - }, - { - updates: [ - { - instanceId: "button-instance", - styleSourceId: id, - property: "color", - value: { type: "keyword", value: "red" }, - state: " p", - }, - ], - } - ) - ).toThrow(); + const mutation = updateSelectedStyleDeclarations( + { + breakpoints: runtimeBreakpoints, + instances: toMap([instance("button-instance")]), + styles: new Map(), + styleSources: new Map(), + styleSourceSelections: new Map(), + }, + { + updates: [ + { + instanceId: "button-instance", + styleSourceId: id, + property: "color", + value: { type: "keyword", value: "red" }, + state: " h2:hover", + }, + ], + } + ); + expect(mutation.payload).toContainEqual({ + namespace: "styleSources", + patches: [ + { op: "add", path: [id], value: { type: "tag", id, tag: "button" } }, + ], + }); }); test("renames, locks, and deletes style sources", () => { diff --git a/packages/project-build/src/runtime/styles.ts b/packages/project-build/src/runtime/styles.ts index 4e36b8a058..4e4e7654a7 100644 --- a/packages/project-build/src/runtime/styles.ts +++ b/packages/project-build/src/runtime/styles.ts @@ -2050,7 +2050,9 @@ const getExistingStyleDeletionKeys = < styleKey !== undefined && existingStyleKeys.has(styleKey) === true; if ( deletion.state !== undefined && - validateSelector(deletion.state).success === false && + validateSelector(deletion.state, { + allowLegacyStateDescendants: true, + }).success === false && exists === false ) { return throwBuilderRuntimeError( @@ -3489,17 +3491,6 @@ export const updateSelectedStyleDeclarations = ( id: update.styleSourceId, tag: tag!, }; - if ( - styleSource.type === "tag" && - update.state !== undefined && - validateSelector(update.state, { allowDescendants: false }).success === - false - ) { - return throwBuilderRuntimeError( - "BAD_REQUEST", - "Selector must be one state scoped to the current element" - ); - } if (isStyleSourceLocked(styleSource)) { return throwBuilderRuntimeError("BAD_REQUEST", "Style source is locked"); } diff --git a/packages/sdk/src/css.test.tsx b/packages/sdk/src/css.test.tsx index 76e8e988e9..40ae345d5d 100644 --- a/packages/sdk/src/css.test.tsx +++ b/packages/sdk/src/css.test.tsx @@ -101,8 +101,8 @@ test("renders a tag selector inside an attached token as a descendant", () => { assetBaseUrl: "/", }); - expect(cssText).toContain(".w-box p"); - expect(atomicCssText).toMatch(/\.c[a-z0-9]+ p/); + expect(cssText).toContain(":where(.w-box) p"); + expect(atomicCssText).toMatch(/:where\(\.c[a-z0-9]+\) p/); }); test("generates distinct upright and italic variable font faces", () => { @@ -228,39 +228,39 @@ test("generate descendant selector", () => { assetBaseUrl: "", }); expect(cssText).toMatchInlineSnapshot(` -" -@media all { - .w-body { - color: blue - } - .w-body:hover { - color: red - } - .w-body a { - color: blue - } - .w-body a:hover { - color: red - } -}" -`); + " + @media all { + .w-body { + color: blue + } + .w-body:hover { + color: red + } + :where(.w-body) a { + color: blue + } + :where(.w-body) a:hover { + color: red + } + }" + `); expect(atomicCssText).toMatchInlineSnapshot(` -" -@media all { - .c17hlgoh { - color: blue - } - .c92zrdl:hover { - color: red - } - .chhpmat a { - color: blue - } - .c32fhpn a:hover { - color: red - } -}" -`); + " + @media all { + .c17hlgoh { + color: blue + } + .c92zrdl:hover { + color: red + } + :where(.chhpmat) a { + color: blue + } + :where(.c32fhpn) a:hover { + color: red + } + }" + `); expect(atomicClasses).toMatchInlineSnapshot(` Map { "body" => [