Skip to content

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

feat: MCP update 3 (#5864)

Oleg Isonen071a4d9a85a9
diff --git a/@types/scroll-timeline.d.ts b/@types/scroll-timeline.d.ts
index a68b734da5..6c4b76d2e2 100644
--- a/@types/scroll-timeline.d.ts
+++ b/@types/scroll-timeline.d.ts
@@ -9,6 +9,12 @@ declare class ScrollTimeline extends AnimationTimeline {
constructor(options?: ScrollTimelineOptions);
}
+// https://drafts.csswg.org/scroll-animations-1/#dictdef-keyframeanimationoptions
+interface KeyframeAnimationOptions {
+ rangeStart?: string;
+ rangeEnd?: string;
+}
+
interface ViewTimelineOptions {
subject?: Element | Document | null;
axis?: ScrollAxis;
diff --git a/apps/builder/app/builder/features/pages/page-settings/section-search.tsx b/apps/builder/app/builder/features/pages/page-settings/section-search.tsx
index 245c28f786..91d911ab1d 100644
--- a/apps/builder/app/builder/features/pages/page-settings/section-search.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings/section-search.tsx
@@ -21,7 +21,7 @@ import type {
PageSettingsValues,
} from "@webstudio-is/project-build/runtime/pages";
import { useStore } from "@nanostores/react";
-import { $assets, $pages } from "~/shared/sync/data-stores";
+import { $assets, $projectSettings } from "~/shared/sync/data-stores";
import { $pageRootScope } from "../page-utils";
import { SearchPreview } from "../search-preview";
import { usePageUrl, type OnChange } from "./shared";
@@ -96,9 +96,9 @@ export const SearchSection = ({
const excludePageFromSearchId = useId();
const { variableValues, scope, aliases } = useStore($pageRootScope);
const assets = useStore($assets);
- const pages = useStore($pages);
+ const projectSettings = useStore($projectSettings);
const pageUrl = usePageUrl(values);
- const faviconAsset = assets.get(pages?.meta?.faviconAssetId ?? "");
+ const faviconAsset = assets.get(projectSettings?.meta.faviconAssetId ?? "");
const faviconUrl = faviconAsset?.type === "image" ? faviconAsset.name : "";
const title = String(computeExpression(values.title, variableValues));
const description = String(
@@ -132,7 +132,7 @@ export const SearchSection = ({
}}
>
<SearchPreview
- siteName={pages?.meta?.siteName ?? ""}
+ siteName={projectSettings?.meta.siteName ?? ""}
faviconUrl={faviconUrl}
pageUrl={pageUrl}
titleLink={title}
diff --git a/apps/builder/app/builder/features/publish/publish.tsx b/apps/builder/app/builder/features/publish/publish.tsx
index a851d3135f..34151e0e88 100644
--- a/apps/builder/app/builder/features/publish/publish.tsx
+++ b/apps/builder/app/builder/features/publish/publish.tsx
@@ -78,6 +78,7 @@ import {
$dataSources,
$instances,
$pages,
+ $projectSettings,
$props,
$resources,
} from "~/shared/sync/data-stores";
@@ -323,9 +324,15 @@ const ChangeProjectDomain = ({
};
const $restrictedFeatures = computed(
- [$pages, $dataSources, $instances, $permissions],
- (pages, dataSources, instances, permissions) =>
- getRestrictedFeatures({ pages, dataSources, instances, permissions })
+ [$pages, $projectSettings, $dataSources, $instances, $permissions],
+ (pages, projectSettings, dataSources, instances, permissions) =>
+ getRestrictedFeatures({
+ pages,
+ projectSettings,
+ dataSources,
+ instances,
+ permissions,
+ })
);
const usePublishCountdown = (isPublishing: boolean) => {
diff --git a/apps/builder/app/builder/features/publish/restricted-features.test.ts b/apps/builder/app/builder/features/publish/restricted-features.test.ts
index 645aad2a76..b59de621d1 100644
--- a/apps/builder/app/builder/features/publish/restricted-features.test.ts
+++ b/apps/builder/app/builder/features/publish/restricted-features.test.ts
@@ -11,6 +11,7 @@ import {
getRestrictedFeatures,
type RestrictedFeaturesPermissions,
} from "./restricted-features";
+import type { ProjectSettings } from "@webstudio-is/project-build";
const createPage = (page: Partial<Page> & Pick<Page, "id">): Page => ({
name: page.id,
@@ -64,13 +65,16 @@ const defaultPermissions: RestrictedFeaturesPermissions = {
const getFeatures = ({
pages,
+ projectSettings,
permissions,
}: {
pages: Pages | undefined;
+ projectSettings?: ProjectSettings;
permissions: Partial<RestrictedFeaturesPermissions>;
}) =>
getRestrictedFeatures({
pages,
+ projectSettings,
dataSources: new Map<string, DataSource>(),
instances: new Map<string, Instance>(),
permissions: { ...defaultPermissions, ...permissions },
@@ -79,7 +83,9 @@ const getFeatures = ({
describe("getRestrictedFeatures", () => {
test("restricts project authentication when auth is not allowed", () => {
const features = getFeatures({
- pages: createPages({
+ pages: createPages(),
+ projectSettings: {
+ compiler: {},
meta: {
auth: JSON.stringify({
version: 1,
@@ -92,7 +98,7 @@ describe("getRestrictedFeatures", () => {
},
}),
},
- }),
+ },
permissions: { allowAuth: false },
});
diff --git a/apps/builder/app/builder/features/publish/restricted-features.ts b/apps/builder/app/builder/features/publish/restricted-features.ts
index e88f80e402..2cc5140a79 100644
--- a/apps/builder/app/builder/features/publish/restricted-features.ts
+++ b/apps/builder/app/builder/features/publish/restricted-features.ts
@@ -7,6 +7,7 @@ import {
type Pages,
} from "@webstudio-is/sdk";
import { findPageAndSelectorByInstanceId } from "@webstudio-is/project-build/runtime/lookup";
+import type { ProjectSettings } from "@webstudio-is/project-build";
export type RestrictedFeature =
| undefined
@@ -24,11 +25,13 @@ export type RestrictedFeaturesPermissions = {
export const getRestrictedFeatures = ({
pages,
+ projectSettings,
dataSources,
instances,
permissions,
}: {
pages: Pages | undefined;
+ projectSettings?: ProjectSettings;
dataSources: Map<string, DataSource>;
instances: Map<string, Instance>;
permissions: RestrictedFeaturesPermissions;
@@ -37,14 +40,15 @@ export const getRestrictedFeatures = ({
if (pages === undefined) {
return features;
}
+ const projectMeta = projectSettings?.meta;
if (
permissions.maxContactEmailsPerProject === 0 &&
- (pages.meta?.contactEmail ?? "").trim()
+ (projectMeta?.contactEmail ?? "").trim()
) {
features.set("Custom contact email", undefined);
}
if (permissions.allowAuth === false) {
- if ((pages.meta?.auth ?? "").trim()) {
+ if ((projectMeta?.auth ?? "").trim()) {
features.set("Project auth", undefined);
}
for (const page of getAllPages(pages)) {
diff --git a/apps/builder/app/builder/features/settings-panel/controls/code.tsx b/apps/builder/app/builder/features/settings-panel/controls/code.tsx
index 7f29ce29c2..fe98b2782c 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/code.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/code.tsx
@@ -34,12 +34,30 @@ import {
humanizeAttribute,
} from "../shared";
import { PropertyLabel } from "../property-label";
+export type CodeIssue = HtmlEmbedCodeError & {
+ severity?: "error" | "warning";
+};
+
+export type CodeControlBehavior = {
+ autoSave?: boolean;
+ formatValue: (value: unknown) => string;
+ processValue: (
+ value: string
+ ) =>
+ | { success: false; issue: CodeIssue }
+ | { success: true; value: string; issue?: CodeIssue };
+ validateBinding: (value: unknown, label: string) => string | undefined;
+ getFixedValue: (
+ value: unknown,
+ label: string
+ ) => { success: true; value: string } | { success: false; message: string };
+};
const ErrorInfo = ({
error,
onAutoFix,
}: {
- error?: HtmlEmbedCodeError;
+ error?: CodeIssue;
onAutoFix: () => void;
}) => {
if (error === undefined) {
@@ -66,7 +84,15 @@ const ErrorInfo = ({
return (
<Tooltip content={errorContent} delayDuration={0}>
<SmallIconButton
- icon={<InfoCircleIcon color={rawTheme.colors.foregroundDestructive} />}
+ icon={
+ <InfoCircleIcon
+ color={
+ error.severity === "warning"
+ ? rawTheme.colors.foregroundSubtle
+ : rawTheme.colors.foregroundDestructive
+ }
+ />
+ }
/>
</Tooltip>
);
@@ -78,30 +104,51 @@ export const CodeControl = ({
propName,
computedValue,
onChange,
-}: ControlProps<"code"> | ControlProps<"codetext">) => {
- const [error, setError] = useState<HtmlEmbedCodeError>();
+ behavior,
+}: (ControlProps<"code"> | ControlProps<"codetext">) & {
+ behavior?: CodeControlBehavior;
+}) => {
+ const [error, setError] = useState<CodeIssue>();
const metaOverride = {
...meta,
control: "text" as const,
};
const lang = meta.control === "code" ? meta.language : undefined;
- const localValue = useDraftValue(String(computedValue ?? ""), (value) => {
- if (lang === "html") {
- const error = validateHtmlEmbedCode(value);
- setError(error);
+ const label = humanizeAttribute(metaOverride.label || propName);
+ const editorValue = behavior
+ ? behavior.formatValue(computedValue)
+ : String(computedValue ?? "");
+ const localValue = useDraftValue(
+ editorValue,
+ (value) => {
+ let storedValue = value;
- if (error) {
- return;
+ if (behavior) {
+ const result = behavior.processValue(value);
+ setError(result.issue);
+ if (result.success === false) {
+ return;
+ }
+ storedValue = result.value;
}
- }
- if (prop?.type === "expression") {
- updateExpressionValue(prop.value, value);
- } else {
- onChange({ type: "string", value });
- }
- });
- const label = humanizeAttribute(metaOverride.label || propName);
+ if (behavior === undefined && lang === "html") {
+ const error = validateHtmlEmbedCode(value);
+ setError(error);
+
+ if (error) {
+ return;
+ }
+ }
+
+ if (prop?.type === "expression") {
+ updateExpressionValue(prop.value, storedValue);
+ } else {
+ onChange({ type: "string", value: storedValue });
+ }
+ },
+ { autoSave: behavior?.autoSave ?? true }
+ );
const { scope, aliases } = useStore($selectedInstanceScope);
const expression =
@@ -150,7 +197,7 @@ export const CodeControl = ({
</DialogTitle>
}
readOnly={overwritable === false}
- invalid={error !== undefined}
+ invalid={error !== undefined && error.severity !== "warning"}
value={localValue.value}
onChange={(value) => {
setError(undefined);
@@ -161,15 +208,31 @@ export const CodeControl = ({
<BindingPopover
scope={scope}
aliases={aliases}
- validate={(value) => validatePrimitiveValue(value, label)}
+ validate={(value) =>
+ behavior
+ ? behavior.validateBinding(value, label)
+ : validatePrimitiveValue(value, label)
+ }
variant={variant}
value={expression}
onChange={(newExpression) =>
onChange({ type: "expression", value: newExpression })
}
- onRemove={(evaluatedValue) =>
- onChange({ type: "string", value: String(evaluatedValue) })
- }
+ onRemove={(evaluatedValue) => {
+ if (behavior) {
+ const fixedValue = behavior.getFixedValue(evaluatedValue, label);
+ if (fixedValue.success === false) {
+ setError({
+ message: fixedValue.message,
+ value: String(evaluatedValue),
+ });
+ return;
+ }
+ onChange({ type: "string", value: fixedValue.value });
+ return;
+ }
+ onChange({ type: "string", value: String(evaluatedValue) });
+ }}
/>
</BindingControl>
</VerticalLayout>
diff --git a/apps/builder/app/builder/features/settings-panel/controls/combined.tsx b/apps/builder/app/builder/features/settings-panel/controls/combined.tsx
index cb7fd3ebd8..dd65e1e98a 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/combined.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/combined.tsx
@@ -9,6 +9,7 @@ import { FileControl } from "./file";
import { UrlControl } from "./url";
import type { ControlProps } from "../shared";
import { JsonControl } from "./json";
+import { JsonCodeControl } from "./json-code";
import { TextContent } from "./text-content";
import { ResourceControl } from "./resource-control";
import { TagControl } from "./tag-control";
@@ -50,6 +51,10 @@ export const renderControl = ({
return <JsonControl key={key} meta={meta} prop={prop} {...rest} />;
}
+ if (meta.control === "json-code") {
+ return <JsonCodeControl key={key} meta={meta} prop={prop} {...rest} />;
+ }
+
if (meta.control === "text") {
return <TextControl key={key} meta={meta} prop={prop} {...rest} />;
}
diff --git a/apps/builder/app/builder/features/settings-panel/controls/json-code.test.ts b/apps/builder/app/builder/features/settings-panel/controls/json-code.test.ts
new file mode 100644
index 0000000000..3bc08b5ecf
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/controls/json-code.test.ts
@@ -0,0 +1,95 @@
+import { expect, test } from "vitest";
+import {
+ formatJsonCode,
+ getFixedJsonCodeValue,
+ parseJsonCode,
+ serializeJsonCode,
+ validateJsonCode,
+ validateJsonCodeValue,
+} from "./json-code";
+
+test("formats stored JSON with two-space indentation", () => {
+ expect(formatJsonCode({ name: "Acme", types: ["Organization"] })).toBe(
+ '{\n "name": "Acme",\n "types": [\n "Organization"\n ]\n}'
+ );
+});
+
+test("formats legacy string JSON as structured JSON", () => {
+ expect(formatJsonCode('{"a":1}')).toBe('{\n "a": 1\n}');
+});
+
+test("keeps invalid persisted JSON source editable without quoting it", () => {
+ expect(formatJsonCode("not json")).toBe("not json");
+});
+
+test("parses editor text into structured JSON", () => {
+ expect(parseJsonCode('{ "name": "Acme" }')).toEqual({
+ success: true,
+ value: { name: "Acme" },
+ });
+});
+
+test("serializes JSON for storage without formatting", () => {
+ expect(serializeJsonCode({ name: "Acme", enabled: true })).toBe(
+ '{"name":"Acme","enabled":true}'
+ );
+});
+
+test("validates and serializes bindings when converting them to fixed code", () => {
+ expect(getFixedJsonCodeValue({ name: "Acme" }, "Code")).toEqual({
+ success: true,
+ value: '{"name":"Acme"}',
+ });
+ expect(getFixedJsonCodeValue('{"name":"Acme"}', "Code")).toEqual({
+ success: true,
+ value: '{"name":"Acme"}',
+ });
+ expect(getFixedJsonCodeValue("not JSON", "Code")).toEqual({
+ success: false,
+ message: "Code: $ JSON-LD must be a valid JSON object or array.",
+ });
+});
+
+test.each(["", "invalid", '"text"', "1", "null"])(
+ "rejects non-object JSON %j",
+ (source) => {
+ expect(parseJsonCode(source)).toEqual({ success: false });
+ }
+);
+
+test("accepts object, array, and JSON string binding values", () => {
+ expect(validateJsonCodeValue({ a: 1 }, "Code")).toBeUndefined();
+ expect(validateJsonCodeValue([{ a: 1 }], "Code")).toBeUndefined();
+ expect(validateJsonCodeValue('{"a":1}', "Code")).toBeUndefined();
+});
+
+test("rejects non-JSON binding values", () => {
+ expect(validateJsonCodeValue(1, "Code")).toBe(
+ "Code: $ JSON-LD must be a valid JSON object or array."
+ );
+});
+
+test("validates JSON-LD structure and keeps vocabulary findings as warnings", () => {
+ expect(
+ validateJsonCode('{"@context":"https://schema.org","@type":1}')
+ ).toMatchObject({
+ success: false,
+ diagnostics: [
+ expect.objectContaining({
+ severity: "error",
+ code: "invalid-keyword-value",
+ }),
+ ],
+ });
+ expect(
+ validateJsonCode('{"@context":"https://schema.org","@type":"MadeUpType"}')
+ ).toMatchObject({
+ success: true,
+ diagnostics: [
+ expect.objectContaining({
+ severity: "warning",
+ code: "unknown-schema-org-type",
+ }),
+ ],
+ });
+});
diff --git a/apps/builder/app/builder/features/settings-panel/controls/json-code.ts b/apps/builder/app/builder/features/settings-panel/controls/json-code.ts
new file mode 100644
index 0000000000..382bc2c668
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/controls/json-code.ts
@@ -0,0 +1,105 @@
+import { createElement } from "react";
+import { parseJsonLd } from "@webstudio-is/sdk/runtime";
+import { validateJsonLdWithSchemaOrg } from "@webstudio-is/sdk/schema-org";
+import type { ControlProps } from "../shared";
+import { CodeControl, type CodeControlBehavior, type CodeIssue } from "./code";
+
+export const formatJsonCode = (value: unknown) => {
+ if (typeof value === "string") {
+ const parsed = parseJsonCode(value);
+ if (parsed.success) {
+ value = parsed.value;
+ } else {
+ return value;
+ }
+ }
+ return JSON.stringify(value ?? {}, undefined, 2) ?? "{}";
+};
+
+export const parseJsonCode = (
+ source: string
+): { success: true; value: object } | { success: false } => {
+ return parseJsonLd(source);
+};
+
+export const serializeJsonCode = (value: object) => JSON.stringify(value);
+
+export const validateJsonCode = (value: unknown) =>
+ validateJsonLdWithSchemaOrg(value);
+
+export const getFixedJsonCodeValue = (value: unknown, label: string) => {
+ const result = validateJsonCode(value);
+ if (result.success) {
+ return { success: true as const, value: serializeJsonCode(result.value) };
+ }
+ const error = result.diagnostics.find(({ severity }) => severity === "error");
+ return {
+ success: false as const,
+ message:
+ error === undefined
+ ? `${label} expects a JSON object or array`
+ : `${label}: ${error.path} ${error.message}`,
+ };
+};
+
+export const validateJsonCodeValue = (value: unknown, label: string) => {
+ const result = getFixedJsonCodeValue(value, label);
+ return result.success ? undefined : result.message;
+};
+
+const processJsonCodeValue = (
+ value: string
+): ReturnType<CodeControlBehavior["processValue"]> => {
+ const result = validateJsonCode(value);
+ const structuralError = result.diagnostics.find(
+ ({ severity }) => severity === "error"
+ );
+ if (result.success === false || structuralError !== undefined) {
+ return {
+ success: false,
+ issue: {
+ message:
+ structuralError === undefined
+ ? "Enter a JSON object or array."
+ : `${structuralError.path} ${structuralError.message}`,
+ value,
+ },
+ };
+ }
+ const warnings = result.diagnostics.filter(
+ ({ severity }) => severity === "warning"
+ );
+ const issue: CodeIssue | undefined =
+ warnings.length === 0
+ ? undefined
+ : {
+ severity: "warning",
+ message: warnings
+ .map(({ path, message }) => `${path} ${message}`)
+ .join("\n"),
+ value,
+ };
+ return {
+ success: true,
+ value: serializeJsonCode(result.value),
+ issue,
+ };
+};
+
+const jsonCodeBehavior: CodeControlBehavior = {
+ autoSave: false,
+ formatValue: formatJsonCode,
+ processValue: processJsonCodeValue,
+ validateBinding: validateJsonCodeValue,
+ getFixedValue: getFixedJsonCodeValue,
+};
+
+export const JsonCodeControl = ({
+ meta,
+ ...props
+}: ControlProps<"json-code">) =>
+ createElement(CodeControl, {
+ ...props,
+ meta: { ...meta, control: "code", language: "json" },
+ behavior: jsonCodeBehavior,
+ });
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar.tsx
index 3e24eb3ddc..b0d3f51478 100644
--- a/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar.tsx
+++ b/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar.tsx
@@ -171,7 +171,7 @@ const Toolbar = ({ state, scale }: ToolbarProps) => {
</IconButton>
</Tooltip>
- {isWithinLink === false && (
+ {(isWithinLink === false || state.isLink) && (
<Tooltip content="Inline link">
<IconButton
aria-label="Inline link"
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx b/apps/builder/app/builder/shared/asset-manager/asset-info.tsx
index 7049529286..e6e72a0079 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-info.tsx
@@ -64,7 +64,12 @@ import {
$activeInspectorPanel,
setActiveSidebarPanel,
} from "~/builder/shared/nano-states";
-import { $instances, $pages, $props } from "~/shared/sync/data-stores";
+import {
+ $instances,
+ $pages,
+ $projectSettings,
+ $props,
+} from "~/shared/sync/data-stores";
import {
formatAssetName,
parseAssetName,
@@ -78,9 +83,15 @@ import {
} from "@webstudio-is/project-build/runtime/assets";
const $usagesByAssetId = computed(
- [$pages, $props, $styles, $assets],
- (pages, props, styles, assets) => {
- return calculateUsagesByAssetId({ pages, props, styles, assets });
+ [$pages, $projectSettings, $props, $styles, $assets],
+ (pages, projectSettings, props, styles, assets) => {
+ return calculateUsagesByAssetId({
+ pages,
+ projectSettings,
+ props,
+ styles,
+ assets,
+ });
}
);
diff --git a/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx b/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx
index e08cdd34ba..76cdc96977 100644
--- a/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx
@@ -15,7 +15,13 @@ import {
Box,
} from "@webstudio-is/design-system";
import type { Asset } from "@webstudio-is/sdk";
-import { $assets, $pages, $props, $styles } from "~/shared/sync/data-stores";
+import {
+ $assets,
+ $pages,
+ $projectSettings,
+ $props,
+ $styles,
+} from "~/shared/sync/data-stores";
import { deleteAssets } from "~/builder/shared/assets";
import { formatAssetName } from "@webstudio-is/project-build/runtime/assets";
import { calculateUsagesByAssetId } from "@webstudio-is/project-build/runtime/assets";
@@ -30,6 +36,7 @@ const getUnusedAssets = () => {
const assets = $assets.get();
const usagesByAssetId = calculateUsagesByAssetId({
pages: $pages.get(),
+ projectSettings: $projectSettings.get(),
props: $props.get(),
styles: $styles.get(),
assets,
diff --git a/apps/builder/app/services/api-build.server.test.ts b/apps/builder/app/services/api-build.server.test.ts
index c91df632a0..c0e0f41969 100644
--- a/apps/builder/app/services/api-build.server.test.ts
+++ b/apps/builder/app/services/api-build.server.test.ts
@@ -89,6 +89,7 @@ const createBuildRow = (overrides: Record<string, unknown> = {}) => ({
]),
deployment: null,
marketplaceProduct: JSON.stringify({}),
+ projectSettings: JSON.stringify({ meta: {}, compiler: {} }),
...overrides,
});
@@ -284,8 +285,6 @@ describe("api build snapshot", () => {
test("returns page folders and data namespaces when requested", () => {
const pages = createDefaultPages({ rootInstanceId: "root-1" });
- pages.meta = { siteName: "Acme" };
- pages.compiler = { atomicStyles: true };
pages.redirects = [{ old: "/old", new: "/new", status: "301" }];
const build = {
id: "build-1",
@@ -301,6 +300,10 @@ describe("api build snapshot", () => {
dataSources: [{ id: "variable-1" }],
breakpoints: [{ id: "breakpoint-1" }],
marketplaceProduct: { categories: ["template"] },
+ projectSettings: {
+ meta: { siteName: "Acme" },
+ compiler: { atomicStyles: true },
+ },
} as unknown as SnapshotBuildInput;
expect(
@@ -312,6 +315,7 @@ describe("api build snapshot", () => {
"resources",
"variables",
"breakpoints",
+ "projectSettings",
"marketplaceProduct",
]),
projectId: "project-1",
@@ -323,8 +327,10 @@ describe("api build snapshot", () => {
version: 7,
homePageId: build.pages.homePageId,
rootFolderId: build.pages.rootFolderId,
- meta: { siteName: "Acme" },
- compiler: { atomicStyles: true },
+ projectSettings: {
+ meta: { siteName: "Acme" },
+ compiler: { atomicStyles: true },
+ },
redirects: [{ old: "/old", new: "/new", status: "301" }],
resources: [{ id: "resource-1" }],
variables: [{ id: "variable-1" }],
diff --git a/apps/builder/app/services/api-build.server.ts b/apps/builder/app/services/api-build.server.ts
index d912606e73..6780f8afab 100644
--- a/apps/builder/app/services/api-build.server.ts
+++ b/apps/builder/app/services/api-build.server.ts
@@ -58,6 +58,7 @@ const buildInclude = z.enum([
"resources",
"variables",
"breakpoints",
+ "projectSettings",
"marketplaceProduct",
]);
@@ -100,13 +101,12 @@ export const createBuildSnapshot = ({
snapshot.homePageId = pages.homePageId;
snapshot.rootFolderId = pages.rootFolderId;
if (include.has("pages")) {
- snapshot.meta = pages.meta;
- snapshot.compiler = pages.compiler;
snapshot.redirects = pages.redirects;
}
add("pages", pages.pages);
add("folders", pages.folders);
}
+ add("projectSettings", build.projectSettings);
add("instances", build.instances);
add("props", build.props);
add("styles", build.styles);
diff --git a/apps/builder/app/services/api-compatibility.server.test.ts b/apps/builder/app/services/api-compatibility.server.test.ts
new file mode 100644
index 0000000000..f4bd12c7ac
--- /dev/null
+++ b/apps/builder/app/services/api-compatibility.server.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, test } from "vitest";
+import { getApiCompatibilityPayload } from "@webstudio-is/trpc-interface/api-compatibility";
+import { assertCliProjectSettingsContract } from "./api-compatibility.server";
+
+describe("API client compatibility", () => {
+ test("requires updated CLI clients when pages move to project settings", () => {
+ let error: unknown;
+ try {
+ assertCliProjectSettingsContract("cli", new Set(["pages"]));
+ } catch (caught) {
+ error = caught;
+ }
+
+ expect(getApiCompatibilityPayload(error)).toMatchObject({
+ reason: "clientVersionUnsupported",
+ target: "cli",
+ action: { type: "updateCli" },
+ });
+ });
+
+ test("accepts current CLI and non-CLI snapshot contracts", () => {
+ expect(() =>
+ assertCliProjectSettingsContract(
+ "cli",
+ new Set(["pages", "projectSettings"])
+ )
+ ).not.toThrow();
+ expect(() =>
+ assertCliProjectSettingsContract("browser", new Set(["pages"]))
+ ).not.toThrow();
+ });
+});
diff --git a/apps/builder/app/services/api-compatibility.server.ts b/apps/builder/app/services/api-compatibility.server.ts
new file mode 100644
index 0000000000..21902173f7
--- /dev/null
+++ b/apps/builder/app/services/api-compatibility.server.ts
@@ -0,0 +1,32 @@
+import { TRPCError } from "@trpc/server";
+import {
+ createApiCompatibilityPayload,
+ type ApiClient,
+ type ApiCompatibilityTarget,
+} from "@webstudio-is/trpc-interface/api-compatibility";
+
+export const throwApiClientUpdateRequired = (
+ target: ApiCompatibilityTarget
+): never => {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: "The API client must be updated before continuing.",
+ cause: createApiCompatibilityPayload({
+ reason: "clientVersionUnsupported",
+ target,
+ }),
+ });
+};
+
+export const assertCliProjectSettingsContract = (
+ client: ApiClient | "unknown" | undefined,
+ include: ReadonlySet<string>
+) => {
+ if (
+ client === "cli" &&
+ include.has("pages") &&
+ include.has("projectSettings") === false
+ ) {
+ throwApiClientUpdateRequired("cli");
+ }
+};
diff --git a/apps/builder/app/services/api-router.server.test.ts b/apps/builder/app/services/api-router.server.test.ts
index a76a8041fa..68cf914dce 100644
--- a/apps/builder/app/services/api-router.server.test.ts
+++ b/apps/builder/app/services/api-router.server.test.ts
@@ -698,6 +698,8 @@ describe("api instance queries", () => {
tag: "section",
depth: 1,
childCount: 1,
+ parentId: "root-1",
+ indexWithinParent: 0,
},
],
});
@@ -844,7 +846,8 @@ describe("api instance queries", () => {
{
id: "token-1",
name: "Primary",
- styles: { color: { type: "keyword", value: "red" } },
+ declarationCount: 1,
+ styles: undefined,
usageCount: 1,
},
],
diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.ts
index a044a05ea7..e93b46457e 100644
--- a/apps/builder/app/services/api-router.server.ts
+++ b/apps/builder/app/services/api-router.server.ts
@@ -55,6 +55,7 @@ import {
serializeProjectSummary,
} from "./api-build.server";
import { throwApiError } from "./api-errors.server";
+import { assertCliProjectSettingsContract } from "./api-compatibility.server";
import {
createBuilderRuntimeState,
executeApiRuntimeMutation,
@@ -594,6 +595,7 @@ export const apiRouter = router({
}
const include = new Set(input.include ?? []);
+ assertCliProjectSettingsContract(ctx.apiClient?.type, include);
const snapshot = createBuildSnapshot({
build,
include,
diff --git a/apps/builder/app/services/api-runtime.server.ts b/apps/builder/app/services/api-runtime.server.ts
index 9a5d04ea1f..b5e0a476e6 100644
--- a/apps/builder/app/services/api-runtime.server.ts
+++ b/apps/builder/app/services/api-runtime.server.ts
@@ -2,6 +2,7 @@ import type { CompactBuild } from "@webstudio-is/project-build";
import type { RuntimeOperationId } from "@webstudio-is/project-build/contracts/builder-runtime";
import { executeBuilderRuntimeOperation } from "@webstudio-is/project-build/runtime/registry";
import { BuilderRuntimeError } from "@webstudio-is/project-build/runtime/errors";
+import { builderRuntimeContext } from "@webstudio-is/project-build/runtime/context";
import { type BuilderRuntimeMutation } from "@webstudio-is/project-build/runtime/mutation";
import type { BuilderState } from "@webstudio-is/project-build/state/builder-state";
import { createBuilderStateFromCompactBuild } from "@webstudio-is/project-build/state/adapters";
@@ -32,6 +33,11 @@ export const executeApiRuntimeOperation = async <Result>({
id,
state: createBuilderRuntimeState(build, assets),
input,
+ context: {
+ createId: builderRuntimeContext.createId,
+ projectId: build.projectId,
+ projectVersion: build.version,
+ },
});
} catch (error) {
if (error instanceof BuilderRuntimeError) {
diff --git a/apps/builder/app/services/build-router.server.test.ts b/apps/builder/app/services/build-router.server.test.ts
index b0bd55025c..db5c4fd18e 100644
--- a/apps/builder/app/services/build-router.server.test.ts
+++ b/apps/builder/app/services/build-router.server.test.ts
@@ -1,14 +1,80 @@
import { afterEach, describe, expect, test, vi } from "vitest";
+import { bundleVersion } from "@webstudio-is/protocol";
import { createPublishedProjectBundleFixture } from "@webstudio-is/protocol/fixtures";
import { buildRouter, __testing__ } from "./build-router.server";
import { authorizeProject } from "@webstudio-is/trpc-interface/index.server";
+import { getApiCompatibilityPayload } from "@webstudio-is/trpc-interface/api-compatibility";
-const { createImportProjectBundleHandler } = __testing__;
+const {
+ assertCliBundleVersion,
+ createImportProjectBundleHandler,
+ prepareProjectBundleForClient,
+} = __testing__;
afterEach(() => {
vi.restoreAllMocks();
});
+describe("build router project bundle compatibility", () => {
+ test("requires the current bundle contract from CLI clients", () => {
+ const ctx = { apiClient: { type: "cli" } } as never;
+ let error: unknown;
+ try {
+ assertCliBundleVersion(ctx, undefined);
+ } catch (caught) {
+ error = caught;
+ }
+ expect(getApiCompatibilityPayload(error)).toMatchObject({
+ reason: "clientVersionUnsupported",
+ target: "cli",
+ action: { type: "updateCli" },
+ });
+ expect(() => assertCliBundleVersion(ctx, bundleVersion)).not.toThrow();
+ });
+
+ test("removes agent instructions from non-CLI bundles", async () => {
+ const bundle = createPublishedProjectBundleFixture({
+ build: {
+ projectSettings: {
+ meta: { siteName: "Acme", agentInstructions: "Internal guidance" },
+ compiler: {},
+ },
+ },
+ });
+
+ const result = await prepareProjectBundleForClient(
+ { apiClient: { type: "browser" } } as never,
+ bundle
+ );
+
+ expect(result.build.projectSettings?.meta).toEqual({ siteName: "Acme" });
+ expect(bundle.build.projectSettings?.meta.agentInstructions).toBe(
+ "Internal guidance"
+ );
+ });
+
+ test("keeps agent instructions for authorized CLI bundles", async () => {
+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
+ const bundle = createPublishedProjectBundleFixture({
+ build: {
+ projectSettings: {
+ meta: { agentInstructions: "Internal guidance" },
+ compiler: {},
+ },
+ },
+ });
+
+ const result = await prepareProjectBundleForClient(
+ { apiClient: { type: "cli" } } as never,
+ bundle
+ );
+
+ expect(result.build.projectSettings?.meta.agentInstructions).toBe(
+ "Internal guidance"
+ );
+ });
+});
+
describe("build router jsx fragment conversion", () => {
test("converts Webstudio JSX through the shared runtime converter", async () => {
vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
diff --git a/apps/builder/app/services/build-router.server.ts b/apps/builder/app/services/build-router.server.ts
index e1d399e8f0..82fb138574 100644
--- a/apps/builder/app/services/build-router.server.ts
+++ b/apps/builder/app/services/build-router.server.ts
@@ -26,8 +26,10 @@ import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";
import {
checkProjectBuildPermissionInput,
importProjectBundleInput,
+ bundleVersion,
publishedProjectBundle,
} from "@webstudio-is/protocol";
+import { removeAgentInstructionsFromProjectSettings } from "@webstudio-is/project-build/shared/project-settings";
import {
loadProjectBundleByBuildId,
loadPublishedProjectBundleByProjectId,
@@ -40,6 +42,54 @@ import {
readStagedUploadText,
removeStagedUpload,
} from "./staged-upload.server";
+import { throwApiClientUpdateRequired } from "./api-compatibility.server";
+
+const projectBundleInput = z.object({
+ projectId: z.string(),
+ bundleVersion: z.union([z.string(), z.number()]).optional(),
+});
+
+const buildBundleInput = z.object({
+ buildId: z.string(),
+ bundleVersion: z.union([z.string(), z.number()]).optional(),
+});
+
+const assertCliBundleVersion = (
+ ctx: AppContext,
+ clientBundleVersion: string | number | undefined
+) => {
+ if (ctx.apiClient?.type === "cli" && clientBundleVersion !== bundleVersion) {
+ throwApiClientUpdateRequired("cli");
+ }
+};
+
+const prepareProjectBundleForClient = async (
+ ctx: AppContext,
+ bundle: z.infer<typeof publishedProjectBundle>
+) => {
+ if (ctx.apiClient?.type === "cli") {
+ const canView = await authorizeProject.hasProjectPermit(
+ { projectId: bundle.build.projectId, permit: "view" },
+ ctx
+ );
+ if (canView === false) {
+ throw new AuthorizationError("You don't have access to this project");
+ }
+ return bundle;
+ }
+ return {
+ ...bundle,
+ build: {
+ ...bundle.build,
+ projectSettings:
+ bundle.build.projectSettings === undefined
+ ? undefined
+ : removeAgentInstructionsFromProjectSettings(
+ bundle.build.projectSettings
+ ),
+ },
+ };
+};
type ImportProjectBundleDependencies = {
importPublishedProjectBundle: typeof importPublishedProjectBundle;
@@ -207,15 +257,23 @@ export const buildRouter = router({
}),
loadProjectBundleByBuildId: procedure
- .input(z.object({ buildId: z.string() }))
+ .input(buildBundleInput)
.query(async ({ ctx, input }) => {
- return await loadProjectBundleByBuildId(input.buildId, ctx);
+ assertCliBundleVersion(ctx, input.bundleVersion);
+ return await prepareProjectBundleForClient(
+ ctx,
+ await loadProjectBundleByBuildId(input.buildId, ctx)
+ );
}),
loadProjectBundleByProjectId: procedure
- .input(z.object({ projectId: z.string() }))
+ .input(projectBundleInput)
.query(async ({ ctx, input }) => {
- return await loadPublishedProjectBundleByProjectId(input.projectId, ctx);
+ assertCliBundleVersion(ctx, input.bundleVersion);
+ return await prepareProjectBundleForClient(
+ ctx,
+ await loadPublishedProjectBundleByProjectId(input.projectId, ctx)
+ );
}),
checkProjectBuildPermission: procedure
@@ -330,4 +388,6 @@ export const buildRouter = router({
export const __testing__ = {
createImportProjectBundleHandler,
+ assertCliBundleVersion,
+ prepareProjectBundleForClient,
};
diff --git a/apps/builder/app/services/project-import.server.ts b/apps/builder/app/services/project-import.server.ts
index 5c76f4b8b2..838dbc42cd 100644
--- a/apps/builder/app/services/project-import.server.ts
+++ b/apps/builder/app/services/project-import.server.ts
@@ -5,9 +5,17 @@ import {
} from "@webstudio-is/trpc-interface/index.server";
import {
loadDevBuildByProjectId,
+ serializeConfig,
serializeData,
} from "@webstudio-is/project-build/index.server";
-import { migratePages } from "@webstudio-is/project-migrations/pages";
+import {
+ migratePages,
+ serializePages,
+} from "@webstudio-is/project-migrations/pages";
+import {
+ createProjectSettingsFromPages,
+ removeLegacyProjectSettingsFromPages,
+} from "@webstudio-is/project-build/shared/project-settings";
import { serializeStyles } from "@webstudio-is/project-build/styles.server";
import { serializeStyleSourceSelections } from "@webstudio-is/project-build/style-source-selections.server";
import {
@@ -73,22 +81,35 @@ const createBuildImportUpdate = ({
lastTransactionId: string;
updatedAt: string;
version: number;
-}) => ({
- version,
- lastTransactionId,
- updatedAt,
- pages: JSON.stringify(data.build.pages),
- breakpoints: serializeData<Breakpoint>(toMap(data.build.breakpoints)),
- styles: serializeStyles(toMap(data.build.styles)),
- styleSources: serializeData<StyleSource>(toMap(data.build.styleSources)),
- styleSourceSelections: serializeStyleSourceSelections(
- toMap(data.build.styleSourceSelections)
- ),
- props: serializeData<Prop>(toMap(data.build.props)),
- dataSources: serializeData<DataSource>(toMap(data.build.dataSources)),
- resources: serializeData<Resource>(toMap(data.build.resources)),
- instances: serializeData<Instance>(toMap(data.build.instances)),
-});
+}) => {
+ const pages = migratePages(data.build.pages);
+ const projectSettings =
+ data.build.projectSettings ?? createProjectSettingsFromPages(pages);
+ return {
+ version,
+ lastTransactionId,
+ updatedAt,
+ pages: JSON.stringify(
+ serializePages(removeLegacyProjectSettingsFromPages(pages))
+ ),
+ projectSettings: serializeConfig(projectSettings),
+ ...(data.build.marketplaceProduct === undefined
+ ? {}
+ : {
+ marketplaceProduct: serializeConfig(data.build.marketplaceProduct),
+ }),
+ breakpoints: serializeData<Breakpoint>(toMap(data.build.breakpoints)),
+ styles: serializeStyles(toMap(data.build.styles)),
+ styleSources: serializeData<StyleSource>(toMap(data.build.styleSources)),
+ styleSourceSelections: serializeStyleSourceSelections(
+ toMap(data.build.styleSourceSelections)
+ ),
+ props: serializeData<Prop>(toMap(data.build.props)),
+ dataSources: serializeData<DataSource>(toMap(data.build.dataSources)),
+ resources: serializeData<Resource>(toMap(data.build.resources)),
+ instances: serializeData<Instance>(toMap(data.build.instances)),
+ };
+};
const getImportedPreviewImageAssetId = (data: ProjectBundle) => {
const socialImageAssetId = getHomePage(migratePages(data.build.pages)).meta
diff --git a/apps/builder/app/shared/builder-data.ts b/apps/builder/app/shared/builder-data.ts
index 58a97b56ee..37aa6f6964 100644
--- a/apps/builder/app/shared/builder-data.ts
+++ b/apps/builder/app/shared/builder-data.ts
@@ -1,6 +1,9 @@
import { getStyleDeclKey, type WebstudioData } from "@webstudio-is/sdk";
import { migratePages } from "@webstudio-is/project-migrations/pages";
-import type { MarketplaceProduct } from "@webstudio-is/project-build";
+import {
+ type MarketplaceProduct,
+ type ProjectSettings,
+} from "@webstudio-is/project-build";
import type { Project } from "@webstudio-is/project";
import type { inferRouterOutputs } from "@trpc/server";
import type { AppRouter } from "~/services/trcp-router.server";
@@ -11,6 +14,7 @@ import {
$dataSources,
$instances,
$marketplaceProduct,
+ $projectSettings,
$pages,
$props,
$resources,
@@ -22,6 +26,7 @@ import { nativeClient } from "~/shared/trpc/trpc-client";
export type BuilderData = WebstudioData & {
marketplaceProduct: undefined | MarketplaceProduct;
+ projectSettings: ProjectSettings;
project: Project;
};
@@ -39,6 +44,10 @@ export const getBuilderData = (): BuilderData => {
if (project === undefined) {
throw Error(`Cannot get webstudio data with empty project`);
}
+ const projectSettings = $projectSettings.get();
+ if (projectSettings === undefined) {
+ throw Error(`Cannot get webstudio data with empty project settings`);
+ }
return {
pages,
project,
@@ -52,6 +61,7 @@ export const getBuilderData = (): BuilderData => {
styles: $styles.get(),
assets: $assets.get(),
marketplaceProduct: $marketplaceProduct.get(),
+ projectSettings,
};
};
@@ -76,6 +86,7 @@ export const loadBuilderData = async ({
{ projectId },
{ signal }
);
+ const pages = migratePages(data.pages);
return {
id: data.id,
version: data.version,
@@ -87,7 +98,7 @@ export const loadBuilderData = async ({
dataSources: hydrateIdMap(data.dataSources),
resources: hydrateIdMap(data.resources),
props: hydrateIdMap(data.props),
- pages: migratePages(data.pages),
+ pages,
breakpoints: hydrateIdMap(data.breakpoints),
styleSources: hydrateIdMap(data.styleSources),
styleSourceSelections: hydrateMap(
@@ -96,6 +107,7 @@ export const loadBuilderData = async ({
),
styles: hydrateMap(data.styles, (item) => getStyleDeclKey(item)),
marketplaceProduct: data.marketplaceProduct,
+ projectSettings: data.projectSettings,
};
} catch (error) {
const message =
diff --git a/apps/builder/app/shared/code-editor.tsx b/apps/builder/app/shared/code-editor.tsx
index 318731a860..aa46a6a64d 100644
--- a/apps/builder/app/shared/code-editor.tsx
+++ b/apps/builder/app/shared/code-editor.tsx
@@ -25,6 +25,7 @@ import {
completionKeymap,
} from "@codemirror/autocomplete";
import { html } from "@codemirror/lang-html";
+import { javascript } from "@codemirror/lang-javascript";
import { markdown } from "@codemirror/lang-markdown";
import { css } from "@webstudio-is/design-system";
import {
@@ -44,6 +45,13 @@ const wrapperStyle = css({
size: {
default: getCodeEditorCssVars({ minHeight: "160px", maxHeight: "320px" }),
small: getCodeEditorCssVars({ minHeight: "16px", maxHeight: "120px" }),
+ full: {
+ ...getCodeEditorCssVars({ minHeight: "100%", maxHeight: "100%" }),
+ height: "100%",
+ "& > div": { height: "100%" },
+ "& > div > div:first-child": { height: "100%" },
+ "& .cm-editor, & .cm-scroller": { height: "100%" },
+ },
},
},
defaultVariants: {
@@ -93,6 +101,16 @@ const getMarkdownExtensions = () => [
keymap.of(closeBracketsKeymap),
];
+const getJsonExtensions = () => [
+ highlightActiveLine(),
+ highlightSpecialChars(),
+ indentOnInput(),
+ javascript(),
+ bracketMatching(),
+ closeBrackets(),
+ keymap.of(closeBracketsKeymap),
+];
+
const cssPropertiesLanguage = LRLanguage.define({
name: "css",
parser: cssLanguage.configure({ top: "Styles" }).parser,
@@ -118,9 +136,9 @@ const getCssPropertiesExtensions = () => [
export const CodeEditor = forwardRef<
HTMLDivElement,
Omit<ComponentProps<typeof EditorContent>, "extensions"> & {
- lang?: "html" | "markdown" | "css-properties";
+ lang?: "html" | "json" | "markdown" | "css-properties";
title?: ReactNode;
- size?: "default" | "small";
+ size?: "default" | "small" | "full";
}
>(({ lang, title, size, ...editorContentProps }, ref) => {
const extensions = useMemo(() => {
@@ -132,6 +150,10 @@ export const CodeEditor = forwardRef<
return getMarkdownExtensions();
}
+ if (lang === "json") {
+ return getJsonExtensions();
+ }
+
if (lang === "css-properties") {
return getCssPropertiesExtensions();
}
diff --git a/apps/builder/app/shared/db/canvas.server.test.ts b/apps/builder/app/shared/db/canvas.server.test.ts
index 5e595c2904..c6864f5e1a 100644
--- a/apps/builder/app/shared/db/canvas.server.test.ts
+++ b/apps/builder/app/shared/db/canvas.server.test.ts
@@ -37,6 +37,7 @@ const createBundleBuild = (
description: "Description",
},
+ projectSettings: { meta: {}, compiler: {} },
...overrides,
};
};
diff --git a/apps/builder/app/shared/db/canvas.server.ts b/apps/builder/app/shared/db/canvas.server.ts
index 116ed0240e..6a32ee5209 100644
--- a/apps/builder/app/shared/db/canvas.server.ts
+++ b/apps/builder/app/shared/db/canvas.server.ts
@@ -74,6 +74,8 @@ const serializeProjectBundle = ({
dataSources: build.dataSources.map(getPair),
resources: build.resources.map(getPair),
instances: build.instances.map(getPair),
+ marketplaceProduct: build.marketplaceProduct,
+ projectSettings: build.projectSettings,
deployment: build.deployment,
},
page,
diff --git a/apps/builder/app/shared/instance-utils/data.test.tsx b/apps/builder/app/shared/instance-utils/data.test.tsx
index f89be928fe..f5f9d4bb28 100644
--- a/apps/builder/app/shared/instance-utils/data.test.tsx
+++ b/apps/builder/app/shared/instance-utils/data.test.tsx
@@ -15,6 +15,7 @@ import {
$dataSources,
$instances,
$pages,
+ $projectSettings,
$props,
$resources,
$styleSourceSelections,
@@ -52,6 +53,7 @@ const setBaseStores = () => {
$dataSources.set(new Map());
$resources.set(new Map());
$assets.set(new Map());
+ $projectSettings.set({ meta: {}, compiler: {} });
return { pages };
};
@@ -89,6 +91,7 @@ describe("data store helpers", () => {
$dataSources.set(new Map());
$resources.set(new Map());
$assets.set(new Map());
+ $projectSettings.set({ meta: {}, compiler: {} });
expect(getWebstudioData()).toMatchObject({
pages,
@@ -916,7 +919,9 @@ describe("data store helpers", () => {
});
test("executes project settings runtime mutations against builder stores", () => {
- setBaseStores();
+ const { pages } = setBaseStores();
+ const legacyMeta = pages.meta;
+ const legacyCompiler = pages.compiler;
executeRuntimeMutation({
id: "projectSettings.update",
@@ -930,16 +935,18 @@ describe("data store helpers", () => {
},
});
- expect($pages.get()?.meta).toEqual(
+ expect($projectSettings.get()?.meta).toEqual(
expect.objectContaining({
contactEmail: "[email protected]",
})
);
- expect($pages.get()?.compiler).toEqual(
+ expect($projectSettings.get()?.compiler).toEqual(
expect.objectContaining({
atomicStyles: true,
})
);
+ expect($pages.get()?.meta).toEqual(legacyMeta);
+ expect($pages.get()?.compiler).toEqual(legacyCompiler);
executeRuntimeMutation({
id: "projectSettings.update",
@@ -950,7 +957,8 @@ describe("data store helpers", () => {
},
});
- expect($pages.get()?.meta).not.toHaveProperty("contactEmail");
+ expect($projectSettings.get()?.meta).not.toHaveProperty("contactEmail");
+ expect($pages.get()?.meta).toEqual(legacyMeta);
});
test("runtime bridge skips page templates without build access", () => {
diff --git a/apps/builder/app/shared/instance-utils/data.ts b/apps/builder/app/shared/instance-utils/data.ts
index cfe42a7e6f..45d2cd8bbf 100644
--- a/apps/builder/app/shared/instance-utils/data.ts
+++ b/apps/builder/app/shared/instance-utils/data.ts
@@ -18,7 +18,9 @@ import {
$breakpoints,
$dataSources,
$instances,
+ $marketplaceProduct,
$pages,
+ $projectSettings,
$project,
$props,
$resources,
@@ -124,11 +126,12 @@ export const executeRuntimeMutationAsync = async <
return commitRuntimeMutation(result);
};
-export const getWebstudioData = (): WebstudioData => {
+export const getWebstudioData = () => {
const pages = $pages.get();
if (pages === undefined) {
throw Error(`Cannot get webstudio data with empty pages`);
}
+ const projectSettings = $projectSettings.get() ?? { meta: {}, compiler: {} };
return {
pages,
instances: $instances.get(),
@@ -140,5 +143,7 @@ export const getWebstudioData = (): WebstudioData => {
styleSources: $styleSources.get(),
styles: $styles.get(),
assets: $assets.get(),
+ marketplaceProduct: $marketplaceProduct.get(),
+ projectSettings,
};
};
diff --git a/apps/builder/app/shared/nano-states/project-settings.ts b/apps/builder/app/shared/nano-states/project-settings.ts
index 0baad19f22..fd499fb65b 100644
--- a/apps/builder/app/shared/nano-states/project-settings.ts
+++ b/apps/builder/app/shared/nano-states/project-settings.ts
@@ -2,6 +2,7 @@ import { atom } from "nanostores";
export type SectionName =
| "general"
+ | "agents"
| "auth"
| "redirects"
| "publish"
diff --git a/apps/builder/app/shared/project-settings/project-settings.tsx b/apps/builder/app/shared/project-settings/project-settings.tsx
index d2526ac8d5..f078214649 100644
--- a/apps/builder/app/shared/project-settings/project-settings.tsx
+++ b/apps/builder/app/shared/project-settings/project-settings.tsx
@@ -6,7 +6,7 @@ import {
DialogTitle,
Grid,
theme,
- ScrollArea,
+ ScrollAreaNative,
Flex,
List,
ListItem,
@@ -21,6 +21,7 @@ import {
import { $isDesignMode } from "~/shared/nano-states";
import { leftPanelWidth, rightPanelWidth } from "./utils";
import { SectionGeneral } from "./section-general";
+import { SectionAgents } from "./section-agents";
import { SectionAuth } from "./section-auth";
import { SectionRedirects } from "./section-redirects";
import { SectionPublish } from "./section-publish";
@@ -33,6 +34,7 @@ const sections = new Map<
FunctionComponent<{ projectId?: string }>
>([
["general", SectionGeneral],
+ ["agents", SectionAgents],
["redirects", SectionRedirects],
["publish", SectionPublish],
["marketplace", SectionMarketplace],
@@ -123,19 +125,25 @@ export const ProjectSettingsDialog = ({
})}
</Flex>
</List>
- <ScrollArea css={{ width: "100%" }}>
+ <ScrollAreaNative css={{ width: "100%" }}>
{status === "loading" ? (
<Flex justify="center" align="center" css={{ minHeight: 400 }}>
<SpinnerIcon size={rawTheme.spacing[15]} />
</Flex>
) : (
- <Grid gap={2} css={{ paddingBlock: theme.spacing[5] }}>
+ <Grid
+ gap={2}
+ css={{
+ paddingBlock: theme.spacing[5],
+ minHeight: currentSection === "agents" ? "100%" : undefined,
+ }}
+ >
{SectionComponent && (
<SectionComponent projectId={projectId} />
)}
</Grid>
)}
- </ScrollArea>
+ </ScrollAreaNative>
</Flex>
{/* Title is at the end intentionally,
* to make the close button last in the tab order
diff --git a/apps/builder/app/shared/project-settings/section-agents.tsx b/apps/builder/app/shared/project-settings/section-agents.tsx
new file mode 100644
index 0000000000..0f96cd871a
--- /dev/null
+++ b/apps/builder/app/shared/project-settings/section-agents.tsx
@@ -0,0 +1,48 @@
+import { useEffect, useState } from "react";
+import { useStore } from "@nanostores/react";
+import { Flex, Grid, Text, Tooltip } from "@webstudio-is/design-system";
+import { InfoCircleIcon } from "@webstudio-is/icons";
+import { CodeEditor } from "~/shared/code-editor";
+import { $projectSettings } from "~/shared/sync/data-stores";
+import { executeRuntimeMutation } from "~/shared/instance-utils/data";
+import { sectionSpacing } from "./utils";
+
+export const SectionAgents = () => {
+ const projectSettings = useStore($projectSettings);
+ const instructions = projectSettings?.meta.agentInstructions ?? "";
+ const [value, setValue] = useState(instructions);
+
+ useEffect(() => setValue(instructions), [instructions]);
+
+ return (
+ <Grid
+ gap={2}
+ css={{ height: "100%", gridTemplateRows: "auto minmax(0, 1fr)" }}
+ >
+ <Flex align="center" gap={1} css={sectionSpacing}>
+ <Text variant="titles">Agents</Text>
+ <Tooltip
+ variant="wrapped"
+ content="Give AI coding agents project-specific guidance. When you sync the project locally, Webstudio writes these instructions to a managed AGENTS.md in the project root. An existing user-owned AGENTS.md is never overwritten."
+ >
+ <InfoCircleIcon tabIndex={0} />
+ </Tooltip>
+ </Flex>
+ <Grid gap={1} css={{ ...sectionSpacing, minHeight: 0 }}>
+ <CodeEditor
+ title="Instructions"
+ lang="markdown"
+ size="full"
+ value={value}
+ onChange={setValue}
+ onChangeComplete={(agentInstructions) => {
+ executeRuntimeMutation({
+ id: "projectSettings.update",
+ input: { meta: { agentInstructions } },
+ });
+ }}
+ />
+ </Grid>
+ </Grid>
+ );
+};
diff --git a/apps/builder/app/shared/project-settings/section-auth.tsx b/apps/builder/app/shared/project-settings/section-auth.tsx
index d2d4dca74e..3f59b8aa5e 100644
--- a/apps/builder/app/shared/project-settings/section-auth.tsx
+++ b/apps/builder/app/shared/project-settings/section-auth.tsx
@@ -28,7 +28,7 @@ import {
} from "@webstudio-is/wsauth";
import { validateBasicAuthCredentials } from "@webstudio-is/project-build/runtime/auth";
import { $permissions } from "~/shared/nano-states";
-import { $pages } from "~/shared/sync/data-stores";
+import { $pages, $projectSettings } from "~/shared/sync/data-stores";
import { getExistingRoutePaths, sectionSpacing } from "./utils";
import { executeRuntimeMutation } from "~/shared/instance-utils/data";
import {
@@ -50,9 +50,10 @@ const saveAuthRoutes = (authRoutes: WsAuthRoute[]) => {
export const SectionAuth = () => {
const { allowAuth } = useStore($permissions);
const pages = useStore($pages);
+ const projectSettings = useStore($projectSettings);
const routeRef = useRef<HTMLInputElement>(null);
const [authRoutes, setAuthRoutes] = useState(() => {
- return parseProjectAuthRoutes($pages.get()?.meta?.auth).routes;
+ return parseProjectAuthRoutes($projectSettings.get()?.meta.auth).routes;
});
const [route, setRoute] = useState("");
const [login, setLogin] = useState("");
@@ -62,7 +63,7 @@ export const SectionAuth = () => {
const [passwordErrors, setPasswordErrors] = useState<string[]>([]);
const [searchQuery, setSearchQuery] = useState("");
- const authContent = pages?.meta?.auth;
+ const authContent = projectSettings?.meta.auth;
const parseResult = useMemo(() => {
return parseProjectAuthRoutes(authContent);
}, [authContent]);
diff --git a/apps/builder/app/shared/project-settings/section-general.tsx b/apps/builder/app/shared/project-settings/section-general.tsx
index c2356282c6..fc8246eaa0 100644
--- a/apps/builder/app/shared/project-settings/section-general.tsx
+++ b/apps/builder/app/shared/project-settings/section-general.tsx
@@ -23,7 +23,7 @@ import { validateContactEmail } from "@webstudio-is/project-build/runtime/projec
import { ImageControl } from "./image-control";
import { $assets, $project } from "~/shared/sync/data-stores";
import { $permissions } from "~/shared/nano-states";
-import { $pages } from "~/shared/sync/data-stores";
+import { $projectSettings } from "~/shared/sync/data-stores";
import { sectionSpacing } from "./utils";
import { CodeEditor } from "~/shared/code-editor";
import { CopyToClipboard } from "~/shared/copy-to-clipboard";
@@ -59,19 +59,21 @@ const saveSetting = <Name extends keyof ProjectMeta>(
export const SectionGeneral = ({ projectId }: { projectId?: string }) => {
const { maxContactEmailsPerProject } = useStore($permissions);
const allowContactEmail = maxContactEmailsPerProject > 0;
- const pages = useStore($pages);
+ const projectSettings = useStore($projectSettings);
const project = useStore($project);
const assets = useStore($assets);
- const [meta, setMeta] = useState(() => pages?.meta ?? defaultMetaSettings);
+ const [meta, setMeta] = useState(
+ () => projectSettings?.meta ?? defaultMetaSettings
+ );
const siteNameId = useId();
const contactEmailId = useId();
- // Update meta when pages data loads (important for dashboard mode)
+ // Update meta when project settings load (important for dashboard mode)
useEffect(() => {
- if (pages?.meta) {
- setMeta(pages.meta);
+ if (projectSettings?.meta) {
+ setMeta(projectSettings.meta);
}
- }, [pages?.meta]);
+ }, [projectSettings?.meta]);
const contactEmailError = validateContactEmail(
meta.contactEmail ?? "",
diff --git a/apps/builder/app/shared/project-settings/section-publish.tsx b/apps/builder/app/shared/project-settings/section-publish.tsx
index bd50f57b27..f18b1cafd1 100644
--- a/apps/builder/app/shared/project-settings/section-publish.tsx
+++ b/apps/builder/app/shared/project-settings/section-publish.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useStore } from "@nanostores/react";
import {
Grid,
Label,
@@ -7,7 +7,7 @@ import {
Text,
} from "@webstudio-is/design-system";
import type { CompilerSettings } from "@webstudio-is/sdk";
-import { $pages } from "~/shared/sync/data-stores";
+import { $projectSettings } from "~/shared/sync/data-stores";
import { useIds } from "~/shared/form-utils";
import { sectionSpacing } from "./utils";
import { executeRuntimeMutation } from "~/shared/instance-utils/data";
@@ -18,9 +18,8 @@ const defaultPublishSettings: CompilerSettings = {
export const SectionPublish = () => {
const ids = useIds(["atomicStyles"]);
- const [settings, setSettings] = useState(
- () => $pages.get()?.compiler ?? defaultPublishSettings
- );
+ const settings =
+ useStore($projectSettings)?.compiler ?? defaultPublishSettings;
const handleSave = (settings: CompilerSettings) => {
executeRuntimeMutation({
@@ -42,7 +41,6 @@ export const SectionPublish = () => {
onCheckedChange={(atomicStyles) => {
if (typeof atomicStyles === "boolean") {
const nextSettings = { ...settings, atomicStyles };
- setSettings(nextSettings);
handleSave(nextSettings);
}
}}
diff --git a/apps/builder/app/shared/sync/builder-patch.test.ts b/apps/builder/app/shared/sync/builder-patch.test.ts
index 6294ea0b0d..ef91f1af94 100644
--- a/apps/builder/app/shared/sync/builder-patch.test.ts
+++ b/apps/builder/app/shared/sync/builder-patch.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from "vitest";
import type { Instance, WebstudioData } from "@webstudio-is/sdk";
import { createDefaultPages } from "@webstudio-is/project-build";
+import type { ProjectSettings } from "@webstudio-is/project-build";
import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts/patch";
import {
createSyncChangesFromBuilderPatchPayload,
@@ -13,6 +14,7 @@ import {
$dataSources,
$instances,
$pages,
+ $projectSettings,
$props,
$resources,
$styleSourceSelections,
@@ -33,7 +35,9 @@ const createInstance = (
children,
});
-const createData = (): WebstudioData => ({
+type TestData = WebstudioData & { projectSettings: ProjectSettings };
+
+const createData = (): TestData => ({
pages: createDefaultPages({ rootInstanceId: "body" }),
instances: new Map([
["body", createInstance("body")],
@@ -48,9 +52,10 @@ const createData = (): WebstudioData => ({
styleSources: new Map(),
styles: new Map(),
assets: new Map(),
+ projectSettings: { meta: {}, compiler: {} },
});
-const setupStores = (data: WebstudioData) => {
+const setupStores = (data: TestData) => {
serverSyncStore.transactionManager.currentStack = [];
serverSyncStore.transactionManager.undoneStack = [];
serverSyncStore.popAll();
@@ -64,6 +69,7 @@ const setupStores = (data: WebstudioData) => {
$styleSources.set(data.styleSources);
$styles.set(data.styles);
$assets.set(data.assets);
+ $projectSettings.set(data.projectSettings);
};
describe("builder patch sync adapter", () => {
@@ -265,6 +271,36 @@ describe("builder patch sync adapter", () => {
]);
});
+ test("commits project settings through sync undo and redo", () => {
+ const data = createData();
+ data.projectSettings.meta.siteName = "Before";
+ setupStores(data);
+
+ createTransactionFromBuilderPatchPayload({
+ data,
+ payload: [
+ {
+ namespace: "projectSettings",
+ patches: [
+ {
+ op: "replace",
+ path: ["meta", "siteName"],
+ value: "After",
+ },
+ ],
+ },
+ ],
+ });
+
+ expect($projectSettings.get()?.meta.siteName).toBe("After");
+
+ serverSyncStore.undo();
+ expect($projectSettings.get()?.meta.siteName).toBe("Before");
+
+ serverSyncStore.redo();
+ expect($projectSettings.get()?.meta.siteName).toBe("After");
+ });
+
test("commits style source selection removals through sync undo and redo", () => {
const data = createData();
data.styleSourceSelections.set("card", {
diff --git a/apps/builder/app/shared/sync/builder-patch.ts b/apps/builder/app/shared/sync/builder-patch.ts
index 8367e0f98b..b1bbc60aa1 100644
--- a/apps/builder/app/shared/sync/builder-patch.ts
+++ b/apps/builder/app/shared/sync/builder-patch.ts
@@ -5,14 +5,23 @@ import type {
BuilderPatchChange,
} from "@webstudio-is/project-build/contracts/patch";
import type { WebstudioData } from "@webstudio-is/sdk";
+import type {
+ MarketplaceProduct,
+ ProjectSettings,
+} from "@webstudio-is/project-build";
import * as builderStatePatch from "@webstudio-is/project-build/state/patch";
import { serverSyncStore } from "./sync-stores";
+type BuilderPatchData = WebstudioData & {
+ marketplaceProduct?: MarketplaceProduct;
+ projectSettings?: ProjectSettings;
+};
+
const getNamespaceData = (
- data: WebstudioData,
+ data: BuilderPatchData,
namespace: BuilderPatchChange["namespace"]
) => {
- const namespaceData = data[namespace as keyof WebstudioData];
+ const namespaceData = data[namespace];
if (namespaceData !== undefined) {
return namespaceData;
}
@@ -20,7 +29,7 @@ const getNamespaceData = (
};
const applyBuilderPatchPayloadMutable = (
- data: WebstudioData,
+ data: BuilderPatchData,
payload: readonly BuilderPatchChange[]
) =>
builderStatePatch.applyBuilderPatchPayloadMutable(
@@ -91,7 +100,7 @@ export const createSyncChangesFromBuilderPatchPayload = ({
data,
payload,
}: {
- data: WebstudioData;
+ data: BuilderPatchData;
payload: BuilderPatchChange[];
}): Change[] => {
const payloadForReversePatches = payload.map((change) => ({
@@ -108,7 +117,7 @@ export const createTransactionFromBuilderPatchPayload = ({
data,
payload,
}: {
- data: WebstudioData;
+ data: BuilderPatchData;
payload: BuilderPatchChange[];
}) => {
serverSyncStore.createTransactionFromChanges(
diff --git a/apps/builder/app/shared/sync/data-stores.ts b/apps/builder/app/shared/sync/data-stores.ts
index f0d2c85b4b..2fae4cf5b2 100644
--- a/apps/builder/app/shared/sync/data-stores.ts
+++ b/apps/builder/app/shared/sync/data-stores.ts
@@ -17,7 +17,10 @@ import type {
StyleSourceSelections,
} from "@webstudio-is/sdk";
import type { Project } from "@webstudio-is/project";
-import type { MarketplaceProduct } from "@webstudio-is/project-build";
+import type {
+ MarketplaceProduct,
+ ProjectSettings,
+} from "@webstudio-is/project-build";
export const $project = atom<Project | undefined>();
@@ -58,6 +61,8 @@ export const $styles = atom<Styles>(new Map());
export const $marketplaceProduct = atom<undefined | MarketplaceProduct>();
+export const $projectSettings = atom<undefined | ProjectSettings>();
+
export const $publisherHost = atom<string>("wstd.work");
/**
@@ -77,6 +82,7 @@ const getInitialDataStoreValues = () => ({
styleSourceSelections: new Map(),
styles: new Map(),
marketplaceProduct: undefined,
+ projectSettings: undefined,
publisherHost: "wstd.work",
});
@@ -98,5 +104,6 @@ export const resetDataStores = () => {
$styleSourceSelections.set(initial.styleSourceSelections);
$styles.set(initial.styles);
$marketplaceProduct.set(initial.marketplaceProduct);
+ $projectSettings.set(initial.projectSettings);
$publisherHost.set(initial.publisherHost);
};
diff --git a/apps/builder/app/shared/sync/patch/patch-service.server.ts b/apps/builder/app/shared/sync/patch/patch-service.server.ts
index 69ce016142..4e86e1470d 100644
--- a/apps/builder/app/shared/sync/patch/patch-service.server.ts
+++ b/apps/builder/app/shared/sync/patch/patch-service.server.ts
@@ -36,6 +36,7 @@ const contentModeBuildColumns = [
const namespaceBuildColumns = {
pages: ["pages"],
+ projectSettings: ["projectSettings"],
breakpoints: ["breakpoints"],
instances: ["instances"],
props: ["props"],
diff --git a/apps/builder/app/shared/sync/sync-client.test.ts b/apps/builder/app/shared/sync/sync-client.test.ts
index 59e63b98a1..3422f32156 100644
--- a/apps/builder/app/shared/sync/sync-client.test.ts
+++ b/apps/builder/app/shared/sync/sync-client.test.ts
@@ -24,6 +24,7 @@ describe("getServerSyncState", () => {
resources: "resources",
assets: "assets",
marketplaceProduct: "marketplaceProduct",
+ projectSettings: "projectSettings",
} as unknown as LoadedBuilderData;
const serverSyncState = getServerSyncState(data);
@@ -41,6 +42,7 @@ describe("getServerSyncState", () => {
["dataSources", "dataSources"],
["resources", "resources"],
["assets", "assets"],
+ ["projectSettings", "projectSettings"],
["marketplaceProduct", "marketplaceProduct"],
])
);
diff --git a/apps/builder/app/shared/sync/sync-client.ts b/apps/builder/app/shared/sync/sync-client.ts
index e471db06aa..51e71bdf66 100644
--- a/apps/builder/app/shared/sync/sync-client.ts
+++ b/apps/builder/app/shared/sync/sync-client.ts
@@ -26,6 +26,7 @@ import {
$styleSourceSelections,
$styles,
$marketplaceProduct,
+ $projectSettings,
$publisherHost,
resetDataStores,
} from "./data-stores";
@@ -78,6 +79,7 @@ const applyBuilderData = (data: LoadedBuilderData) => {
$styleSourceSelections.set(data.styleSourceSelections);
$styles.set(data.styles);
$marketplaceProduct.set(data.marketplaceProduct);
+ $projectSettings.set(data.projectSettings);
};
const applyBuilderMetadata = (data: LoadedBuilderData) => {
diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.ts
index c9ed95a29c..2d0c461b8c 100644
--- a/apps/builder/app/shared/sync/sync-stores.ts
+++ b/apps/builder/app/shared/sync/sync-stores.ts
@@ -39,7 +39,10 @@ import {
$selectedInstanceOutlines,
$hoveredInstanceOutline,
} from "~/shared/nano-states";
-import { $marketplaceProduct } from "~/shared/sync/data-stores";
+import {
+ $marketplaceProduct,
+ $projectSettings,
+} from "~/shared/sync/data-stores";
import { $ephemeralStyles } from "~/canvas/stores";
import {
ImmerhinSyncObject,
@@ -96,6 +99,7 @@ const serverSyncStores = {
dataSources: $dataSources,
resources: $resources,
assets: $assets,
+ projectSettings: $projectSettings,
marketplaceProduct: $marketplaceProduct,
} as const;
diff --git a/apps/builder/e2e/README.md b/apps/builder/e2e/README.md
index dde602317d..d5e3030450 100644
--- a/apps/builder/e2e/README.md
+++ b/apps/builder/e2e/README.md
@@ -73,7 +73,9 @@ absorb occasional browser/backend flakes.
`pnpm e2e:builder:dev` defaults to `E2E_BUILDER_URL=https://127.0.0.1:3000`,
so it runs against the already-running Vite dev server instead of building and
serving the production bundle. Override `E2E_BUILDER_URL` when the dev server is
-running on another port.
+running on another port. The E2E harness maps `wstd.dev` and project subdomains
+to loopback for Chromium when this URL is loopback, so focused local runs do not
+require machine-level host-file edits.
The dev backend uses `E2E_DB_BOOTSTRAP=if-empty` and keeps Docker containers
running. The e2e runner still resets test data before each run.
diff --git a/apps/builder/e2e/fixtures/content-mode-project.ts b/apps/builder/e2e/fixtures/content-mode-project.ts
index 5a5e62ff0b..9a66643ff4 100644
--- a/apps/builder/e2e/fixtures/content-mode-project.ts
+++ b/apps/builder/e2e/fixtures/content-mode-project.ts
@@ -17,6 +17,7 @@ export type SeededContentModeProject = {
linkInstanceId: string;
imageInstanceId: string;
videoInstanceId: string;
+ assetTemplateImageAssetId: string;
assetTemplateImageName: string;
assetTemplateName: string;
assetTemplateImageAlt: string;
@@ -446,7 +447,7 @@ const createContentModeBuildData = ({
{ type: "text", value: "System resource variable configured" },
{
type: "expression",
- value: encodeDataSourceVariable(dataResourceSystemDataSourceId),
+ value: `${encodeDataSourceVariable(dataResourceSystemDataSourceId)}.data.year`,
},
],
},
@@ -968,6 +969,7 @@ export const prepareExistingContentModeProject = async ({
linkInstanceId,
imageInstanceId,
videoInstanceId,
+ assetTemplateImageAssetId: seededAssetTemplateImageAssetId,
assetTemplateImageName: seededAssetTemplateImageName,
assetTemplateName,
assetTemplateImageAlt,
diff --git a/apps/builder/e2e/flows/canvas-media.ts b/apps/builder/e2e/flows/canvas-media.ts
index 4af9ff8bc0..2a3849622e 100644
--- a/apps/builder/e2e/flows/canvas-media.ts
+++ b/apps/builder/e2e/flows/canvas-media.ts
@@ -15,6 +15,27 @@ export const waitForCanvasImage = async ({
});
};
+export const waitForCanvasImageCount = async ({
+ page,
+ alt,
+ count,
+}: {
+ page: Page;
+ alt: string;
+ count: number;
+}) => {
+ const canvas = await waitForCanvasFrame({ page });
+ const images = canvas.getByRole("img", { name: alt });
+ const startedAt = Date.now();
+ while (Date.now() - startedAt < 10_000) {
+ if ((await images.count()) === count) {
+ return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ throw new Error(`Expected ${count} images named ${JSON.stringify(alt)}.`);
+};
+
export const waitForCanvasImageSourceName = async ({
page,
sourceName,
diff --git a/apps/builder/e2e/flows/content-editing.ts b/apps/builder/e2e/flows/content-editing.ts
index 776b273d83..837d409b0e 100644
--- a/apps/builder/e2e/flows/content-editing.ts
+++ b/apps/builder/e2e/flows/content-editing.ts
@@ -184,3 +184,30 @@ export const replaceCanvasTextAndApplyInlineFormats = async ({
throw error;
}
};
+
+export const removeCanvasInlineLink = async ({
+ page,
+ text,
+}: {
+ page: Page;
+ text: string;
+}) => {
+ const { canvas, editable } = await startCanvasTextEditingByText({
+ page,
+ currentText: text,
+ });
+
+ await page.keyboard.press("ControlOrMeta+A");
+ await page.getByRole("button", { name: "Inline link", exact: true }).click();
+
+ const save = waitForChangeToBeSaved({ page });
+ try {
+ await canvas.locator("body").click({ position: { x: 1, y: 1 } });
+ await editable.waitFor({ state: "hidden", timeout: 1_000 });
+ await waitForCanvasText({ page, text });
+ await save;
+ } catch (error) {
+ await save.catch(() => undefined);
+ throw error;
+ }
+};
diff --git a/apps/builder/e2e/flows/data-variables.ts b/apps/builder/e2e/flows/data-variables.ts
new file mode 100644
index 0000000000..a33584e48b
--- /dev/null
+++ b/apps/builder/e2e/flows/data-variables.ts
@@ -0,0 +1,212 @@
+import { createServer } from "node:http";
+import type { Page } from "playwright";
+import { selectCanvasTextInstance } from "./canvas-selection";
+import { waitForChangeToBeSaved, waitForSyncStatus } from "./sync-status";
+
+const getVariableForm = (page: Page) =>
+ page
+ .locator("form")
+ .filter({ has: page.locator('input[name="name"]') })
+ .last();
+
+const closeVariablePanelAndWaitForSave = async ({ page }: { page: Page }) => {
+ const save = waitForChangeToBeSaved({ page });
+ await page.getByRole("button", { name: "Close" }).last().click();
+ await save;
+ await page
+ .getByText("New Variable", { exact: true })
+ .waitFor({ state: "hidden" });
+ await waitForSyncStatus({ page, status: "idle" });
+};
+
+const openNewVariablePanel = async ({ page }: { page: Page }) => {
+ await page.getByRole("tab", { name: "Settings" }).click();
+ await page.getByRole("button", { name: "Add data variable" }).click();
+ await page.getByText("New Variable", { exact: true }).waitFor();
+};
+
+const selectVariableType = async ({
+ page,
+ next,
+}: {
+ page: Page;
+ next: string;
+}) => {
+ await page
+ .getByText("Type", { exact: true })
+ .locator("xpath=following::button[1]")
+ .click();
+ await page
+ .getByRole("option", { name: new RegExp(`^${next}( Pro)?$`) })
+ .click();
+};
+
+const fillVariableName = async ({
+ page,
+ name,
+}: {
+ page: Page;
+ name: string;
+}) => {
+ await getVariableForm(page).locator('input[name="name"]').fill(name);
+};
+
+export const selectContentInstance = async ({ page }: { page: Page }) => {
+ await selectCanvasTextInstance({ page, text: "Initial content" });
+ await page
+ .getByText("No instance selected", { exact: true })
+ .waitFor({ state: "hidden" });
+ await page.getByRole("tab", { name: "Settings" }).click();
+ await page
+ .getByRole("button", { name: "Add data variable" })
+ .waitFor({ state: "visible" });
+};
+
+export const bindSelectedTextContentToExpression = async ({
+ page,
+ expression,
+}: {
+ page: Page;
+ expression: string;
+}) => {
+ await page.getByText("Text Content", { exact: true }).waitFor();
+ await page.getByText("Text Content", { exact: true }).hover();
+ await page
+ .getByText("Text Content", { exact: true })
+ .locator("xpath=following::button[@data-variant][1]")
+ .click();
+ const bindingDialog = page.getByRole("dialog", { name: "Binding" });
+ await bindingDialog.waitFor();
+
+ const expressionEditor = bindingDialog.locator(".cm-content").last();
+ await expressionEditor.click();
+ await page.keyboard.press("ControlOrMeta+A");
+ await page.keyboard.insertText(expression);
+
+ const save = waitForChangeToBeSaved({ page });
+ try {
+ await page.keyboard.press("ControlOrMeta+Enter");
+ await save;
+ } catch (error) {
+ const dialogText = await bindingDialog.innerText().catch(() => "");
+ throw new Error(
+ `Expected Text Content binding ${JSON.stringify(expression)} to save. Binding dialog: ${dialogText}`,
+ { cause: error }
+ );
+ }
+ await waitForSyncStatus({ page, status: "idle" });
+ await page.keyboard.press("Escape");
+};
+
+export const createHttpResourceVariable = async ({
+ page,
+ name,
+ url,
+}: {
+ page: Page;
+ name: string;
+ url: string;
+}) => {
+ await openNewVariablePanel({ page });
+ await fillVariableName({ page, name });
+ await selectVariableType({ page, next: "Resource" });
+ await page.getByRole("textbox", { name: "URL" }).fill(url);
+ await closeVariablePanelAndWaitForSave({ page });
+};
+
+export const createGraphqlResourceVariable = async ({
+ page,
+ name,
+ url,
+ query,
+}: {
+ page: Page;
+ name: string;
+ url: string;
+ query: string;
+}) => {
+ await openNewVariablePanel({ page });
+ await fillVariableName({ page, name });
+ await selectVariableType({ page, next: "GraphQL" });
+ await page.getByRole("textbox", { name: "URL" }).fill(url);
+ await page.getByRole("textbox", { name: "Query" }).fill(query);
+ await closeVariablePanelAndWaitForSave({ page });
+};
+
+export const createSystemResourceVariable = async ({
+ page,
+ name,
+ resource = "Sitemap",
+}: {
+ page: Page;
+ name: string;
+ resource?: "Sitemap" | "Current Date" | "Assets";
+}) => {
+ await openNewVariablePanel({ page });
+ await fillVariableName({ page, name });
+ await selectVariableType({ page, next: "System Resource" });
+ if (resource !== "Sitemap") {
+ await getVariableForm(page)
+ .getByText("Resource", { exact: true })
+ .locator("xpath=following::button[1]")
+ .click();
+ await page.getByRole("option", { name: resource, exact: true }).click();
+ }
+ await closeVariablePanelAndWaitForSave({ page });
+};
+
+export const startJsonResourceServer = async ({ title }: { title: string }) => {
+ const server = createServer((_request, response) => {
+ response.writeHead(200, {
+ "Access-Control-Allow-Origin": "*",
+ "Content-Type": "application/json",
+ });
+ response.end(JSON.stringify({ title }));
+ });
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", () => resolve());
+ });
+ const address = server.address();
+ if (address === null || typeof address === "string") {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ throw new Error("Expected a numeric local resource server port.");
+ }
+ return {
+ url: `http://127.0.0.1:${address.port}/posts`,
+ close: async () =>
+ await new Promise<void>((resolve) => server.close(() => resolve())),
+ };
+};
+
+export const startGraphqlResourceServer = async ({
+ title,
+}: {
+ title: string;
+}) => {
+ const server = createServer((request, response) => {
+ if (request.method !== "POST") {
+ response.writeHead(405).end();
+ return;
+ }
+ response.writeHead(200, {
+ "Access-Control-Allow-Origin": "*",
+ "Content-Type": "application/json",
+ });
+ response.end(JSON.stringify({ data: { post: { title } } }));
+ });
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", () => resolve());
+ });
+ const address = server.address();
+ if (address === null || typeof address === "string") {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ throw new Error("Expected a numeric local GraphQL server port.");
+ }
+ return {
+ url: `http://127.0.0.1:${address.port}/graphql`,
+ close: async () =>
+ await new Promise<void>((resolve) => server.close(() => resolve())),
+ };
+};
diff --git a/apps/builder/e2e/flows/generated-app.ts b/apps/builder/e2e/flows/generated-app.ts
index 6349dd1fc7..481946fba6 100644
--- a/apps/builder/e2e/flows/generated-app.ts
+++ b/apps/builder/e2e/flows/generated-app.ts
@@ -1,12 +1,15 @@
-import { execFile } from "node:child_process";
+import { execFile, spawn, type ChildProcess } from "node:child_process";
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { createServer } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
+import type { Page as PlaywrightPage } from "playwright";
import { bundleVersion } from "@webstudio-is/protocol";
import { getStyleDeclKey, type Page } from "@webstudio-is/sdk";
import { loadDevBuild } from "../db";
+import { stopChildProcess } from "../process";
const execFileAsync = promisify(execFile);
const cliLocalPath = fileURLToPath(
@@ -15,6 +18,55 @@ const cliLocalPath = fileURLToPath(
type BuildRow = Awaited<ReturnType<typeof loadDevBuild>>;
+const getAvailablePort = async () => {
+ const server = createServer();
+ server.unref();
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", () => resolve());
+ });
+ const address = server.address();
+ if (address === null || typeof address === "string") {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ throw new Error("Expected a numeric port for generated-app preview.");
+ }
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ return address.port;
+};
+
+const waitForGeneratedPreview = async ({
+ process,
+ url,
+ output,
+}: {
+ process: ChildProcess;
+ url: string;
+ output: () => string;
+}) => {
+ const deadline = Date.now() + 60_000;
+ while (Date.now() < deadline) {
+ if (process.exitCode !== null || process.signalCode !== null) {
+ throw new Error(
+ `Generated preview exited before it became ready at ${url}. Output:\n${output()}`
+ );
+ }
+ try {
+ const response = await fetch(url, {
+ signal: AbortSignal.timeout(2_000),
+ });
+ if (response.ok) {
+ return await response.text();
+ }
+ } catch {
+ // The generated production server is still starting.
+ }
+ await new Promise<void>((resolve) => setTimeout(resolve, 250));
+ }
+ throw new Error(
+ `Generated preview did not become ready at ${url}. Output:\n${output()}`
+ );
+};
+
const parseBuildField = <Value>(build: BuildRow, field: keyof BuildRow) =>
JSON.parse(String(build[field])) as Value;
@@ -84,7 +136,7 @@ export const expectGeneratedAppBuild = async ({
expectedText,
}: {
projectId: string;
- expectedText: string;
+ expectedText?: string;
}) => {
const tempDir = await mkdtemp(join(tmpdir(), "webstudio-e2e-generated-"));
try {
@@ -105,20 +157,177 @@ export const expectGeneratedAppBuild = async ({
}
);
- const generatedHome = await readFile(
- join(tempDir, "app", "__generated__", "_index.tsx"),
- "utf8"
- );
- if (generatedHome.includes(expectedText) === false) {
- throw new Error(
- `Expected generated home route to include "${expectedText}".`
+ if (expectedText !== undefined) {
+ const generatedHome = await readFile(
+ join(tempDir, "app", "__generated__", "_index.tsx"),
+ "utf8"
);
+ if (generatedHome.includes(expectedText) === false) {
+ throw new Error(
+ `Expected generated home route to include "${expectedText}".`
+ );
+ }
}
} finally {
await rm(tempDir, { recursive: true, force: true });
}
};
+const withGeneratedPreview = async <Result>({
+ projectId,
+ callback,
+}: {
+ projectId: string;
+ callback: ({ url, html }: { url: string; html: string }) => Promise<Result>;
+}) => {
+ const tempDir = await mkdtemp(join(tmpdir(), "webstudio-e2e-generated-"));
+ let preview: ChildProcess | undefined;
+ try {
+ const build = await loadDevBuild({ projectId });
+ await mkdir(join(tempDir, ".webstudio"), { recursive: true });
+ await writeFile(
+ join(tempDir, ".webstudio", "data.json"),
+ `${JSON.stringify(createLocalBundleFromDevBuild(build), undefined, 2)}\n`
+ );
+
+ const port = await getAvailablePort();
+ const output: string[] = [];
+ preview = spawn(
+ process.execPath,
+ [
+ cliLocalPath,
+ "preview",
+ "--assets",
+ "false",
+ "--template",
+ "defaults",
+ "--template",
+ "react-router",
+ "--host",
+ "127.0.0.1",
+ "--port",
+ String(port),
+ ],
+ {
+ cwd: tempDir,
+ detached: process.platform !== "win32",
+ stdio: ["ignore", "pipe", "pipe"],
+ env: { ...process.env, PWD: tempDir },
+ }
+ );
+ const appendOutput = (chunk: unknown) => {
+ output.push(String(chunk));
+ while (output.join("").length > 8_000) {
+ output.shift();
+ }
+ };
+ preview.stdout?.on("data", appendOutput);
+ preview.stderr?.on("data", appendOutput);
+
+ const url = `http://127.0.0.1:${port}/`;
+ const html = await waitForGeneratedPreview({
+ process: preview,
+ url,
+ output: () => output.join(""),
+ });
+ return await callback({ url, html });
+ } finally {
+ if (preview !== undefined) {
+ // The CLI starts npm and the generated server below it.
+ await stopChildProcess(preview, { killGroup: true });
+ }
+ await rm(tempDir, { recursive: true, force: true });
+ }
+};
+
+export const expectGeneratedAppToRender = async ({
+ projectId,
+ expectedText,
+ path = "/",
+}: {
+ projectId: string;
+ expectedText: string;
+ path?: string;
+}) => {
+ await withGeneratedPreview({
+ projectId,
+ callback: async ({ url, html }) => {
+ const response =
+ path === "/"
+ ? undefined
+ : await fetch(new URL(path, url), { redirect: "manual" });
+ const routeHtml = response === undefined ? html : await response.text();
+ if (
+ (response !== undefined && response.ok === false) ||
+ routeHtml.includes(expectedText) === false
+ ) {
+ throw new Error(
+ `Expected generated preview route ${JSON.stringify(path)} at ${url} to render ${JSON.stringify(expectedText)}.`
+ );
+ }
+ },
+ });
+};
+
+export const expectGeneratedAppRedirect = async ({
+ projectId,
+ path,
+ status,
+ location,
+}: {
+ projectId: string;
+ path: string;
+ status: number;
+ location: string;
+}) => {
+ await withGeneratedPreview({
+ projectId,
+ callback: async ({ url }) => {
+ const response = await fetch(new URL(path, url), {
+ redirect: "manual",
+ });
+ const actualLocation = response.headers.get("location");
+ if (response.status !== status || actualLocation !== location) {
+ throw new Error(
+ `Expected generated preview redirect ${JSON.stringify(path)} to return ${status} with location ${JSON.stringify(location)}. Received ${response.status} with location ${JSON.stringify(actualLocation)}.`
+ );
+ }
+ },
+ });
+};
+
+export const expectGeneratedAppNavigation = async ({
+ projectId,
+ page,
+ linkText,
+ targetPath,
+}: {
+ projectId: string;
+ page: PlaywrightPage;
+ linkText: string;
+ targetPath: string;
+}) => {
+ await withGeneratedPreview({
+ projectId,
+ callback: async ({ url }) => {
+ const targetUrl = new URL(targetPath, url).toString();
+ await page.goto(url);
+ await page.getByRole("link", { name: linkText, exact: true }).click();
+ await page.waitForURL(targetUrl);
+ const activeLink = page.getByRole("link", {
+ name: linkText,
+ exact: true,
+ });
+ const ariaCurrent = await activeLink.getAttribute("aria-current");
+ if (ariaCurrent !== "page") {
+ throw new Error(
+ `Expected generated preview link ${JSON.stringify(linkText)} to be active after navigating to ${JSON.stringify(targetPath)}. Received aria-current=${JSON.stringify(ariaCurrent)}.`
+ );
+ }
+ },
+ });
+};
+
export const expectGeneratedRedirects = async ({
projectId,
expectedRedirects,
diff --git a/apps/builder/e2e/flows/props-panel.ts b/apps/builder/e2e/flows/props-panel.ts
index d8c8bd6501..0346ab2da7 100644
--- a/apps/builder/e2e/flows/props-panel.ts
+++ b/apps/builder/e2e/flows/props-panel.ts
@@ -33,6 +33,26 @@ export const fillSelectedStringProperty = async ({
await save;
};
+export const fillSelectedNumberProperty = async ({
+ page,
+ label,
+ value,
+}: {
+ page: Page;
+ label: string;
+ value: number;
+}) => {
+ const propertyLabel = getPropertyLabel({ page, label });
+ await propertyLabel.waitFor({ state: "visible", timeout: 10_000 });
+ const input = getNumberPropertyInput({ page, label });
+ await input.waitFor({ state: "visible", timeout: 10_000 });
+
+ const save = waitForChangeToBeSaved({ page });
+ await input.fill(String(value));
+ await input.blur();
+ await save;
+};
+
export const chooseSelectedAssetProperty = async ({
page,
label,
@@ -85,6 +105,28 @@ const getPropertyInput = ({
? page.getByPlaceholder("https://www.url.com").first()
: page.locator("textarea").first();
+const getNumberPropertyInput = ({
+ page,
+ label,
+}: {
+ page: Page;
+ label: string;
+}) =>
+ getPropertyLabel({ page, label }).locator(
+ "xpath=ancestor::*[.//input[@type='number']][1]//input[@type='number']"
+ );
+
+const getBooleanPropertySwitch = ({
+ page,
+ label,
+}: {
+ page: Page;
+ label: string;
+}) =>
+ getPropertyLabel({ page, label }).locator(
+ "xpath=ancestor::*[.//*[@role='switch']][1]//*[@role='switch']"
+ );
+
export const waitForSelectedStringPropertyValue = async ({
page,
label,
@@ -116,3 +158,92 @@ export const waitForSelectedStringPropertyValue = async ({
`Expected selected property "${label}" to have value "${value}", received "${await input.inputValue()}"`
);
};
+
+export const waitForSelectedNumberPropertyValue = async ({
+ page,
+ label,
+ value,
+}: {
+ page: Page;
+ label: string;
+ value: number;
+}) => {
+ const propertyLabel = getPropertyLabel({ page, label });
+ await propertyLabel.waitFor({ state: "visible", timeout: 10_000 });
+ const input = getNumberPropertyInput({ page, label });
+ await input.waitFor({ state: "visible", timeout: 10_000 });
+ const expected = String(value);
+ const startedAt = Date.now();
+ while (Date.now() - startedAt < 10_000) {
+ if ((await input.inputValue()) === expected) {
+ return;
+ }
+ await new Promise<void>((resolve) => setTimeout(resolve, 100));
+ }
+
+ throw new Error(
+ `Expected selected number property "${label}" to have value "${expected}", received "${await input.inputValue()}"`
+ );
+};
+
+export const setSelectedBooleanProperty = async ({
+ page,
+ label,
+ checked,
+}: {
+ page: Page;
+ label: string;
+ checked: boolean;
+}) => {
+ const propertyLabel = getPropertyLabel({ page, label });
+ await propertyLabel.waitFor({ state: "visible", timeout: 10_000 });
+ const control = getBooleanPropertySwitch({ page, label });
+ await control.waitFor({ state: "visible", timeout: 10_000 });
+ if ((await control.getAttribute("aria-checked")) === String(checked)) {
+ return;
+ }
+
+ const save = waitForChangeToBeSaved({ page });
+ await control.click();
+ await save;
+};
+
+export const waitForSelectedBooleanPropertyValue = async ({
+ page,
+ label,
+ checked,
+}: {
+ page: Page;
+ label: string;
+ checked: boolean;
+}) => {
+ const propertyLabel = getPropertyLabel({ page, label });
+ await propertyLabel.waitFor({ state: "visible", timeout: 10_000 });
+ const control = getBooleanPropertySwitch({ page, label });
+ await control.waitFor({ state: "visible", timeout: 10_000 });
+ const expected = String(checked);
+ const startedAt = Date.now();
+ while (Date.now() - startedAt < 10_000) {
+ if ((await control.getAttribute("aria-checked")) === expected) {
+ return;
+ }
+ await new Promise<void>((resolve) => setTimeout(resolve, 100));
+ }
+
+ throw new Error(
+ `Expected selected boolean property "${label}" to be ${expected}, received "${await control.getAttribute("aria-checked")}"`
+ );
+};
+
+export const resetSelectedProperty = async ({
+ page,
+ label,
+}: {
+ page: Page;
+ label: string;
+}) => {
+ const propertyLabel = getPropertyLabel({ page, label });
+ const save = waitForChangeToBeSaved({ page });
+ await propertyLabel.click({ modifiers: ["Alt"] });
+ await save;
+};
diff --git a/apps/builder/e2e/harness.test.ts b/apps/builder/e2e/harness.test.ts
new file mode 100644
index 0000000000..dd31cebd5a
--- /dev/null
+++ b/apps/builder/e2e/harness.test.ts
@@ -0,0 +1,65 @@
+import type { Browser, BrowserContext, Page } from "playwright";
+import { expect, test, vi } from "vitest";
+import {
+ createBrowserScopeForBrowser,
+ getBrowserLaunchOptions,
+ newPage,
+} from "./harness";
+
+test("maps Builder and project wstd.dev hosts to loopback for local browser runs", () => {
+ expect(getBrowserLaunchOptions("https://127.0.0.1:5174")).toMatchObject({
+ args: [
+ "--host-resolver-rules=MAP wstd.dev 127.0.0.1,MAP *.wstd.dev 127.0.0.1",
+ ],
+ });
+});
+
+test("does not override host resolution for non-loopback Builder URLs", () => {
+ expect(getBrowserLaunchOptions("https://builder.example.com")).toEqual({});
+});
+
+test("keeps timed-out work on its closed context after a scope reset", async () => {
+ const contexts: Array<{
+ closed: boolean;
+ context: BrowserContext;
+ page: Page;
+ }> = [];
+ const browser = {
+ newContext: vi.fn(async () => {
+ const record = {
+ closed: false,
+ page: {} as Page,
+ context: undefined as unknown as BrowserContext,
+ };
+ record.context = {
+ newPage: vi.fn(async () => {
+ if (record.closed) {
+ throw new Error("context closed");
+ }
+ return record.page;
+ }),
+ close: vi.fn(async () => {
+ record.closed = true;
+ }),
+ } as unknown as BrowserContext;
+ contexts.push(record);
+ return record.context;
+ }),
+ } as Pick<Browser, "newContext">;
+ const scope = await createBrowserScopeForBrowser(browser);
+ let continueTimedOutWork: (() => void) | undefined;
+ const timedOutWork = scope.run(async () => {
+ await new Promise<void>((resolve) => {
+ continueTimedOutWork = resolve;
+ });
+ return await newPage();
+ });
+
+ await scope.reset();
+ continueTimedOutWork?.();
+
+ await expect(timedOutWork).rejects.toThrow("context closed");
+ await expect(scope.run(newPage)).resolves.toBe(contexts[1]?.page);
+ expect(contexts[0]?.closed).toBe(true);
+ await scope.close();
+});
diff --git a/apps/builder/e2e/harness.ts b/apps/builder/e2e/harness.ts
index 657255c7a5..1aa72e5883 100644
--- a/apps/builder/e2e/harness.ts
+++ b/apps/builder/e2e/harness.ts
@@ -1,10 +1,12 @@
import { parseBuilderUrl } from "@webstudio-is/protocol";
import { basename } from "node:path";
+import { AsyncLocalStorage } from "node:async_hooks";
import {
chromium,
type Browser,
type BrowserContext,
type BrowserContextOptions,
+ type LaunchOptions,
} from "playwright";
import env from "../app/env/env.server";
@@ -106,13 +108,42 @@ export const getSuites = () => suites;
let browser: Browser | undefined;
let context: BrowserContext | undefined;
+export type BrowserScope = {
+ run: <Result>(task: () => Promise<Result>) => Promise<Result>;
+ reset: () => Promise<void>;
+ close: () => Promise<void>;
+};
+
+type BrowserScopeState = {
+ context: BrowserContext;
+ isolatedContexts: Set<BrowserContext>;
+};
+
+const browserScopeStorage = new AsyncLocalStorage<BrowserScopeState>();
+
const browserContextOptions: BrowserContextOptions = {
ignoreHTTPSErrors: true,
permissions: ["clipboard-read", "clipboard-write"],
};
+const isLoopbackHost = (hostname: string) =>
+ hostname === "127.0.0.1" || hostname === "localhost" || hostname === "::1";
+
+export const getBrowserLaunchOptions = (url = builderUrl): LaunchOptions => {
+ const hostname = new URL(url).hostname;
+ if (isLoopbackHost(hostname) === false) {
+ return {};
+ }
+ return {
+ // Builder tests use project subdomains such as p-project-id.wstd.dev.
+ args: [
+ "--host-resolver-rules=MAP wstd.dev 127.0.0.1,MAP *.wstd.dev 127.0.0.1",
+ ],
+ };
+};
+
export const startBrowser = async () => {
- browser = await chromium.launch();
+ browser = await chromium.launch(getBrowserLaunchOptions());
context = await browser.newContext(browserContextOptions);
};
@@ -123,12 +154,53 @@ export const stopBrowser = async () => {
browser = undefined;
};
+export const createBrowserScopeForBrowser = async (
+ browserInstance: Pick<Browser, "newContext">
+): Promise<BrowserScope> => {
+ const createState = async (): Promise<BrowserScopeState> => {
+ return {
+ context: await browserInstance.newContext(browserContextOptions),
+ isolatedContexts: new Set(),
+ };
+ };
+ let state = await createState();
+ const closeState = async (target: BrowserScopeState) => {
+ await Promise.allSettled(
+ [...target.isolatedContexts].map((isolatedContext) =>
+ isolatedContext.close()
+ )
+ );
+ target.isolatedContexts.clear();
+ await target.context.close().catch(() => undefined);
+ };
+ return {
+ run: async (task) => {
+ const activeState = state;
+ return await browserScopeStorage.run(activeState, task);
+ },
+ reset: async () => {
+ const previousState = state;
+ await closeState(previousState);
+ state = await createState();
+ },
+ close: async () => await closeState(state),
+ };
+};
+
+export const createBrowserScope = async (): Promise<BrowserScope> => {
+ if (browser === undefined) {
+ throw new Error("Browser is not initialized");
+ }
+ return await createBrowserScopeForBrowser(browser);
+};
+
export const newPage = async () => {
- if (context === undefined) {
+ const activeContext = browserScopeStorage.getStore()?.context ?? context;
+ if (activeContext === undefined) {
throw new Error("Browser context is not initialized");
}
- return await context.newPage();
+ return await activeContext.newPage();
};
export const newIsolatedPage = async () => {
@@ -137,10 +209,13 @@ export const newIsolatedPage = async () => {
}
const isolatedContext = await browser.newContext(browserContextOptions);
+ const scope = browserScopeStorage.getStore();
+ scope?.isolatedContexts.add(isolatedContext);
return {
page: await isolatedContext.newPage(),
close: async () => {
+ scope?.isolatedContexts.delete(isolatedContext);
await isolatedContext.close();
},
};
diff --git a/apps/builder/e2e/process.test.ts b/apps/builder/e2e/process.test.ts
new file mode 100644
index 0000000000..c2f56399c3
--- /dev/null
+++ b/apps/builder/e2e/process.test.ts
@@ -0,0 +1,99 @@
+import { EventEmitter } from "node:events";
+import type { ChildProcess } from "node:child_process";
+import { expect, test, vi } from "vitest";
+import { stopChildProcess } from "./process";
+
+const createChild = () => {
+ const child = new EventEmitter() as ChildProcess;
+ Object.defineProperties(child, {
+ exitCode: { value: null, writable: true },
+ signalCode: { value: null, writable: true },
+ });
+ child.kill = vi.fn(() => true);
+ return child;
+};
+
+test("stops a child gracefully without escalating", async () => {
+ const child = createChild();
+ vi.mocked(child.kill).mockImplementation((signal) => {
+ Object.defineProperty(child, "signalCode", {
+ value: signal,
+ writable: true,
+ });
+ child.emit("exit", null, signal);
+ return true;
+ });
+
+ await stopChildProcess(child, { timeoutMs: 1 });
+
+ expect(child.kill).toHaveBeenCalledTimes(1);
+ expect(child.kill).toHaveBeenCalledWith("SIGTERM");
+});
+
+test("escalates a child that ignores SIGTERM", async () => {
+ const child = createChild();
+ vi.mocked(child.kill).mockImplementation((signal) => {
+ if (signal === "SIGKILL") {
+ Object.defineProperty(child, "signalCode", {
+ value: signal,
+ writable: true,
+ });
+ child.emit("exit", null, signal);
+ }
+ return true;
+ });
+
+ await stopChildProcess(child, { timeoutMs: 1 });
+
+ expect(child.kill).toHaveBeenNthCalledWith(1, "SIGTERM");
+ expect(child.kill).toHaveBeenNthCalledWith(2, "SIGKILL");
+});
+
+test("rejects when a child remains alive after SIGKILL", async () => {
+ const child = createChild();
+ Object.defineProperty(child, "pid", { value: 42 });
+
+ await expect(stopChildProcess(child, { timeoutMs: 1 })).rejects.toThrow(
+ "Child process 42 did not exit after SIGKILL"
+ );
+
+ expect(child.kill).toHaveBeenNthCalledWith(1, "SIGTERM");
+ expect(child.kill).toHaveBeenNthCalledWith(2, "SIGKILL");
+});
+
+test.runIf(process.platform !== "win32")(
+ "signals the detached process group used by generated previews",
+ async () => {
+ const child = createChild();
+ Object.defineProperty(child, "pid", { value: 42 });
+ let groupRunning = true;
+ const kill = vi
+ .spyOn(process, "kill")
+ .mockImplementation((_pid, signal) => {
+ if (signal === 0) {
+ if (groupRunning) {
+ return true;
+ }
+ throw Object.assign(new Error("Process group not found"), {
+ code: "ESRCH",
+ });
+ }
+ if (signal === "SIGKILL") {
+ groupRunning = false;
+ Object.defineProperty(child, "signalCode", {
+ value: signal,
+ writable: true,
+ });
+ child.emit("exit", null, signal);
+ }
+ return true;
+ });
+
+ await stopChildProcess(child, { killGroup: true, timeoutMs: 1 });
+
+ expect(kill).toHaveBeenCalledWith(-42, "SIGTERM");
+ expect(kill).toHaveBeenCalledWith(-42, "SIGKILL");
+ expect(child.kill).not.toHaveBeenCalled();
+ kill.mockRestore();
+ }
+);
diff --git a/apps/builder/e2e/process.ts b/apps/builder/e2e/process.ts
new file mode 100644
index 0000000000..6aae427a80
--- /dev/null
+++ b/apps/builder/e2e/process.ts
@@ -0,0 +1,70 @@
+import type { ChildProcess } from "node:child_process";
+
+const delay = (milliseconds: number) =>
+ new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
+
+const hasExited = (child: ChildProcess) =>
+ child.exitCode !== null || child.signalCode !== null;
+
+const isProcessGroupRunning = (pid: number) => {
+ try {
+ process.kill(-pid, 0);
+ return true;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ESRCH") {
+ return false;
+ }
+ throw error;
+ }
+};
+
+export const stopChildProcess = async (
+ child: ChildProcess,
+ {
+ killGroup = false,
+ timeoutMs = 5_000,
+ }: { killGroup?: boolean; timeoutMs?: number } = {}
+) => {
+ const usesProcessGroup =
+ killGroup && process.platform !== "win32" && child.pid !== undefined;
+ const isRunning = () =>
+ usesProcessGroup
+ ? isProcessGroupRunning(child.pid as number)
+ : hasExited(child) === false;
+ const waitUntilStopped = async () => {
+ const deadline = Date.now() + timeoutMs;
+ while (isRunning() && Date.now() < deadline) {
+ await delay(Math.min(25, Math.max(1, deadline - Date.now())));
+ }
+ return isRunning() === false;
+ };
+
+ if (isRunning() === false) {
+ return;
+ }
+ const sendSignal = (signal: NodeJS.Signals) => {
+ if (usesProcessGroup) {
+ try {
+ process.kill(-(child.pid as number), signal);
+ return;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ESRCH") {
+ return;
+ }
+ }
+ }
+ child.kill(signal);
+ };
+
+ sendSignal("SIGTERM");
+ if (await waitUntilStopped()) {
+ return;
+ }
+
+ sendSignal("SIGKILL");
+ if ((await waitUntilStopped()) === false) {
+ throw new Error(
+ `Child process${child.pid === undefined ? "" : ` ${child.pid}`} did not exit after SIGKILL`
+ );
+ }
+};
diff --git a/apps/builder/e2e/run-local.sh b/apps/builder/e2e/run-local.sh
index 7b93676520..c0f45e472c 100644
--- a/apps/builder/e2e/run-local.sh
+++ b/apps/builder/e2e/run-local.sh
@@ -106,8 +106,9 @@ install_playwright_chromium() {
esac
}
-build_builder_app() {
+build_e2e_apps() {
pnpm --dir "$ROOT_DIR" --filter=@webstudio-is/builder build
+ pnpm --dir "$ROOT_DIR" --filter=@webstudio-is/sdk-components-react-router build
}
run_builder_e2e_tests() {
@@ -154,8 +155,8 @@ if [ "$E2E_RUN_TESTS" = "true" ]; then
install_playwright_chromium
if [ "${E2E_BUILDER_URL:-}" = "" ]; then
- run_step "build builder app" "$E2E_BUILDER_BUILD_TIMEOUT_SECONDS" \
- build_builder_app
+ run_step "build builder and generated preview dependencies" "$E2E_BUILDER_BUILD_TIMEOUT_SECONDS" \
+ build_e2e_apps
fi
run_step "run builder e2e tests" "$E2E_TEST_COMMAND_TIMEOUT_SECONDS" \
diff --git a/apps/builder/e2e/run.ts b/apps/builder/e2e/run.ts
index 729636efe3..ca44ed9bc9 100644
--- a/apps/builder/e2e/run.ts
+++ b/apps/builder/e2e/run.ts
@@ -1,31 +1,23 @@
import { spawn, type ChildProcess } from "node:child_process";
import { setTimeout as delay } from "node:timers/promises";
+import { readdir } from "node:fs/promises";
+import { fileURLToPath } from "node:url";
import {
+ builderUrl,
+ createBrowserScope,
dashboardUrl,
getSuites,
newPage,
postgrestUrl,
startBrowser,
stopBrowser,
+ type BrowserScope,
} from "./harness";
import { resetDatabase } from "./db";
import { logPerf, measure, printPerfSummary } from "./perf";
-import "./tests/animation-runtime.[shard-1].e2e";
-import "./tests/content-mode-editing.[shard-1].e2e";
-import "./tests/content-mode-editing.[shard-2].e2e";
-import "./tests/content-mode-editing.[shard-3].e2e";
-import "./tests/data-variables-runtime.[shard-2].e2e";
-import "./tests/pages-actions.[shard-1].e2e";
-import "./tests/pages-actions.[shard-2].e2e";
-import "./tests/pages-actions.[shard-3].e2e";
-import "./tests/preview-links.[shard-1].e2e";
-import "./tests/project-settings-runtime.[shard-2].e2e";
-import "./tests/props-runtime.[shard-2].e2e";
-import "./tests/share-link-permissions.[shard-1].e2e";
-import "./tests/slot-keyboard.[shard-3].e2e";
-import "./tests/style-panel-runtime.[shard-1].e2e";
-import "./tests/style-panel-runtime.[shard-2].e2e";
-import "./tests/style-panel-runtime.[shard-3].e2e";
+import { getE2eTestModules } from "./test-modules";
+import { stopChildProcess } from "./process";
+import { runWithTimeout } from "./timeout";
const testTimeoutMs =
Number.parseInt(process.env.E2E_TEST_TIMEOUT_MS ?? "", 10) || 120_000;
@@ -40,6 +32,17 @@ const testFilters = [
: [process.env.E2E_TEST_FILTER]),
];
+// Shard ownership lives in filenames, so adding a test file requires no second
+// registry update and focused shards avoid unrelated fixture setup.
+const testModules = getE2eTestModules(
+ await readdir(fileURLToPath(new URL("./tests", import.meta.url))),
+ testShard
+);
+
+for (const module of testModules) {
+ await import(module);
+}
+
process.env.NODE_TLS_REJECT_UNAUTHORIZED ??= "0";
const waitForHttp = async (url: string, timeoutMs: number) => {
@@ -88,7 +91,7 @@ const waitForPostgrest = async () => {
const waitForBuilder = async (child: ChildProcess) => {
await Promise.race([
- waitForHttp(dashboardUrl, 60_000),
+ waitForHttp(builderUrl, 60_000),
new Promise<never>((_, reject) => {
child.once("exit", (code, signal) => {
reject(
@@ -113,27 +116,6 @@ const warmLoginRoute = async () => {
}
};
-const withTimeout = async <Result>(
- name: string,
- timeoutMs: number,
- task: () => Promise<Result>
-) => {
- let timeout: NodeJS.Timeout | undefined;
-
- try {
- return await Promise.race([
- task(),
- new Promise<never>((_, reject) => {
- timeout = setTimeout(() => {
- reject(new Error(`Timed out after ${timeoutMs}ms: ${name}`));
- }, timeoutMs);
- }),
- ]);
- } finally {
- clearTimeout(timeout);
- }
-};
-
const pipeBuilderOutput = (child: ChildProcess) => {
child.stdout?.on("data", (chunk) => {
process.stdout.write(`[builder] ${chunk}`);
@@ -146,28 +128,39 @@ const pipeBuilderOutput = (child: ChildProcess) => {
const runSuiteTests = async ({
suite,
tests,
+ browserScope,
+ onTimeout,
}: {
suite: ReturnType<typeof getSuites>[number];
tests: ReturnType<typeof getSuites>[number]["tests"];
+ browserScope: BrowserScope;
+ onTimeout: () => Promise<void>;
}) => {
try {
for (const test of tests) {
const startedAt = Date.now();
- await withTimeout(
- `${suite.name} › ${test.name}`,
- testTimeoutMs,
- async () => {
- await suite.beforeEach?.();
- await test.run();
- }
- );
+ await runWithTimeout({
+ name: `${suite.name} › ${test.name}`,
+ timeoutMs: testTimeoutMs,
+ onTimeout,
+ task: async () =>
+ await browserScope.run(async () => {
+ await suite.beforeEach?.();
+ await test.run();
+ }),
+ });
const duration = Date.now() - startedAt;
console.info(`✓ ${suite.name} › ${test.name} (${duration}ms)`);
}
} finally {
const afterAllStartedAt = Date.now();
- await withTimeout(`${suite.name} afterAll`, testTimeoutMs, async () => {
- await suite.afterAll?.();
+ await runWithTimeout({
+ name: `${suite.name} afterAll`,
+ timeoutMs: testTimeoutMs,
+ onTimeout,
+ task: async () => {
+ await browserScope.run(async () => await suite.afterAll?.());
+ },
});
logPerf(`${suite.name} afterAll`, afterAllStartedAt);
}
@@ -204,17 +197,10 @@ const startBuilder = async (): Promise<ChildProcess | undefined> => {
};
const stopBuilder = async (child: ChildProcess | undefined) => {
- if (child === undefined || child.killed) {
+ if (child === undefined) {
return;
}
-
- child.kill("SIGTERM");
- await Promise.race([
- new Promise<void>((resolve) => child.once("exit", () => resolve())),
- delay(5_000).then(() => {
- child.kill("SIGKILL");
- }),
- ]);
+ await stopChildProcess(child);
};
const getRunnableSuites = () => {
@@ -271,6 +257,7 @@ const run = async () => {
const totalStartedAt = Date.now();
const bootStartedAt = Date.now();
let builder: ChildProcess | undefined;
+ const browserScopes: BrowserScope[] = [];
try {
const runnableSuites = getRunnableSuites();
@@ -291,24 +278,50 @@ const run = async () => {
await measure("reset database", resetDatabase);
- for (const { suite } of runnableSuites) {
+ const scopedSuites = await Promise.all(
+ runnableSuites.map(async (runnableSuite) => {
+ const browserScope = await createBrowserScope();
+ browserScopes.push(browserScope);
+ return { ...runnableSuite, browserScope };
+ })
+ );
+ let resetAllBrowserScopesPromise: Promise<void> | undefined;
+ const resetAllBrowserScopes = () => {
+ resetAllBrowserScopesPromise ??= Promise.allSettled(
+ browserScopes.map((scope) => scope.reset())
+ ).then(() => undefined);
+ return resetAllBrowserScopesPromise;
+ };
+
+ for (const { suite, browserScope } of scopedSuites) {
const beforeAllStartedAt = Date.now();
- await withTimeout(`${suite.name} beforeAll`, testTimeoutMs, async () => {
- await suite.beforeAll?.();
+ await runWithTimeout({
+ name: `${suite.name} beforeAll`,
+ timeoutMs: testTimeoutMs,
+ onTimeout: resetAllBrowserScopes,
+ task: async () => {
+ await browserScope.run(async () => await suite.beforeAll?.());
+ },
});
logPerf(`${suite.name} beforeAll`, beforeAllStartedAt);
}
await Promise.all(
- runnableSuites.map(async ({ suite, tests }) => {
+ scopedSuites.map(async ({ suite, tests, browserScope }) => {
const suiteStartedAt = Date.now();
- await runSuiteTests({ suite, tests });
+ await runSuiteTests({
+ suite,
+ tests,
+ browserScope,
+ onTimeout: resetAllBrowserScopes,
+ });
const suiteDuration = Date.now() - suiteStartedAt;
console.info(`✓ ${suite.name} completed (${suiteDuration}ms)`);
})
);
logPerf("tests", testsStartedAt);
} finally {
+ await Promise.allSettled(browserScopes.map((scope) => scope.close()));
await stopBrowser();
await stopBuilder(builder);
logPerf("runner total", totalStartedAt);
diff --git a/apps/builder/e2e/schema/current.sql b/apps/builder/e2e/schema/current.sql
index 4c7bdbbf13..edda6ef144 100644
--- a/apps/builder/e2e/schema/current.sql
+++ b/apps/builder/e2e/schema/current.sql
@@ -207,6 +207,7 @@ BEGIN
resources,
instances,
"marketplaceProduct",
+ "projectSettings",
"publishStatus",
"projectId",
id,
@@ -225,6 +226,7 @@ BEGIN
resources,
instances,
"marketplaceProduct",
+ "projectSettings",
"publishStatus",
"projectId",
extensions.uuid_generate_v4() as id,
@@ -265,6 +267,7 @@ BEGIN
"dataSources" = '[]'::text,
resources = '[]'::text,
"marketplaceProduct" = '{}'::text,
+ "projectSettings" = '{"meta":{},"compiler":{}}'::text,
"isCleaned" = TRUE
WHERE deployment IS NOT NULL
AND id NOT IN (SELECT "buildId" FROM latest_builds)
@@ -436,6 +439,7 @@ CREATE TABLE public."Build" (
"lastTransactionId" text,
resources text DEFAULT '[]'::text NOT NULL,
"marketplaceProduct" text DEFAULT '{}'::text NOT NULL,
+ "projectSettings" text DEFAULT '{"meta":{},"compiler":{}}'::text NOT NULL,
"isCleaned" boolean DEFAULT false
);
@@ -679,7 +683,8 @@ BEGIN
"dataSources" = source."dataSources",
"resources" = source."resources",
"instances" = source."instances",
- "marketplaceProduct" = source."marketplaceProduct"
+ "marketplaceProduct" = source."marketplaceProduct",
+ "projectSettings" = source."projectSettings"
FROM (
SELECT * FROM "Build"
WHERE "projectId" = project_id AND "id" = from_build_id
diff --git a/apps/builder/e2e/test-modules.test.ts b/apps/builder/e2e/test-modules.test.ts
new file mode 100644
index 0000000000..6d5a1921f1
--- /dev/null
+++ b/apps/builder/e2e/test-modules.test.ts
@@ -0,0 +1,18 @@
+import { expect, test } from "vitest";
+import { getE2eTestModules } from "./test-modules";
+
+test("discovers every e2e module and filters ownership by shard tag", () => {
+ const files = [
+ "pages-drag.[shard-3].e2e.ts",
+ "navigator-drag.[shard-1].e2e.ts",
+ "helper.ts",
+ ];
+
+ expect(getE2eTestModules(files)).toEqual([
+ "./tests/navigator-drag.[shard-1].e2e.ts",
+ "./tests/pages-drag.[shard-3].e2e.ts",
+ ]);
+ expect(getE2eTestModules(files, "shard-3")).toEqual([
+ "./tests/pages-drag.[shard-3].e2e.ts",
+ ]);
+});
diff --git a/apps/builder/e2e/test-modules.ts b/apps/builder/e2e/test-modules.ts
new file mode 100644
index 0000000000..390a1cb101
--- /dev/null
+++ b/apps/builder/e2e/test-modules.ts
@@ -0,0 +1,12 @@
+export const getE2eTestModules = (
+ fileNames: readonly string[],
+ shard?: string
+) =>
+ fileNames
+ .filter((fileName) => fileName.endsWith(".e2e.ts"))
+ .filter(
+ (fileName) =>
+ shard === undefined || shard === "" || fileName.includes(`[${shard}]`)
+ )
+ .sort()
+ .map((fileName) => `./tests/${fileName}`);
diff --git a/apps/builder/e2e/tests/content-mode-editing.[shard-1].e2e.ts b/apps/builder/e2e/tests/content-mode-editing.[shard-1].e2e.ts
index 5e82314fb4..c99e7df1ce 100644
--- a/apps/builder/e2e/tests/content-mode-editing.[shard-1].e2e.ts
+++ b/apps/builder/e2e/tests/content-mode-editing.[shard-1].e2e.ts
@@ -9,6 +9,7 @@ import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
import {
selectCanvasImage,
waitForCanvasImage,
+ waitForCanvasImageCount,
waitForCanvasImageSourceName,
waitForCanvasVideoSource,
} from "../flows/canvas-media";
@@ -17,14 +18,19 @@ import {
waitForCanvasTextStyleCount,
} from "../flows/canvas-style";
import { chooseSelectedAssetProperty } from "../flows/props-panel";
-import { waitForSyncStatus } from "../flows/sync-status";
+import {
+ waitForChangeToBeSaved,
+ waitForSyncStatus,
+} from "../flows/sync-status";
import { insertTemplateAfterCanvasText } from "../flows/template-insertion";
import {
getSharedContentModeProject,
setupSharedContentModeProject,
+ createContentModeProject,
} from "../fixtures/content-mode-suite";
import { newIsolatedPage, test } from "../harness";
import { measure } from "../perf";
+import { loadDevBuild } from "../db";
test.beforeAll(async () => {
await setupSharedContentModeProject();
@@ -188,6 +194,13 @@ test("Editor can upload, replace, and delete asset in content mode", async () =>
let replacementAssetTitle = "";
await measure("content mode replace asset", async () => {
await openAssetDetails({ page, filename: uploadedAssetTitle });
+ const assetId = await page.locator("#asset-manager-id").inputValue();
+ if (assetId.length === 0) {
+ throw new Error(
+ "Expected Asset details to expose the uploaded asset id"
+ );
+ }
+ await page.getByText("0 uses", { exact: true }).waitFor();
replacementAssetTitle = await replaceSelectedAsset({
page,
filename: replacementFilename,
@@ -315,3 +328,109 @@ test("Editor can replace image source with asset in content mode", async () => {
await close();
}
});
+
+test("Builder copy/paste preserves image asset references after reload", async () => {
+ const fixture = await createContentModeProject({
+ email: "[email protected]",
+ title: "Asset Copy E2E",
+ assetNamePrefix: "asset-copy-",
+ editorToken: "asset-copy-e2e-editor-token",
+ builderToken: "asset-copy-e2e-builder-token",
+ });
+ const { page, close } = await newIsolatedPage();
+
+ const getImageAssetReferenceCount = async () => {
+ const build = await loadDevBuild({ projectId: fixture.projectId });
+ const props = JSON.parse(build.props) as Array<{
+ name: string;
+ type: string;
+ value: string;
+ }>;
+ const references = props.filter(
+ (prop) =>
+ prop.name === "src" &&
+ prop.type === "asset" &&
+ prop.value === fixture.assetTemplateImageAssetId
+ );
+ return references.length;
+ };
+
+ try {
+ await measure("asset copy open builder", async () => {
+ await openProjectBuilder({
+ page,
+ projectId: fixture.projectId,
+ authToken: fixture.editorToken,
+ mode: "content",
+ });
+ });
+ await waitForCanvasText({ page, text: "Initial content" });
+ const initialAssetReferenceCount = await getImageAssetReferenceCount();
+
+ await measure("asset copy insert template", async () => {
+ await insertTemplateAfterCanvasText({
+ page,
+ anchorText: "Initial content",
+ templateName: fixture.assetTemplateName,
+ });
+ });
+ await waitForCanvasImage({
+ page,
+ alt: fixture.assetTemplateImageAlt,
+ });
+ await measure("asset copy open build mode", async () => {
+ await openProjectBuilder({
+ page,
+ projectId: fixture.projectId,
+ authToken: fixture.builderToken,
+ });
+ });
+ await waitForCanvasImage({
+ page,
+ alt: fixture.assetTemplateImageAlt,
+ });
+ await selectCanvasImage({
+ page,
+ alt: fixture.assetTemplateImageAlt,
+ });
+ await page.keyboard.press("ControlOrMeta+C");
+ const save = waitForChangeToBeSaved({ page });
+ await page.keyboard.press("ControlOrMeta+V");
+ await save;
+ await waitForSyncStatus({ page, status: "idle" });
+ await waitForCanvasImageCount({
+ page,
+ alt: fixture.assetTemplateImageAlt,
+ count: 2,
+ });
+ if (
+ (await getImageAssetReferenceCount()) !==
+ initialAssetReferenceCount + 2
+ ) {
+ throw new Error(
+ "Expected insertion and paste to add two asset references."
+ );
+ }
+
+ await measure("asset copy reload builder", async () => {
+ await openProjectBuilder({
+ page,
+ projectId: fixture.projectId,
+ authToken: fixture.builderToken,
+ });
+ });
+ await waitForCanvasImageCount({
+ page,
+ alt: fixture.assetTemplateImageAlt,
+ count: 2,
+ });
+ if (
+ (await getImageAssetReferenceCount()) !==
+ initialAssetReferenceCount + 2
+ ) {
+ throw new Error("Expected reload to preserve copied asset references.");
+ }
+ } finally {
+ await close();
+ }
+});
diff --git a/apps/builder/e2e/tests/content-mode-editing.[shard-2].e2e.ts b/apps/builder/e2e/tests/content-mode-editing.[shard-2].e2e.ts
index 949666ba32..57b1c98210 100644
--- a/apps/builder/e2e/tests/content-mode-editing.[shard-2].e2e.ts
+++ b/apps/builder/e2e/tests/content-mode-editing.[shard-2].e2e.ts
@@ -16,11 +16,14 @@ import {
} from "../flows/canvas-media";
import {
pasteCanvasText,
+ removeCanvasInlineLink,
replaceCanvasText,
replaceCanvasTextAndApplyInlineFormats,
} from "../flows/content-editing";
import {
+ fillSelectedNumberProperty,
fillSelectedStringProperty,
+ waitForSelectedNumberPropertyValue,
waitForSelectedStringPropertyValue,
} from "../flows/props-panel";
import {
@@ -83,6 +86,63 @@ const getElementTagWithTextCount = async ({
).length;
};
+const getElementHrefWithText = async ({
+ projectId,
+ text,
+}: {
+ projectId: string;
+ text: string;
+}) => {
+ const build = await loadDevBuild({ projectId });
+ const instances = JSON.parse(build.instances) as Array<{
+ id: string;
+ tag?: string;
+ children?: Array<{ type: string; value?: string }>;
+ }>;
+ const props = JSON.parse(build.props) as Array<{
+ instanceId: string;
+ name: string;
+ type: string;
+ value: unknown;
+ }>;
+ const instancesById = new Map(
+ instances.map((instance) => [instance.id, instance])
+ );
+
+ const instanceContainsText = (instanceId: string): boolean => {
+ const instance = instancesById.get(instanceId);
+ if (instance === undefined) {
+ return false;
+ }
+ return (
+ instance.children?.some((child) => {
+ if (child.type === "text") {
+ return child.value?.includes(text);
+ }
+ return (
+ child.type === "id" &&
+ child.value !== undefined &&
+ instanceContainsText(child.value)
+ );
+ }) ?? false
+ );
+ };
+
+ const link = instances.find(
+ (instance) => instance.tag === "a" && instanceContainsText(instance.id)
+ );
+ if (link === undefined) {
+ throw new Error(`Expected a link containing "${text}"`);
+ }
+ const href = props.find(
+ (prop) => prop.instanceId === link.id && prop.name === "href"
+ );
+ if (href?.type !== "string" || typeof href.value !== "string") {
+ throw new Error(`Expected a static href for link containing "${text}"`);
+ }
+ return href.value;
+};
+
const undoShortcut = async ({ page }: { page: Page }) => {
await page.keyboard.press("ControlOrMeta+Z");
await waitForSyncStatus({ page, status: "idle" });
@@ -207,6 +267,7 @@ test("Editor can edit text and content props but not design props", async () =>
const editedImageSrc =
"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='80'%3E%3Crect width='120' height='80' fill='%23dff7e8'/%3E%3C/svg%3E";
const editedImageAlt = "Edited image alt";
+ const editedImageWidth = 240;
const editedVideoSrc = "https://example.com/edited-video.mp4";
const editedContent = "Edited isolated content";
const { page, close } = await newIsolatedPage();
@@ -299,6 +360,11 @@ test("Editor can edit text and content props but not design props", async () =>
control: "text",
value: editedImageAlt,
});
+ await fillSelectedNumberProperty({
+ page,
+ label: "Width",
+ value: editedImageWidth,
+ });
await selectCanvasVideoSource({
page,
@@ -354,6 +420,11 @@ test("Editor can edit text and content props but not design props", async () =>
control: "text",
value: editedImageAlt,
});
+ await waitForSelectedNumberPropertyValue({
+ page,
+ label: "Width",
+ value: editedImageWidth,
+ });
await selectCanvasVideoSource({
page,
@@ -414,6 +485,7 @@ test("Editor can paste text while editing canvas content", async () => {
test("Editor rich text formatting persists after reload", async () => {
const fixture = getSharedContentModeProject();
const formattedText = "Rich editor formatted copy";
+ const editedHref = "/rich-text-editor-link";
const { page, close } = await newIsolatedPage();
try {
@@ -436,7 +508,7 @@ test("Editor rich text formatting persists after reload", async () => {
page,
currentText: fixture.shareLinkEditableText,
text: formattedText,
- formats: ["Bold", "Italic"],
+ formats: ["Bold", "Italic", "Inline link"],
});
});
await waitForCanvasText({ page, text: formattedText });
@@ -451,9 +523,14 @@ test("Editor rich text formatting persists after reload", async () => {
tag: "i",
text: formattedText,
});
- if (boldCount !== 1 || italicCount !== 1) {
+ const linkCount = await getElementTagWithTextCount({
+ projectId: fixture.projectId,
+ tag: "a",
+ text: formattedText,
+ });
+ if (boldCount !== 1 || italicCount !== 1 || linkCount !== 1) {
throw new Error(
- `Expected rich text editor to persist one bold and one italic formatted subtree. bold=${boldCount}, italic=${italicCount}`
+ `Expected rich text editor to persist one bold, italic, and inline link subtree. bold=${boldCount}, italic=${italicCount}, link=${linkCount}`
);
}
@@ -467,6 +544,27 @@ test("Editor rich text formatting persists after reload", async () => {
});
await waitForCanvasText({ page, text: formattedText });
+ await selectCanvasTextInstanceForProps({
+ page,
+ text: formattedText,
+ propertyLabel: "Href",
+ });
+ await fillSelectedStringProperty({
+ page,
+ label: "Href",
+ control: "url",
+ value: editedHref,
+ });
+ const savedHref = await getElementHrefWithText({
+ projectId: fixture.projectId,
+ text: formattedText,
+ });
+ if (savedHref !== editedHref) {
+ throw new Error(
+ `Expected rich-text link href to be saved as "${editedHref}", received "${savedHref}"`
+ );
+ }
+
await measure("content mode reload rich text formatting", async () => {
await openProjectBuilder({
page,
@@ -476,6 +574,15 @@ test("Editor rich text formatting persists after reload", async () => {
});
});
await waitForCanvasText({ page, text: formattedText });
+ const reloadedHref = await getElementHrefWithText({
+ projectId: fixture.projectId,
+ text: formattedText,
+ });
+ if (reloadedHref !== editedHref) {
+ throw new Error(
+ `Expected reloaded rich-text link href to be "${editedHref}", received "${reloadedHref}"`
+ );
+ }
const reloadedBoldCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
@@ -487,9 +594,50 @@ test("Editor rich text formatting persists after reload", async () => {
tag: "i",
text: formattedText,
});
- if (reloadedBoldCount !== 1 || reloadedItalicCount !== 1) {
+ const reloadedLinkCount = await getElementTagWithTextCount({
+ projectId: fixture.projectId,
+ tag: "a",
+ text: formattedText,
+ });
+ if (
+ reloadedBoldCount !== 1 ||
+ reloadedItalicCount !== 1 ||
+ reloadedLinkCount !== 1
+ ) {
+ throw new Error(
+ `Expected reloaded rich text formatting to persist. bold=${reloadedBoldCount}, italic=${reloadedItalicCount}, link=${reloadedLinkCount}`
+ );
+ }
+
+ await removeCanvasInlineLink({ page, text: formattedText });
+ const removedLinkCount = await getElementTagWithTextCount({
+ projectId: fixture.projectId,
+ tag: "a",
+ text: formattedText,
+ });
+ if (removedLinkCount !== 0) {
+ throw new Error(
+ `Expected rich-text link removal to delete the inline link subtree, received ${removedLinkCount} link instances`
+ );
+ }
+
+ await measure("content mode reload rich text link removal", async () => {
+ await openProjectBuilder({
+ page,
+ projectId: fixture.projectId,
+ authToken: fixture.editorToken,
+ mode: "content",
+ });
+ });
+ await waitForCanvasText({ page, text: formattedText });
+ const reloadedRemovedLinkCount = await getElementTagWithTextCount({
+ projectId: fixture.projectId,
+ tag: "a",
+ text: formattedText,
+ });
+ if (reloadedRemovedLinkCount !== 0) {
throw new Error(
- `Expected reloaded rich text formatting to persist. bold=${reloadedBoldCount}, italic=${reloadedItalicCount}`
+ `Expected rich-text link removal to persist after reload, received ${reloadedRemovedLinkCount} link instances`
);
}
} finally {
diff --git a/apps/builder/e2e/tests/data-variables-runtime.[shard-2].e2e.ts b/apps/builder/e2e/tests/data-variables-runtime.[shard-2].e2e.ts
index ca3f667e67..000ff08420 100644
--- a/apps/builder/e2e/tests/data-variables-runtime.[shard-2].e2e.ts
+++ b/apps/builder/e2e/tests/data-variables-runtime.[shard-2].e2e.ts
@@ -1,13 +1,19 @@
import type { Page } from "playwright";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
-import { selectCanvasTextInstance } from "../flows/canvas-selection";
+import {
+ bindSelectedTextContentToExpression,
+ createGraphqlResourceVariable,
+ createHttpResourceVariable,
+ createSystemResourceVariable,
+ selectContentInstance,
+} from "../flows/data-variables";
import {
waitForChangeToBeSaved,
waitForSyncStatus,
} from "../flows/sync-status";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { loginWithSecret } from "../flows/dashboard";
-import { expectGeneratedAppBuild } from "../flows/generated-app";
+import { expectGeneratedAppToRender } from "../flows/generated-app";
import { newIsolatedPage, test } from "../harness";
import { measure } from "../perf";
import { loadDevBuild } from "../db";
@@ -45,22 +51,6 @@ const getDataVariableRuntimeState = async (fixture: { projectId: string }) => {
};
};
-const selectVariableType = async ({
- page,
- next,
-}: {
- page: Page;
- next: string;
-}) => {
- await page
- .getByText("Type", { exact: true })
- .locator("xpath=following::button[1]")
- .click();
- await page
- .getByRole("option", { name: new RegExp(`^${next}( Pro)?$`) })
- .click();
-};
-
const getVariableForm = (page: Page) =>
page
.locator("form")
@@ -108,17 +98,6 @@ const openNewVariablePanel = async ({ page }: { page: Page }) => {
await page.getByText("New Variable", { exact: true }).waitFor();
};
-const selectContentInstance = async ({ page }: { page: Page }) => {
- await selectCanvasTextInstance({ page, text: "Initial content" });
- await page
- .getByText("No instance selected", { exact: true })
- .waitFor({ state: "hidden" });
- await page.getByRole("tab", { name: "Settings" }).click();
- await page
- .getByRole("button", { name: "Add data variable" })
- .waitFor({ state: "visible" });
-};
-
const createStringVariable = async ({
page,
name,
@@ -175,50 +154,6 @@ const deleteVariable = async ({
await waitForSyncStatus({ page, status: "idle" });
};
-const bindSelectedTextContentToExpression = async ({
- page,
- expression,
-}: {
- page: Page;
- expression: string;
-}) => {
- await page.getByText("Text Content", { exact: true }).waitFor();
- await page.getByText("Text Content", { exact: true }).hover();
- await page
- .getByText("Text Content", { exact: true })
- .locator("xpath=following::button[@data-variant][1]")
- .click();
- const bindingDialog = page.getByRole("dialog", { name: "Binding" });
- await bindingDialog.waitFor();
-
- const expressionEditor = bindingDialog.locator(".cm-content").last();
- await expressionEditor.click();
- await page.keyboard.press("ControlOrMeta+A");
- await page.keyboard.type(expression);
-
- const save = waitForChangeToBeSaved({ page });
- await page.keyboard.press("ControlOrMeta+Enter");
- await save;
- await waitForSyncStatus({ page, status: "idle" });
- await page.keyboard.press("Escape");
-};
-
-const createHttpResourceVariable = async ({
- page,
- name,
- url,
-}: {
- page: Page;
- name: string;
- url: string;
-}) => {
- await openNewVariablePanel({ page });
- await fillVariableName({ page, name });
- await selectVariableType({ page, next: "Resource" });
- await page.getByRole("textbox", { name: "URL" }).fill(url);
- await closeVariablePanelAndWaitForSave({ page });
-};
-
const editHttpResourceVariableWithCurl = async ({
page,
fixture,
@@ -237,41 +172,6 @@ const editHttpResourceVariableWithCurl = async ({
await closeVariablePanelAndWaitForSave({ page });
};
-const createGraphqlResourceVariable = async ({
- page,
- name,
- url,
- query,
-}: {
- page: Page;
- name: string;
- url: string;
- query: string;
-}) => {
- await openNewVariablePanel({ page });
- await fillVariableName({ page, name });
- await selectVariableType({ page, next: "GraphQL" });
- await page.getByRole("textbox", { name: "URL" }).fill(url);
- await page.getByRole("textbox", { name: "Query" }).fill(query);
- await closeVariablePanelAndWaitForSave({ page });
-};
-
-const createSystemResourceVariable = async ({
- page,
- name,
-}: {
- page: Page;
- name: string;
-}) => {
- await openNewVariablePanel({ page });
- await fillVariableName({ page, name });
- await selectVariableType({
- page,
- next: "System Resource",
- });
- await closeVariablePanelAndWaitForSave({ page });
-};
-
const expectVariableListItem = async ({
page,
name,
@@ -281,8 +181,14 @@ const expectVariableListItem = async ({
name: string;
badge: "Static variable" | "Dynamic data variable";
}) => {
- await page.getByText(name, { exact: true }).waitFor({ state: "visible" });
- await page.getByLabel(badge).first().waitFor({ state: "visible" });
+ const itemButton = page
+ .getByText(name, { exact: true })
+ .locator("xpath=ancestor::button[@data-id][1]");
+ await itemButton.waitFor({ state: "visible" });
+ await itemButton
+ .locator("xpath=parent::*")
+ .getByLabel(badge)
+ .waitFor({ state: "attached" });
};
const expectPersistedDataVariables = async ({
@@ -505,11 +411,6 @@ test("Builder-created data variables and resources persist after reload", async
name: httpName,
curl: `curl '${httpCurlUrl}?${httpSearchParamName}=${httpSearchParamValue}' --request POST --header '${httpHeaderName}: ${httpHeaderValue}' --header 'Content-Type: application/json' --data '{"${httpBodyValue}":true}'`,
});
- await deleteVariable({
- page,
- fixture,
- name: graphqlName,
- });
}
);
@@ -529,7 +430,7 @@ test("Builder-created data variables and resources persist after reload", async
graphqlUrl,
graphqlQuery,
systemName,
- deletedName: graphqlName,
+ deletedName: undefined,
});
await expectVariableListItem({
@@ -542,8 +443,10 @@ test("Builder-created data variables and resources persist after reload", async
name: httpName,
badge: "Dynamic data variable",
});
- await page.getByText(graphqlName, { exact: true }).waitFor({
- state: "hidden",
+ await expectVariableListItem({
+ page,
+ name: graphqlName,
+ badge: "Dynamic data variable",
});
await expectVariableListItem({
page,
@@ -571,8 +474,10 @@ test("Builder-created data variables and resources persist after reload", async
name: httpName,
badge: "Dynamic data variable",
});
- await page.getByText(graphqlName, { exact: true }).waitFor({
- state: "hidden",
+ await expectVariableListItem({
+ page,
+ name: graphqlName,
+ badge: "Dynamic data variable",
});
await expectVariableListItem({
page,
@@ -580,6 +485,38 @@ test("Builder-created data variables and resources persist after reload", async
badge: "Dynamic data variable",
});
+ await expectPersistedDataVariables({
+ fixture,
+ staticName,
+ staticValue: editedStaticValue,
+ httpName,
+ httpUrl,
+ httpCurlUrl,
+ httpSearchParamName,
+ httpSearchParamValue,
+ httpHeaderName,
+ httpHeaderValue,
+ httpBodyValue,
+ graphqlName,
+ graphqlUrl,
+ graphqlQuery,
+ systemName,
+ deletedName: undefined,
+ });
+
+ await measure(
+ "data variables runtime delete graphql variable",
+ async () => {
+ await deleteVariable({
+ page,
+ fixture,
+ name: graphqlName,
+ });
+ }
+ );
+ await page.getByText(graphqlName, { exact: true }).waitFor({
+ state: "hidden",
+ });
await expectPersistedDataVariables({
fixture,
staticName,
@@ -654,8 +591,8 @@ test("Text Content can bind to a Builder-created variable and persist after relo
});
await waitForCanvasText({ page, text: staticValue });
- await measure("text content binding generated app build", async () => {
- await expectGeneratedAppBuild({
+ await measure("text content binding generated app renders", async () => {
+ await expectGeneratedAppToRender({
projectId: fixture.projectId,
expectedText: staticValue,
});
diff --git a/apps/builder/e2e/tests/data-variables-runtime.[shard-3].e2e.ts b/apps/builder/e2e/tests/data-variables-runtime.[shard-3].e2e.ts
new file mode 100644
index 0000000000..6b222e5a46
--- /dev/null
+++ b/apps/builder/e2e/tests/data-variables-runtime.[shard-3].e2e.ts
@@ -0,0 +1,189 @@
+import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
+import {
+ bindSelectedTextContentToExpression,
+ createGraphqlResourceVariable,
+ createHttpResourceVariable,
+ createSystemResourceVariable,
+ selectContentInstance,
+ startGraphqlResourceServer,
+ startJsonResourceServer,
+} from "../flows/data-variables";
+import { loginWithSecret } from "../flows/dashboard";
+import { expectGeneratedAppToRender } from "../flows/generated-app";
+import { createContentModeProject } from "../fixtures/content-mode-suite";
+import { newIsolatedPage, test } from "../harness";
+import { measure } from "../perf";
+
+const openGeneratedResourceProject = async ({
+ page,
+ email,
+ title,
+ assetNamePrefix,
+}: {
+ page: Awaited<ReturnType<typeof newIsolatedPage>>["page"];
+ email: string;
+ title: string;
+ assetNamePrefix: string;
+}) => {
+ const fixture = await createContentModeProject({
+ email,
+ title,
+ assetNamePrefix,
+ editorToken: `${assetNamePrefix}editor-token`,
+ builderToken: `${assetNamePrefix}builder-token`,
+ });
+ await loginWithSecret({ page, email });
+ await measure(`${title} open builder`, async () => {
+ await openProjectBuilder({
+ page,
+ projectId: fixture.projectId,
+ authToken: fixture.builderToken,
+ });
+ await waitForCanvasText({ page, text: "Initial content" });
+ });
+ await selectContentInstance({ page });
+ return fixture;
+};
+
+const reloadAndSelectContent = async ({
+ page,
+ fixture,
+ phase,
+}: {
+ page: Awaited<ReturnType<typeof newIsolatedPage>>["page"];
+ fixture: { projectId: string; builderToken: string };
+ phase: string;
+}) => {
+ await measure(phase, async () => {
+ await openProjectBuilder({
+ page,
+ projectId: fixture.projectId,
+ authToken: fixture.builderToken,
+ });
+ await waitForCanvasText({ page, text: "Initial content" });
+ await selectContentInstance({ page });
+ });
+};
+
+test("Generated app fetches and renders a Builder-created HTTP resource", async () => {
+ const { page, close } = await newIsolatedPage();
+ const resource = await startJsonResourceServer({
+ title: "Rendered from local HTTP resource",
+ });
+ const resourceName = "e2eGeneratedPosts";
+
+ try {
+ const fixture = await openGeneratedResourceProject({
+ page,
+ email: "[email protected]",
+ title: "Generated HTTP Resource",
+ assetNamePrefix: "generated-resource-",
+ });
+ await measure("generated HTTP resource create variable", async () => {
+ await createHttpResourceVariable({
+ page,
+ name: resourceName,
+ url: resource.url,
+ });
+ });
+ await reloadAndSelectContent({
+ page,
+ fixture,
+ phase: "generated HTTP resource reload Builder",
+ });
+ await bindSelectedTextContentToExpression({
+ page,
+ expression: `${resourceName}.data.title`,
+ });
+ await waitForCanvasText({
+ page,
+ text: "Rendered from local HTTP resource",
+ });
+ await expectGeneratedAppToRender({
+ projectId: fixture.projectId,
+ expectedText: "Rendered from local HTTP resource",
+ });
+ } finally {
+ await resource.close();
+ await close();
+ }
+});
+
+test("Generated app fetches and renders a Builder-created GraphQL resource", async () => {
+ const { page, close } = await newIsolatedPage();
+ const resource = await startGraphqlResourceServer({
+ title: "Rendered from local GraphQL resource",
+ });
+ const resourceName = "e2eGeneratedPost";
+
+ try {
+ const fixture = await openGeneratedResourceProject({
+ page,
+ email: "[email protected]",
+ title: "Generated GraphQL Resource",
+ assetNamePrefix: "generated-graphql-resource-",
+ });
+ await createGraphqlResourceVariable({
+ page,
+ name: resourceName,
+ url: resource.url,
+ query: "query Post { post { title } }",
+ });
+ await reloadAndSelectContent({
+ page,
+ fixture,
+ phase: "generated GraphQL resource reload Builder",
+ });
+ await bindSelectedTextContentToExpression({
+ page,
+ expression: `${resourceName}.data.data.post.title`,
+ });
+ await waitForCanvasText({
+ page,
+ text: "Rendered from local GraphQL resource",
+ });
+ await expectGeneratedAppToRender({
+ projectId: fixture.projectId,
+ expectedText: "Rendered from local GraphQL resource",
+ });
+ } finally {
+ await resource.close();
+ await close();
+ }
+});
+
+test("Generated app renders a Builder-created current-date system resource", async () => {
+ const { page, close } = await newIsolatedPage();
+ const resourceName = "e2eGeneratedCurrentDate";
+ const expectedYear = String(new Date().getUTCFullYear());
+
+ try {
+ const fixture = await openGeneratedResourceProject({
+ page,
+ email: "[email protected]",
+ title: "Generated System Resource",
+ assetNamePrefix: "generated-system-resource-",
+ });
+ await createSystemResourceVariable({
+ page,
+ name: resourceName,
+ resource: "Current Date",
+ });
+ await reloadAndSelectContent({
+ page,
+ fixture,
+ phase: "generated system resource reload Builder",
+ });
+ await bindSelectedTextContentToExpression({
+ page,
+ expression: `${resourceName}.data.year`,
+ });
+ await waitForCanvasText({ page, text: expectedYear });
+ await expectGeneratedAppToRender({
+ projectId: fixture.projectId,
+ expectedText: expectedYear,
+ });
+ } finally {
+ await close();
+ }
+});
diff --git a/apps/builder/e2e/tests/pages-actions.[shard-2].e2e.ts b/apps/builder/e2e/tests/pages-actions.[shard-2].e2e.ts
index c2702614b3..154778202b 100644
--- a/apps/builder/e2e/tests/pages-actions.[shard-2].e2e.ts
+++ b/apps/builder/e2e/tests/pages-actions.[shard-2].e2e.ts
@@ -229,16 +229,6 @@ const getElementTagWithTextCount = async ({
return (await inspectBuild(fixture)).countElementTagWithText({ tag, text });
};
-const getInstanceWithTextCount = async ({
- fixture,
- text,
-}: {
- fixture: SeededContentModeProject;
- text: string;
-}) => {
- return (await inspectBuild(fixture)).countInstancesWithText(text);
-};
-
const getExactTextChildCount = async ({
fixture,
text,
@@ -1292,136 +1282,3 @@ test("Builder allows native paste inside focused builder inputs", async () => {
await close();
}
});
-
-test("Builder runs paste plugins through generic browser paste events", async () => {
- const { page, close } = await newIsolatedPage();
- const instanceJsonText = "Instance JSON paste heading";
- const instanceTextText = "Instance text paste heading";
- const jsxText = "JSX paste heading";
- const htmlText = "HTML paste heading";
- const markdownText = "Markdown paste heading";
- const webflowText = "Webflow paste heading";
-
- const webflowData = JSON.stringify({
- type: "@webflow/XscpData",
- payload: {
- nodes: [
- {
- _id: "webflow-heading",
- type: "Heading",
- tag: "h1",
- children: ["webflow-heading-text"],
- classes: [],
- },
- {
- _id: "webflow-heading-text",
- v: webflowText,
- text: true,
- },
- ],
- styles: [],
- assets: [],
- },
- });
-
- try {
- await measure(
- "pages actions open builder for generic paste plugins",
- async () => {
- await openProjectBuilder({
- page,
- projectId: fixture.projectId,
- authToken: fixture.builderToken,
- });
- }
- );
- await waitForCanvasText({ page, text: "Initial content" });
-
- await selectBodyInNavigator({ page });
- await pasteClipboardData({
- page,
- data: {
- "application/json": createInstanceTransfer({
- id: "instance-json-paste",
- text: instanceJsonText,
- }),
- },
- });
- await waitForCanvasText({ page, text: instanceJsonText });
-
- await selectBodyInNavigator({ page });
- await pasteClipboardData({
- page,
- data: {
- "text/plain": createInstanceTransfer({
- id: "instance-text-paste",
- text: instanceTextText,
- }),
- },
- });
- await waitForCanvasText({ page, text: instanceTextText });
-
- await selectBodyInNavigator({ page });
- await pasteClipboardData({
- page,
- data: {
- "text/plain": `<ws.element ws:tag="h2">${jsxText}</ws.element>`,
- },
- });
- await waitForCanvasText({ page, text: jsxText });
-
- await selectBodyInNavigator({ page });
- await pasteClipboardData({
- page,
- data: {
- "text/plain": `<section><h2>${htmlText}</h2></section>`,
- },
- });
- await waitForCanvasText({ page, text: htmlText });
-
- await selectBodyInNavigator({ page });
- await pasteClipboardData({
- page,
- data: {
- "text/plain": `## ${markdownText}`,
- },
- });
- await waitForCanvasText({ page, text: markdownText });
-
- await selectBodyInNavigator({ page });
- await pasteClipboardData({
- page,
- data: {
- "application/json": webflowData,
- },
- });
- await waitForCanvasText({ page, text: webflowText });
-
- const expectedPastes = [
- ["p", instanceJsonText],
- ["p", instanceTextText],
- ["h2", jsxText],
- ["h2", htmlText],
- ["h2", markdownText],
- ] as const;
- for (const [tag, text] of expectedPastes) {
- const count = await getElementTagWithTextCount({ fixture, tag, text });
- if (count !== 1) {
- throw new Error(
- `Expected generic paste to create one ${tag} containing "${text}", found ${count}`
- );
- }
- }
- const webflowTextCount = await getInstanceWithTextCount({
- fixture,
- text: webflowText,
- });
- if (webflowTextCount === 0) {
- throw new Error(
- `Expected generic Webflow paste to persist text "${webflowText}"`
- );
- }
- } finally {
- await close();
- }
-});
diff --git a/apps/builder/e2e/tests/pages-actions.[shard-3].e2e.ts b/apps/builder/e2e/tests/pages-actions.[shard-3].e2e.ts
index 8c431549fb..50946d76aa 100644
--- a/apps/builder/e2e/tests/pages-actions.[shard-3].e2e.ts
+++ b/apps/builder/e2e/tests/pages-actions.[shard-3].e2e.ts
@@ -1,6 +1,7 @@
import type { Page } from "playwright";
import { expectTextHidden } from "../flows/assertions";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
+import { expectGeneratedAppBuild } from "../flows/generated-app";
import {
createFolder,
createPageFromTemplate,
@@ -21,6 +22,7 @@ import { measure } from "../perf";
import { loadDevBuild } from "../db";
let fixture: SeededContentModeProject;
+let pasteFixture: SeededContentModeProject;
const copiedPageTransferMarker = "@webstudio/page/v0.1";
@@ -199,6 +201,13 @@ test.beforeAll(async () => {
editorToken: "pages-actions-e2e-editor-token",
builderToken: "pages-actions-e2e-builder-token",
});
+ pasteFixture = await createContentModeProject({
+ email: "[email protected]",
+ title: "Pages Actions Paste E2E",
+ assetNamePrefix: "pages-actions-paste-",
+ editorToken: "pages-actions-paste-e2e-editor-token",
+ builderToken: "pages-actions-paste-e2e-builder-token",
+ });
});
test("Builder can copy, duplicate, and delete a page from the header menu", async () => {
@@ -238,6 +247,12 @@ test("Builder can copy, duplicate, and delete a page from the header menu", asyn
});
await waitForCanvasText({ page, text: "2026" });
await expectDataResourceCopies(fixture, dataResourceCountsBefore);
+ await measure(
+ "pages actions generated app build for copied resources",
+ async () => {
+ await expectGeneratedAppBuild({ projectId: fixture.projectId });
+ }
+ );
await openPageSettings({ page, pageName });
const renameSave = waitForChangeToBeSaved({ page });
@@ -471,3 +486,207 @@ test("Builder can copy, duplicate, and delete a page template from actions menus
await close();
}
});
+
+const createInstanceTransfer = ({ id, text }: { id: string; text: string }) =>
+ JSON.stringify({
+ "@webstudio/instance/v0.1": {
+ instanceSelector: [id, "source-body"],
+ children: [{ type: "id", value: id }],
+ instances: [
+ {
+ type: "instance",
+ id,
+ component: "ws:element",
+ tag: "p",
+ children: [{ type: "text", value: text }],
+ },
+ ],
+ assets: [],
+ dataSources: [],
+ resources: [],
+ props: [],
+ breakpoints: [],
+ styleSourceSelections: [],
+ styleSources: [],
+ styles: [],
+ },
+ });
+
+const selectPasteBody = async ({ page }: { page: Page }) => {
+ const navigatorTab = page.getByRole("tab", { name: "Navigator" });
+ if ((await navigatorTab.getAttribute("aria-selected")) !== "true") {
+ await navigatorTab.click();
+ }
+ const body = page
+ .locator("[data-navigator-tree] [data-tree-button]")
+ .filter({ hasText: "Body" })
+ .last();
+ await body.dblclick();
+};
+
+const pasteClipboardData = async ({
+ page,
+ data,
+}: {
+ page: Page;
+ data: Record<string, string>;
+}) => {
+ const save = waitForChangeToBeSaved({ page });
+ await page.evaluate((data) => {
+ const clipboardData = new DataTransfer();
+ for (const [mimeType, value] of Object.entries(data)) {
+ clipboardData.setData(mimeType, value);
+ }
+ document.dispatchEvent(
+ new ClipboardEvent("paste", {
+ bubbles: true,
+ cancelable: true,
+ clipboardData,
+ })
+ );
+ }, data);
+ await save;
+ await waitForSyncStatus({ page, status: "idle" });
+};
+
+const countPastedElements = async ({
+ tag,
+ text,
+}: {
+ tag: string;
+ text: string;
+}) => {
+ const build = await loadDevBuild({ projectId: pasteFixture.projectId });
+ const instances = JSON.parse(build.instances) as Array<{
+ component?: string;
+ tag?: string;
+ children?: Array<{ type: string; value?: string }>;
+ }>;
+ return instances.filter(
+ (instance) =>
+ instance.component === "ws:element" &&
+ instance.tag === tag &&
+ instance.children?.some(
+ (child) => child.type === "text" && child.value?.includes(text)
+ )
+ ).length;
+};
+
+const countBuildInstancesWithText = async (text: string) => {
+ const build = await loadDevBuild({ projectId: pasteFixture.projectId });
+ const instances = JSON.parse(build.instances) as Array<{
+ id: string;
+ children?: Array<{ type: string; value?: string }>;
+ }>;
+ const instancesById = new Map(
+ instances.map((instance) => [instance.id, instance])
+ );
+ const containsText = (instanceId: string): boolean => {
+ const instance = instancesById.get(instanceId);
+ return (
+ instance?.children?.some(
+ (child) =>
+ (child.type === "text" && child.value?.includes(text)) ||
+ (child.type === "id" &&
+ child.value !== undefined &&
+ containsText(child.value))
+ ) ?? false
+ );
+ };
+ return instances.filter((instance) => containsText(instance.id)).length;
+};
+
+test("Builder runs paste plugins through generic browser paste events", async () => {
+ const { page, close } = await newIsolatedPage();
+ const entries = [
+ [
+ "application/json",
+ createInstanceTransfer({
+ id: "paste-json",
+ text: "Instance JSON paste heading",
+ }),
+ "Instance JSON paste heading",
+ "p",
+ ],
+ [
+ "text/plain",
+ createInstanceTransfer({
+ id: "paste-text",
+ text: "Instance text paste heading",
+ }),
+ "Instance text paste heading",
+ "p",
+ ],
+ [
+ "text/plain",
+ '<ws.element ws:tag="h2">JSX paste heading</ws.element>',
+ "JSX paste heading",
+ "h2",
+ ],
+ [
+ "text/plain",
+ "<section><h2>HTML paste heading</h2></section>",
+ "HTML paste heading",
+ "h2",
+ ],
+ ["text/plain", "## Markdown paste heading", "Markdown paste heading", "h2"],
+ [
+ "application/json",
+ JSON.stringify({
+ type: "@webflow/XscpData",
+ payload: {
+ nodes: [
+ {
+ _id: "webflow-heading",
+ type: "Heading",
+ tag: "h1",
+ children: ["webflow-heading-text"],
+ classes: [],
+ },
+ {
+ _id: "webflow-heading-text",
+ v: "Webflow paste heading",
+ text: true,
+ },
+ ],
+ styles: [],
+ assets: [],
+ },
+ }),
+ "Webflow paste heading",
+ undefined,
+ ],
+ ] as const;
+
+ try {
+ await openProjectBuilder({
+ page,
+ projectId: pasteFixture.projectId,
+ authToken: pasteFixture.builderToken,
+ });
+ await waitForCanvasText({ page, text: "Initial content" });
+
+ for (const [mimeType, value, text, tag] of entries) {
+ await selectPasteBody({ page });
+ await pasteClipboardData({ page, data: { [mimeType]: value } });
+ await waitForCanvasText({ page, text });
+ if (tag === undefined) {
+ const count = await countBuildInstancesWithText(text);
+ if (count === 0) {
+ throw new Error(
+ `Expected generic Webflow paste to persist ${JSON.stringify(text)}`
+ );
+ }
+ continue;
+ }
+ const count = await countPastedElements({ tag, text });
+ if (count !== 1) {
+ throw new Error(
+ `Expected one ${tag} containing ${JSON.stringify(text)}, found ${count}`
+ );
+ }
+ }
+ } finally {
+ await close();
+ }
+});
diff --git a/apps/builder/e2e/tests/preview-links.[shard-1].e2e.ts b/apps/builder/e2e/tests/preview-links.[shard-1].e2e.ts
index 5b072b63dc..a270b45915 100644
--- a/apps/builder/e2e/tests/preview-links.[shard-1].e2e.ts
+++ b/apps/builder/e2e/tests/preview-links.[shard-1].e2e.ts
@@ -1,5 +1,9 @@
import type { Locator } from "playwright";
import { openBuilderUrl, waitForCanvasFrame } from "../flows/builder";
+import {
+ expectGeneratedAppNavigation,
+ expectGeneratedAppToRender,
+} from "../flows/generated-app";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { insertAuthorizationToken, loadDevBuild, updateBuild } from "../db";
import { getProjectBuilderUrl, newIsolatedPage, test } from "../harness";
@@ -404,3 +408,22 @@ test("Preview links expose current page state for components and element anchors
await close();
}
});
+
+test("Generated preview renders and navigates linked routes", async () => {
+ const { page, close } = await newIsolatedPage();
+ try {
+ await expectGeneratedAppToRender({
+ projectId: fixture.projectId,
+ path: "/my-page",
+ expectedText: previewLinkText.pageLink,
+ });
+ await expectGeneratedAppNavigation({
+ projectId: fixture.projectId,
+ page,
+ linkText: previewLinkText.pageLink,
+ targetPath: "/my-page",
+ });
+ } finally {
+ await close();
+ }
+});
diff --git a/apps/builder/e2e/tests/project-settings-runtime.[shard-2].e2e.ts b/apps/builder/e2e/tests/project-settings-runtime.[shard-2].e2e.ts
index 397bf90055..b9404ae3f9 100644
--- a/apps/builder/e2e/tests/project-settings-runtime.[shard-2].e2e.ts
+++ b/apps/builder/e2e/tests/project-settings-runtime.[shard-2].e2e.ts
@@ -1,5 +1,6 @@
import type { Page as PlaywrightPage } from "playwright";
import type { Page as WebstudioPage } from "@webstudio-is/sdk";
+import { parseProjectAuthRoutes } from "@webstudio-is/project-build/runtime/project-settings";
import { loadDevBuild, updateProject } from "../db";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
import { loginWithSecret } from "../flows/dashboard";
@@ -12,15 +13,15 @@ import {
waitForChangeToBeSaved,
waitForSyncStatus,
} from "../flows/sync-status";
-import { expectGeneratedRedirects } from "../flows/generated-app";
+import {
+ expectGeneratedAppRedirect,
+ expectGeneratedRedirects,
+} from "../flows/generated-app";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { newIsolatedPage, test } from "../harness";
import { measure } from "../perf";
type PersistedPages = {
- meta?: {
- siteName?: string;
- };
redirects?: Array<{
old: string;
new: string;
@@ -29,11 +30,25 @@ type PersistedPages = {
pages: WebstudioPage[];
};
+type PersistedProjectSettings = {
+ compiler: { atomicStyles?: boolean };
+ meta: { auth?: string | null; siteName?: string };
+};
+
const getPersistedPages = async ({ projectId }: { projectId: string }) => {
const build = await loadDevBuild({ projectId });
return JSON.parse(build.pages) as PersistedPages;
};
+const getPersistedProjectSettings = async ({
+ projectId,
+}: {
+ projectId: string;
+}) => {
+ const build = await loadDevBuild({ projectId });
+ return JSON.parse(build.projectSettings) as PersistedProjectSettings;
+};
+
const getPersistedPageByName = async ({
projectId,
name,
@@ -68,6 +83,29 @@ const saveSiteName = async ({
await waitForSyncStatus({ page, status: "idle" });
};
+const setAtomicStyles = async ({
+ page,
+ checked,
+}: {
+ page: PlaywrightPage;
+ checked: boolean;
+}) => {
+ await page.getByRole("option", { name: "Publish" }).click();
+ const checkbox = page.getByRole("checkbox", {
+ name: "Generate atomic CSS when publishing",
+ });
+ const toggle = async () => {
+ const save = waitForChangeToBeSaved({ page });
+ await checkbox.click();
+ await save;
+ await waitForSyncStatus({ page, status: "idle" });
+ };
+ if ((await checkbox.isChecked()) === checked) {
+ await toggle();
+ }
+ await toggle();
+};
+
const addRedirect = async ({
page,
from,
@@ -90,6 +128,70 @@ const addRedirect = async ({
await waitForSyncStatus({ page, status: "idle" });
};
+const addBasicAuth = async ({
+ page,
+ route,
+ login,
+ password,
+}: {
+ page: PlaywrightPage;
+ route: string;
+ login: string;
+ password: string;
+}) => {
+ await page.getByRole("option", { name: "Authentication" }).click();
+ await page.getByPlaceholder("/private or /docs/*").fill(route);
+ await page.getByPlaceholder("Login").fill(login);
+ await page.getByPlaceholder("Password").fill(password);
+ const save = waitForChangeToBeSaved({ page });
+ await page.getByRole("button", { name: "Add" }).click();
+ await save;
+ await waitForSyncStatus({ page, status: "idle" });
+};
+
+const deleteBasicAuth = async ({
+ page,
+ route,
+}: {
+ page: PlaywrightPage;
+ route: string;
+}) => {
+ await page.getByText(route, { exact: true }).hover();
+ const save = waitForChangeToBeSaved({ page });
+ await page
+ .getByRole("button", { name: `Delete authentication for ${route}` })
+ .click();
+ await save;
+ await waitForSyncStatus({ page, status: "idle" });
+};
+
+const expectPersistedBasicAuth = async ({
+ projectId,
+ route,
+ login,
+ exists,
+}: {
+ projectId: string;
+ route: string;
+ login: string;
+ exists: boolean;
+}) => {
+ const settings = await getPersistedProjectSettings({ projectId });
+ const routes = parseProjectAuthRoutes(settings.meta.auth ?? undefined).routes;
+ const authRoute = routes.find((authRoute) => authRoute.route === route);
+ if (exists === false) {
+ if (authRoute !== undefined) {
+ throw new Error(`Expected auth route ${route} to be deleted.`);
+ }
+ return;
+ }
+ if (authRoute?.auth.login !== login) {
+ throw new Error(
+ `Expected auth route ${route} for ${login}. Received ${JSON.stringify(routes)}`
+ );
+ }
+};
+
const deleteRedirect = async ({
page,
from,
@@ -116,9 +218,10 @@ const expectPersistedProjectSettings = async ({
redirect?: { from: string; to: string; status?: string };
}) => {
const pages = await getPersistedPages({ projectId });
- if (pages.meta?.siteName !== siteName) {
+ const settings = await getPersistedProjectSettings({ projectId });
+ if (settings.meta.siteName !== siteName) {
throw new Error(
- `Expected siteName "${siteName}", received ${JSON.stringify(pages.meta)}.`
+ `Expected siteName "${siteName}", received ${JSON.stringify(settings.meta)}.`
);
}
@@ -177,6 +280,7 @@ test("Project settings site name and redirects persist after reload", async () =
await measure("project settings runtime update settings", async () => {
await openProjectSettings({ page });
await saveSiteName({ page, siteName });
+ await setAtomicStyles({ page, checked: false });
await addRedirect({
page,
from: redirect.from,
@@ -189,18 +293,23 @@ test("Project settings site name and redirects persist after reload", async () =
siteName,
redirect,
});
- await measure("project settings runtime generated redirects", async () => {
- await expectGeneratedRedirects({
- projectId: fixture.projectId,
- expectedRedirects: [
- {
- old: redirect.from,
- new: redirect.to,
- status: "301",
- },
- ],
- });
- });
+ if (
+ (await getPersistedProjectSettings({ projectId: fixture.projectId }))
+ .compiler.atomicStyles !== false
+ ) {
+ throw new Error("Expected atomic CSS setting to persist as disabled.");
+ }
+ await measure(
+ "project settings runtime generated redirect response",
+ async () => {
+ await expectGeneratedAppRedirect({
+ projectId: fixture.projectId,
+ path: redirect.from,
+ status: 301,
+ location: redirect.to,
+ });
+ }
+ );
await measure("project settings runtime reload with redirect", async () => {
await openProjectBuilder({
@@ -220,6 +329,19 @@ test("Project settings site name and redirects persist after reload", async () =
}
await page.getByRole("option", { name: "Redirects" }).click();
await page.getByText(redirect.from, { exact: true }).waitFor();
+ await page.getByRole("option", { name: "Publish" }).click();
+ if (
+ await page
+ .getByRole("checkbox", {
+ name: "Generate atomic CSS when publishing",
+ })
+ .isChecked()
+ ) {
+ throw new Error(
+ "Expected atomic CSS setting to remain disabled after reload."
+ );
+ }
+ await page.getByRole("option", { name: "Redirects" }).click();
await measure("project settings runtime delete redirect", async () => {
await deleteRedirect({ page, from: redirect.from });
@@ -372,3 +494,73 @@ test("Marketplace page settings persist after reload", async () => {
await close();
}
});
+
+test("Project authentication routes persist after reload and deletion", async () => {
+ const email = "[email protected]";
+ const fixture = await createContentModeProject({
+ email,
+ title: "Project Auth Runtime",
+ assetNamePrefix: "project-auth-runtime-",
+ editorToken: "project-auth-runtime-editor-token",
+ builderToken: "project-auth-runtime-builder-token",
+ });
+ const { page, close } = await newIsolatedPage();
+ const route = "/private";
+ const login = "editor";
+ const password = "e2e-secret";
+
+ try {
+ await loginWithSecret({ page, email });
+ await measure("project auth runtime open builder", async () => {
+ await openProjectBuilder({
+ page,
+ projectId: fixture.projectId,
+ authToken: fixture.builderToken,
+ });
+ await waitForCanvasText({ page, text: "Initial content" });
+ });
+
+ await measure("project auth runtime add route", async () => {
+ await openProjectSettings({ page });
+ await page.getByRole("option", { name: "Authentication" }).click();
+ await page.getByPlaceholder("/private or /docs/*").fill("private");
+ if (
+ (await page.getByRole("button", { name: "Add" }).isDisabled()) === false
+ ) {
+ throw new Error("Expected invalid auth route to disable Add.");
+ }
+ await addBasicAuth({ page, route, login, password });
+ });
+ await expectPersistedBasicAuth({
+ projectId: fixture.projectId,
+ route,
+ login,
+ exists: true,
+ });
+
+ await measure("project auth runtime reload builder", async () => {
+ await openProjectBuilder({
+ page,
+ projectId: fixture.projectId,
+ authToken: fixture.builderToken,
+ });
+ await waitForCanvasText({ page, text: "Initial content" });
+ });
+ await openProjectSettings({ page });
+ await page.getByRole("option", { name: "Authentication" }).click();
+ await page.getByText(route, { exact: true }).waitFor();
+ await page.getByText(login, { exact: true }).waitFor();
+
+ await measure("project auth runtime delete route", async () => {
+ await deleteBasicAuth({ page, route });
+ });
+ await expectPersistedBasicAuth({
+ projectId: fixture.projectId,
+ route,
+ login,
+ exists: false,
+ });
+ } finally {
+ await close();
+ }
+});
diff --git a/apps/builder/e2e/tests/props-runtime.[shard-2].e2e.ts b/apps/builder/e2e/tests/props-runtime.[shard-2].e2e.ts
index 75128b6194..a8ae95b4ae 100644
--- a/apps/builder/e2e/tests/props-runtime.[shard-2].e2e.ts
+++ b/apps/builder/e2e/tests/props-runtime.[shard-2].e2e.ts
@@ -2,6 +2,11 @@ import type { Page } from "playwright";
import { loadDevBuild } from "../db";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
import { selectCanvasTextInstance } from "../flows/canvas-selection";
+import {
+ resetSelectedProperty,
+ setSelectedBooleanProperty,
+ waitForSelectedBooleanPropertyValue,
+} from "../flows/props-panel";
import {
waitForChangeToBeSaved,
waitForSyncStatus,
@@ -18,13 +23,19 @@ const openComponentsPanel = async ({ page }: { page: Page }) => {
const insertComponentPanelOption = async ({
page,
name,
+ component,
}: {
page: Page;
name: string;
+ component?: string;
}) => {
const search = page.getByPlaceholder("Find components");
await search.fill(name);
- await page.getByRole("option", { name, exact: true }).click();
+ const option =
+ component === undefined
+ ? page.getByRole("option", { name, exact: true })
+ : page.locator(`[data-drag-component="${component}"]`);
+ await option.click();
await waitForSyncStatus({ page, status: "idle" });
};
@@ -56,6 +67,26 @@ const selectNavigatorItem = async ({
await item.click();
};
+const selectFirstNavigatorChild = async ({
+ page,
+ parentLabel,
+}: {
+ page: Page;
+ parentLabel: string;
+}) => {
+ await openNavigatorPanel({ page });
+ const parent = page
+ .locator("[data-navigator-tree] [data-tree-button]")
+ .filter({ hasText: parentLabel })
+ .first();
+ await parent.waitFor({ state: "visible" });
+ await parent.press("ArrowRight");
+ const child = parent.locator("xpath=following::button[@data-tree-button][1]");
+ await child.waitFor({ state: "visible" });
+ await child.click();
+ await child.click();
+};
+
const updateResourceActionUrl = async ({
page,
url,
@@ -242,6 +273,79 @@ const expectPersistedExpressionProp = async ({
}
};
+const expectPersistedBooleanProp = async ({
+ projectId,
+ component,
+ name,
+ value,
+}: {
+ projectId: string;
+ component: string;
+ name: string;
+ value: boolean;
+}) => {
+ const build = await loadDevBuild({ projectId });
+ const instances = JSON.parse(build.instances) as Array<{
+ id: string;
+ component: string;
+ }>;
+ const props = JSON.parse(build.props) as Array<{
+ instanceId: string;
+ name: string;
+ type: string;
+ value?: unknown;
+ }>;
+ const instanceIds = new Set(
+ instances
+ .filter((instance) => instance.component === component)
+ .map((instance) => instance.id)
+ );
+ const prop = props.find(
+ (prop) =>
+ instanceIds.has(prop.instanceId) &&
+ prop.name === name &&
+ prop.type === "boolean" &&
+ prop.value === value
+ );
+ if (prop === undefined) {
+ throw new Error(
+ `Expected ${component} ${name}=${value} to persist. Props: ${JSON.stringify(props)}`
+ );
+ }
+};
+
+const expectBooleanPropDeleted = async ({
+ projectId,
+ component,
+ name,
+}: {
+ projectId: string;
+ component: string;
+ name: string;
+}) => {
+ const build = await loadDevBuild({ projectId });
+ const instances = JSON.parse(build.instances) as Array<{
+ id: string;
+ component: string;
+ }>;
+ const props = JSON.parse(build.props) as Array<{
+ instanceId: string;
+ name: string;
+ }>;
+ const instanceIds = new Set(
+ instances
+ .filter((instance) => instance.component === component)
+ .map((instance) => instance.id)
+ );
+ if (
+ props.some((prop) => instanceIds.has(prop.instanceId) && prop.name === name)
+ ) {
+ throw new Error(
+ `Expected ${component} ${name} prop to be deleted. Props: ${JSON.stringify(props)}`
+ );
+ }
+};
+
test("Props panel resource action persists after reload", async () => {
const fixture = await createContentModeProject({
@@ -365,3 +469,111 @@ test("Props panel expression binding persists after reload", async () => {
await close();
}
});
+
+test("Props panel boolean prop persists after reload", async () => {
+ const fixture = await createContentModeProject({
+ email: "[email protected]",
+ title: "Props Boolean Runtime",
+ assetNamePrefix: "props-boolean-runtime-",
+ editorToken: "props-boolean-runtime-editor-token",
+ builderToken: "props-boolean-runtime-builder-token",
+ });
+ const { page, close } = await newIsolatedPage();
+
+ try {
+ await measure("props boolean runtime open builder", async () => {
+ await openProjectBuilder({
+ page,
+ projectId: fixture.projectId,
+ authToken: fixture.builderToken,
+ });
+ });
+ await waitForCanvasText({ page, text: "Initial content" });
+
+ await measure("props boolean runtime insert checkbox", async () => {
+ await openComponentsPanel({ page });
+ await insertComponentPanelOption({
+ page,
+ name: "Checkbox",
+ component: "@webstudio-is/sdk-components-react-radix:Checkbox",
+ });
+ });
+ await selectFirstNavigatorChild({
+ page,
+ parentLabel: "Checkbox Field",
+ });
+ await page.getByRole("tab", { name: "Settings" }).click();
+
+ await measure("props boolean runtime set checked", async () => {
+ await setSelectedBooleanProperty({
+ page,
+ label: "Checked",
+ checked: true,
+ });
+ });
+ await expectPersistedBooleanProp({
+ projectId: fixture.projectId,
+ component: "@webstudio-is/sdk-components-react-radix:Checkbox",
+ name: "checked",
+ value: true,
+ });
+
+ await measure("props boolean runtime reload builder", async () => {
+ await openProjectBuilder({
+ page,
+ projectId: fixture.projectId,
+ authToken: fixture.builderToken,
+ });
+ });
+ await selectFirstNavigatorChild({
+ page,
+ parentLabel: "Checkbox Field",
+ });
+ await page.getByRole("tab", { name: "Settings" }).click();
+ await waitForSelectedBooleanPropertyValue({
+ page,
+ label: "Checked",
+ checked: true,
+ });
+ await expectPersistedBooleanProp({
+ projectId: fixture.projectId,
+ component: "@webstudio-is/sdk-components-react-radix:Checkbox",
+ name: "checked",
+ value: true,
+ });
+
+ await measure("props boolean runtime reset checked", async () => {
+ await resetSelectedProperty({ page, label: "Checked" });
+ });
+ await expectBooleanPropDeleted({
+ projectId: fixture.projectId,
+ component: "@webstudio-is/sdk-components-react-radix:Checkbox",
+ name: "checked",
+ });
+
+ await measure("props boolean runtime reload after reset", async () => {
+ await openProjectBuilder({
+ page,
+ projectId: fixture.projectId,
+ authToken: fixture.builderToken,
+ });
+ });
+ await selectFirstNavigatorChild({
+ page,
+ parentLabel: "Checkbox Field",
+ });
+ await page.getByRole("tab", { name: "Settings" }).click();
+ await waitForSelectedBooleanPropertyValue({
+ page,
+ label: "Checked",
+ checked: false,
+ });
+ await expectBooleanPropDeleted({
+ projectId: fixture.projectId,
+ component: "@webstudio-is/sdk-components-react-radix:Checkbox",
+ name: "checked",
+ });
+ } finally {
+ await close();
+ }
+});
diff --git a/apps/builder/e2e/tests/style-panel-runtime.[shard-1].e2e.ts b/apps/builder/e2e/tests/style-panel-runtime.[shard-1].e2e.ts
index 90df11fc06..1a56430949 100644
--- a/apps/builder/e2e/tests/style-panel-runtime.[shard-1].e2e.ts
+++ b/apps/builder/e2e/tests/style-panel-runtime.[shard-1].e2e.ts
@@ -42,6 +42,25 @@ const setCssValue = async ({
await waitForSyncStatus({ page, status: "idle" });
};
+const resetCssValue = async ({
+ page,
+ property,
+}: {
+ page: Page;
+ property: string;
+}) => {
+ const input = page.getByLabel(property, { exact: true }).first();
+ const labelText = `${property.slice(0, 1).toUpperCase()}${property.slice(1)}`;
+ const control = input.locator(
+ `xpath=ancestor::*[.//*[normalize-space()=${JSON.stringify(labelText)}]][1]`
+ );
+ const label = control.getByText(labelText, { exact: true });
+ await label.waitFor({ state: "visible", timeout: 10_000 });
+ const save = waitForChangeToBeSaved({ page });
+ await label.click({ modifiers: ["Alt"] });
+ await save;
+};
+
const selectStyleSourceState = async ({
page,
state,
@@ -73,6 +92,19 @@ const expectBuildStylesToContain = async ({
}
};
+const expectBuildStylesNotToContain = async ({
+ fixture,
+ text,
+}: {
+ fixture: SeededContentModeProject;
+ text: string;
+}) => {
+ const styles = await readBuildStylesText(fixture);
+ if (styles.includes(text)) {
+ throw new Error(`Expected build styles not to contain "${text}".`);
+ }
+};
+
test("Builder style panel edits representative styles and persists after reload", async () => {
const fixture = await createStylePanelRuntimeProject("styles");
const { page, close } = await newIsolatedPage();
@@ -143,6 +175,15 @@ test("Builder style panel edits representative styles and persists after reload"
text: `"state":":hover"`,
});
+ await page.getByRole("tab", { name: "Style" }).click();
+ await measure("style panel runtime reset css value", async () => {
+ await resetCssValue({ page, property: "width" });
+ });
+ await expectBuildStylesNotToContain({
+ fixture,
+ text: `"property":"width"`,
+ });
+
await measure("style panel runtime reload builder", async () => {
await openProjectBuilder({
page,
@@ -174,18 +215,16 @@ test("Builder style panel edits representative styles and persists after reload"
property: "color",
value: "rgb(34, 85, 255)",
});
- await waitForCanvasTextStyle({
- page,
- text,
- property: "width",
- value: "420px",
- });
await waitForHoveredCanvasTextStyle({
page,
text,
property: "color",
value: "rgb(202, 18, 107)",
});
+ await expectBuildStylesNotToContain({
+ fixture,
+ text: `"property":"width"`,
+ });
await expectBuildStylesToContain({
fixture,
text: `"state":":hover"`,
diff --git a/apps/builder/e2e/timeout.test.ts b/apps/builder/e2e/timeout.test.ts
new file mode 100644
index 0000000000..6deb905847
--- /dev/null
+++ b/apps/builder/e2e/timeout.test.ts
@@ -0,0 +1,72 @@
+import { expect, test, vi } from "vitest";
+import { runWithTimeout } from "./timeout";
+
+test("aborts, cleans up, and waits for timed-out work to settle", async () => {
+ const events: string[] = [];
+ let releaseTask: (() => void) | undefined;
+ const cleanup = vi.fn(async () => {
+ events.push("cleanup");
+ releaseTask?.();
+ });
+
+ await expect(
+ runWithTimeout({
+ name: "slow test",
+ timeoutMs: 1,
+ onTimeout: cleanup,
+ task: async () => {
+ await new Promise<void>((resolve) => {
+ releaseTask = () => {
+ events.push("settled");
+ resolve();
+ };
+ });
+ },
+ })
+ ).rejects.toThrow("Timed out after 1ms: slow test");
+
+ expect(cleanup).toHaveBeenCalledOnce();
+ expect(events).toEqual(["cleanup", "settled"]);
+});
+
+test("preserves timeout semantics when cleanup rejects", async () => {
+ const cleanupError = new Error("cleanup failed");
+ let releaseTask: (() => void) | undefined;
+
+ const result = runWithTimeout({
+ name: "cleanup failure",
+ timeoutMs: 1,
+ settleTimeoutMs: 50,
+ onTimeout: async () => {
+ releaseTask?.();
+ throw cleanupError;
+ },
+ task: async () => {
+ await new Promise<void>((resolve) => {
+ releaseTask = resolve;
+ });
+ },
+ });
+
+ await expect(result).rejects.toMatchObject({
+ message: "Timed out after 1ms: cleanup failure",
+ cause: cleanupError,
+ });
+});
+
+test("fails within the settlement grace period when work ignores cancellation", async () => {
+ const startedAt = Date.now();
+
+ await expect(
+ runWithTimeout({
+ name: "uncooperative test",
+ timeoutMs: 1,
+ settleTimeoutMs: 1,
+ task: async () => await new Promise<never>(() => undefined),
+ })
+ ).rejects.toThrow(
+ "Timed out after 1ms: uncooperative test; task did not settle within 1ms"
+ );
+
+ expect(Date.now() - startedAt).toBeLessThan(100);
+});
diff --git a/apps/builder/e2e/timeout.ts b/apps/builder/e2e/timeout.ts
new file mode 100644
index 0000000000..0b0897f6de
--- /dev/null
+++ b/apps/builder/e2e/timeout.ts
@@ -0,0 +1,60 @@
+const delay = (milliseconds: number) =>
+ new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
+
+export const runWithTimeout = async <Result>({
+ name,
+ timeoutMs,
+ settleTimeoutMs = 5_000,
+ task,
+ onTimeout,
+}: {
+ name: string;
+ timeoutMs: number;
+ settleTimeoutMs?: number;
+ task: (signal: AbortSignal) => Promise<Result>;
+ onTimeout?: () => Promise<void>;
+}) => {
+ const controller = new AbortController();
+ const taskPromise = task(controller.signal);
+ let timeout: NodeJS.Timeout | undefined;
+ const timeoutPromise = new Promise<{ type: "timeout" }>((resolve) => {
+ timeout = setTimeout(() => resolve({ type: "timeout" }), timeoutMs);
+ });
+
+ try {
+ const outcome = await Promise.race([
+ taskPromise.then(
+ (value) => ({ type: "success" as const, value }),
+ (error: unknown) => ({ type: "failure" as const, error })
+ ),
+ timeoutPromise,
+ ]);
+ if (outcome.type === "success") {
+ return outcome.value;
+ }
+ if (outcome.type === "failure") {
+ throw outcome.error;
+ }
+ controller.abort();
+ let cleanupError: unknown;
+ try {
+ await onTimeout?.();
+ } catch (error) {
+ cleanupError = error;
+ }
+ const settled = await Promise.race([
+ taskPromise.then(
+ () => true,
+ () => true
+ ),
+ delay(settleTimeoutMs).then(() => false),
+ ]);
+ const error = new Error(
+ `Timed out after ${timeoutMs}ms: ${name}${settled ? "" : `; task did not settle within ${settleTimeoutMs}ms`}`,
+ cleanupError === undefined ? undefined : { cause: cleanupError }
+ );
+ throw error;
+ } finally {
+ clearTimeout(timeout);
+ }
+};
diff --git a/apps/builder/package.json b/apps/builder/package.json
index ce53f18bed..be4d0d6bf0 100644
--- a/apps/builder/package.json
+++ b/apps/builder/package.json
@@ -157,7 +157,7 @@
"react-test-renderer": "18.3.0-canary-14898b6a9-20240318",
"type-fest": "^4.37.0",
"typescript": "7.0.2",
- "vite": "npm:rolldown-vite@^7.3.1",
+ "vite": "^6.3.4",
"vitest": "^3.1.2"
},
"sideEffects": false,
diff --git a/fixtures/react-router-cloudflare/.webstudio/data.json b/fixtures/react-router-cloudflare/.webstudio/data.json
index c1c50c33d2..a3a39cdc2e 100644
--- a/fixtures/react-router-cloudflare/.webstudio/data.json
+++ b/fixtures/react-router-cloudflare/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-a4rjtk",
+ "bundleVersion": "bundle-u14gh7",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
@@ -7,11 +7,6 @@
"createdAt": "2025-01-04T11:01:50.091+00:00",
"updatedAt": "2025-01-04T11:01:50.091+00:00",
"pages": {
- "meta": {
- "siteName": "",
- "faviconAssetId": "d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd",
- "code": ""
- },
"homePageId": "9di_L14CzctvSruIoKVvE",
"rootFolderId": "root",
"pages": [
@@ -411,6 +406,14 @@
]
],
"resources": [],
+ "projectSettings": {
+ "meta": {
+ "siteName": "",
+ "faviconAssetId": "d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd",
+ "code": ""
+ },
+ "compiler": {}
+ },
"deployment": {
"destination": "saas",
"domains": ["cli-basic-test-d0osr"],
diff --git a/fixtures/react-router-docker/.webstudio/data.json b/fixtures/react-router-docker/.webstudio/data.json
index c1c50c33d2..a3a39cdc2e 100644
--- a/fixtures/react-router-docker/.webstudio/data.json
+++ b/fixtures/react-router-docker/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-a4rjtk",
+ "bundleVersion": "bundle-u14gh7",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
@@ -7,11 +7,6 @@
"createdAt": "2025-01-04T11:01:50.091+00:00",
"updatedAt": "2025-01-04T11:01:50.091+00:00",
"pages": {
- "meta": {
- "siteName": "",
- "faviconAssetId": "d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd",
- "code": ""
- },
"homePageId": "9di_L14CzctvSruIoKVvE",
"rootFolderId": "root",
"pages": [
@@ -411,6 +406,14 @@
]
],
"resources": [],
+ "projectSettings": {
+ "meta": {
+ "siteName": "",
+ "faviconAssetId": "d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd",
+ "code": ""
+ },
+ "compiler": {}
+ },
"deployment": {
"destination": "saas",
"domains": ["cli-basic-test-d0osr"],
diff --git a/fixtures/react-router-netlify/.webstudio/data.json b/fixtures/react-router-netlify/.webstudio/data.json
index c1c50c33d2..a3a39cdc2e 100644
--- a/fixtures/react-router-netlify/.webstudio/data.json
+++ b/fixtures/react-router-netlify/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-a4rjtk",
+ "bundleVersion": "bundle-u14gh7",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
@@ -7,11 +7,6 @@
"createdAt": "2025-01-04T11:01:50.091+00:00",
"updatedAt": "2025-01-04T11:01:50.091+00:00",
"pages": {
- "meta": {
- "siteName": "",
- "faviconAssetId": "d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd",
- "code": ""
- },
"homePageId": "9di_L14CzctvSruIoKVvE",
"rootFolderId": "root",
"pages": [
@@ -411,6 +406,14 @@
]
],
"resources": [],
+ "projectSettings": {
+ "meta": {
+ "siteName": "",
+ "faviconAssetId": "d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd",
+ "code": ""
+ },
+ "compiler": {}
+ },
"deployment": {
"destination": "saas",
"domains": ["cli-basic-test-d0osr"],
diff --git a/fixtures/react-router-vercel/.webstudio/data.json b/fixtures/react-router-vercel/.webstudio/data.json
index c1c50c33d2..a3a39cdc2e 100644
--- a/fixtures/react-router-vercel/.webstudio/data.json
+++ b/fixtures/react-router-vercel/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-a4rjtk",
+ "bundleVersion": "bundle-u14gh7",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
@@ -7,11 +7,6 @@
"createdAt": "2025-01-04T11:01:50.091+00:00",
"updatedAt": "2025-01-04T11:01:50.091+00:00",
"pages": {
- "meta": {
- "siteName": "",
- "faviconAssetId": "d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd",
- "code": ""
- },
"homePageId": "9di_L14CzctvSruIoKVvE",
"rootFolderId": "root",
"pages": [
@@ -411,6 +406,14 @@
]
],
"resources": [],
+ "projectSettings": {
+ "meta": {
+ "siteName": "",
+ "faviconAssetId": "d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd",
+ "code": ""
+ },
+ "compiler": {}
+ },
"deployment": {
"destination": "saas",
"domains": ["cli-basic-test-d0osr"],
diff --git a/fixtures/ssg-cloudflare-pages/.webstudio/data.json b/fixtures/ssg-cloudflare-pages/.webstudio/data.json
index 3c2a037698..929ce962ee 100644
--- a/fixtures/ssg-cloudflare-pages/.webstudio/data.json
+++ b/fixtures/ssg-cloudflare-pages/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-a4rjtk",
+ "bundleVersion": "bundle-u14gh7",
"build": {
"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
@@ -7,11 +7,6 @@
"createdAt": "2024-07-29T12:50:07.515+00:00",
"updatedAt": "2024-07-29T12:50:07.515+00:00",
"pages": {
- "meta": {
- "siteName": "",
- "faviconAssetId": "",
- "code": ""
- },
"homePageId": "9di_L14CzctvSruIoKVvE",
"rootFolderId": "root",
"pages": [
@@ -411,6 +406,14 @@
]
],
"resources": [],
+ "projectSettings": {
+ "meta": {
+ "siteName": "",
+ "faviconAssetId": "",
+ "code": ""
+ },
+ "compiler": {}
+ },
"deployment": {
"domains": [],
"projectDomain": "cli-basic-test-d0osr"
diff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json
index 0656d2fba3..47a0d4bba5 100644
--- a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json
+++ b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-a4rjtk",
+ "bundleVersion": "bundle-u14gh7",
"build": {
"id": "8f0fdff2-e76b-4f86-9203-ea7df5f1143c",
"projectId": "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e",
@@ -7,7 +7,6 @@
"createdAt": "2026-01-04T10:46:48.415+00:00",
"updatedAt": "2026-01-04T10:46:48.415+00:00",
"pages": {
- "meta": {},
"homePageId": "Y60VJnVZMU_ifI0GnAR1N",
"rootFolderId": "root",
"pages": [
@@ -145,6 +144,10 @@
]
],
"resources": [],
+ "projectSettings": {
+ "meta": {},
+ "compiler": {}
+ },
"deployment": {
"destination": "saas",
"domains": ["fixture-client-do-not-touch-wsmel"],
diff --git a/fixtures/webstudio-cloudflare-template/.webstudio/data.json b/fixtures/webstudio-cloudflare-template/.webstudio/data.json
index 3c2a037698..929ce962ee 100644
--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json
+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-a4rjtk",
+ "bundleVersion": "bundle-u14gh7",
"build": {
"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
@@ -7,11 +7,6 @@
"createdAt": "2024-07-29T12:50:07.515+00:00",
"updatedAt": "2024-07-29T12:50:07.515+00:00",
"pages": {
- "meta": {
- "siteName": "",
- "faviconAssetId": "",
- "code": ""
- },
"homePageId": "9di_L14CzctvSruIoKVvE",
"rootFolderId": "root",
"pages": [
@@ -411,6 +406,14 @@
]
],
"resources": [],
+ "projectSettings": {
+ "meta": {
+ "siteName": "",
+ "faviconAssetId": "",
+ "code": ""
+ },
+ "compiler": {}
+ },
"deployment": {
"domains": [],
"projectDomain": "cli-basic-test-d0osr"
diff --git a/fixtures/webstudio-features/.webstudio/data.json b/fixtures/webstudio-features/.webstudio/data.json
index 0e19ebfd5e..e426b92eaa 100644
--- a/fixtures/webstudio-features/.webstudio/data.json
+++ b/fixtures/webstudio-features/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-a4rjtk",
+ "bundleVersion": "bundle-u14gh7",
"build": {
"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32",
"projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",
@@ -7,11 +7,6 @@
"createdAt": "2026-01-15T16:19:55.574+00:00",
"updatedAt": "2026-01-15T16:19:55.574+00:00",
"pages": {
- "meta": {
- "siteName": "KittyGuardedZone",
- "faviconAssetId": "7cf5892080fa66b5e6175ffd2d27c304ee6b09ce1f21847a95000225ad1afa59",
- "code": "<script>console.log('KittyGuardedZone')</script>\n"
- },
"homePageId": "7Db64ZXgYiRqKSQNR-qTQ",
"rootFolderId": "root",
"pages": [
@@ -6885,6 +6880,14 @@
}
]
],
+ "projectSettings": {
+ "meta": {
+ "siteName": "KittyGuardedZone",
+ "faviconAssetId": "7cf5892080fa66b5e6175ffd2d27c304ee6b09ce1f21847a95000225ad1afa59",
+ "code": "<script>console.log('KittyGuardedZone')</script>\n"
+ },
+ "compiler": {}
+ },
"deployment": {
"destination": "saas",
"domains": ["webstudio-fixture-project-a-0su3o"],
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 754b946051..8fe7505e73 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -42,6 +42,7 @@
"deepmerge": "^4.3.1",
"decode-named-character-reference": "^1.0.2",
"env-paths": "^3.0.0",
+ "esbuild": "^0.25.3",
"fast-deep-equal": "^3.1.3",
"immer": "^10.1.1",
"nanoid": "^5.1.5",
diff --git a/packages/cli/src/auth-config.ts b/packages/cli/src/auth-config.ts
index 9b59f97b78..dd4dd042e9 100644
--- a/packages/cli/src/auth-config.ts
+++ b/packages/cli/src/auth-config.ts
@@ -4,12 +4,16 @@ import { getAllPages, getPagePath, type Pages } from "@webstudio-is/sdk";
import { createWsAuthResources } from "@webstudio-is/wsauth";
import { migratePages } from "@webstudio-is/project-migrations/pages";
import type { PublishedProjectBundle } from "@webstudio-is/protocol";
+import type { ProjectSettings } from "@webstudio-is/project-build";
export const LOCAL_AUTH_FILE = ".webstudio/auth.json";
-export const createAuthConfigResources = (pages: Pages) =>
+export const createAuthConfigResources = (
+ pages: Pages,
+ projectSettings?: ProjectSettings
+) =>
createWsAuthResources({
- projectContent: pages.meta?.auth,
+ projectContent: projectSettings?.meta.auth ?? pages.meta?.auth,
pages: getAllPages(pages)
.filter((page) => page.meta.auth !== undefined)
.map((page) => ({
@@ -20,7 +24,11 @@ export const createAuthConfigResources = (pages: Pages) =>
export const createAuthConfigContentFromBundle = (
data: Pick<PublishedProjectBundle, "build">
-) => createAuthConfigResources(migratePages(data.build.pages)).content;
+) =>
+ createAuthConfigResources(
+ migratePages(data.build.pages),
+ data.build.projectSettings
+ ).content;
export const assertAuthConfigMatchesBundle = ({
authFileContent,
diff --git a/packages/cli/src/cli-bundle-externals.test.ts b/packages/cli/src/cli-bundle-externals.test.ts
new file mode 100644
index 0000000000..3eeb62dd8a
--- /dev/null
+++ b/packages/cli/src/cli-bundle-externals.test.ts
@@ -0,0 +1,10 @@
+import { describe, expect, test } from "vitest";
+import { isExternal } from "../vite.config";
+
+describe("CLI bundle externals", () => {
+ test("loads esbuild and Node builtins from the installed environment", () => {
+ expect(isExternal("esbuild")).toBe(true);
+ expect(isExternal("esbuild/lib/main.js")).toBe(true);
+ expect(isExternal("node:fs")).toBe(true);
+ });
+});
diff --git a/packages/cli/src/cli.test.ts b/packages/cli/src/cli.test.ts
index 600a6110ac..179e1534a3 100644
--- a/packages/cli/src/cli.test.ts
+++ b/packages/cli/src/cli.test.ts
@@ -209,11 +209,12 @@ describe("registerCommands", () => {
expect(commandNames(commands)).toEqual(
expect.arrayContaining([
"preview",
- "screenshot <url>",
+ "screenshot [url]",
"import",
"permissions",
"publish",
"domains",
+ "registry",
"mcp",
"$0",
])
@@ -236,6 +237,13 @@ describe("registerCommands", () => {
"Specify a domains command."
);
+ const registry = runGroupBuilder(commands, "registry");
+ expect(registry.childCommands).toEqual(["inspect"]);
+ expect(registry.demandCommand).toHaveBeenCalledWith(
+ 1,
+ "Specify a registry command."
+ );
+
for (const { command } of apiCommandMetadata) {
if (
cliCommandMetadata.some(
@@ -268,4 +276,12 @@ describe("registerCommands", () => {
expect(domainsHelp).toContain("webstudio domains list");
expect(domainsHelp).toContain("webstudio domains create");
});
+
+ test("documents registry inspection as a read-only nested command", async () => {
+ const output = await getHelpOutput(["registry", "inspect", "--help"]);
+
+ expect(output).toContain("--source");
+ expect(output).toContain("--item");
+ expect(output).toContain("No files are installed");
+ });
});
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index 3012f4f5df..8f96e58902 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -22,6 +22,7 @@ import {
} from "./commands/api-command-metadata";
import { schema, schemaOptions } from "./commands/schema";
import { initFlow, initOptions } from "./commands/init-flow";
+import { registryInspect, registryInspectOptions } from "./commands/registry";
import makeCLI from "yargs";
import packageJson from "../package.json" with { type: "json" };
import type { CommonYargsArgv } from "./commands/yargs-types";
@@ -190,11 +191,25 @@ export const registerCommands = (cmd: CommonYargsArgv) => {
preview
);
cmd.command(
- ["screenshot <url>"],
- "Capture a PNG screenshot of a URL with an installed Chromium-family browser",
+ ["screenshot [url]"],
+ "Capture a PNG screenshot of a URL or local generated project route",
screenshotOptions,
screenshot
);
+ cmd.command(
+ ["registry"],
+ "Inspect external component registries without installing items",
+ (yargs: CommonYargsArgv) =>
+ yargs
+ .command(
+ ["inspect"],
+ "Inspect one local or remote shadcn registry item",
+ registryInspectOptions,
+ registryInspect
+ )
+ .demandCommand(1, "Specify a registry command."),
+ () => undefined
+ );
const { direct, grouped } = getGroupedCommands(cliCommandMetadata);
for (const metadata of direct) {
registerApiCommand(cmd, metadata.cliCommand, metadata);
diff --git a/packages/cli/src/commands/api-command-metadata.ts b/packages/cli/src/commands/api-command-metadata.ts
index cdbcc73adc..688f3a1faf 100644
--- a/packages/cli/src/commands/api-command-metadata.ts
+++ b/packages/cli/src/commands/api-command-metadata.ts
@@ -1,5 +1,6 @@
import {
publicApiOperations,
+ type InputJsonSchema,
type PublicApiOperationMethod,
type PublicApiOperationPermit,
} from "@webstudio-is/protocol";
@@ -17,6 +18,8 @@ type ApiCommandMetadata = {
inputFields: readonly string[];
requiredInputFields: readonly string[];
inputFieldTypes: Partial<Record<string, "array">>;
+ inputSchema: InputJsonSchema;
+ outputSchema?: InputJsonSchema;
requiredOptions?: readonly string[];
examples: readonly string[];
};
@@ -77,9 +80,10 @@ export const topLevelCliCommandMetadata = [
{
command: "screenshot",
description:
- "Capture a PNG screenshot of a URL with an installed Chromium-family browser",
+ "Capture a PNG screenshot of an absolute URL or a generated project route with an installed Chromium-family browser",
examples: [
'webstudio screenshot "https://example.com" --output current.png --width 1440 --height 900',
+ "webstudio screenshot --path /pricing --output pricing.png",
],
},
{
@@ -122,6 +126,7 @@ export const topLevelCliCommandMetadata = [
const apiCommandOptionsByCommand: Partial<
Record<ApiCommandName, ApiCommandOptions>
> = {
+ audit: apiCommand.auditCommandOptions,
snapshot: apiCommand.snapshotCommandOptions,
"apply-patch": apiCommand.applyPatchCommandOptions,
"list-pages": apiCommand.pagesCommandOptions,
@@ -200,6 +205,7 @@ const apiCommandOptionsByCommand: Partial<
"delete-domain": apiCommand.deleteDomainCommandOptions,
"verify-domain": apiCommand.verifyDomainCommandOptions,
"list-assets": apiCommand.assetsCommandOptions,
+ "list-fonts": apiCommand.fontsCommandOptions,
"upload-asset": apiCommand.uploadAssetCommandOptions,
"upload-assets": apiCommand.uploadAssetsCommandOptions,
"find-asset-usage": apiCommand.assetCommandOptions,
@@ -215,11 +221,16 @@ export const apiCommandMetadata = publicApiOperations.map((operation) => ({
inputFields: operation.inputFields,
requiredInputFields: operation.requiredInputFields,
inputFieldTypes: operation.inputFieldTypes,
+ inputSchema: operation.inputSchema,
+ ...(operation.outputSchema === undefined
+ ? {}
+ : { outputSchema: operation.outputSchema }),
requiredOptions: operation.requiredOptions,
examples: operation.examples,
})) satisfies ApiCommandMetadata[];
export const highLevelCliCommands = [
+ { command: "audit", operation: "audit" },
{ command: "permissions", operation: "permissions" },
{
command: "get-marketplace-product",
diff --git a/packages/cli/src/commands/api-command.test.ts b/packages/cli/src/commands/api-command.test.ts
index d3831434b6..d286e98bb6 100644
--- a/packages/cli/src/commands/api-command.test.ts
+++ b/packages/cli/src/commands/api-command.test.ts
@@ -1,10 +1,12 @@
import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import makeCLI from "yargs";
import {
getPublicApiOperation,
publicApiOperations,
} from "@webstudio-is/protocol";
import { apiCompatibilityHeaders } from "./api";
-import { apiCommand } from "./api-command";
+import { apiCommand, auditCommandOptions } from "./api-command";
+import type { CommonYargsArgv } from "./yargs-types";
import { apiCommandMetadata } from "./api-command-metadata";
const apiCalls = new Proxy({} as Record<string, ReturnType<typeof vi.fn>>, {
@@ -112,8 +114,8 @@ const expectJsonOutput = (command: string) => {
version: 1,
source: expect.any(String),
committed: expect.any(Boolean),
- namespaces: { read: [], write: [], invalidated: [], missing: [] },
- diagnostics: [],
+ namespaceCounts: { read: 0, write: 0, invalidated: 0, missing: 0 },
+ diagnosticCount: 0,
},
},
});
@@ -425,7 +427,7 @@ test("passes refresh to local-capable command session", async () => {
);
const session = createCliProjectSession.mock.results[0]?.value;
- expect(session.refresh).toHaveBeenCalledWith(["pages"]);
+ expect(session.refresh).toHaveBeenCalledWith(["pages", "projectSettings"]);
expect(session.read).toHaveBeenCalledWith(
"pages.list",
{ projectId: "project-1", includeFolders: undefined },
@@ -472,6 +474,102 @@ test("calls build snapshot for configured project", async () => {
});
});
+test("runs a focused project audit", async () => {
+ await expectCommandCall({
+ options: {
+ command: "audit",
+ scopes: ["accessibility", "seo"],
+ severities: ["error", "warning"],
+ pagePath: "/pricing",
+ limit: 25,
+ cursor: "cursor-1",
+ verbose: true,
+ },
+ call: apiCalls.audit,
+ connection: {
+ scopes: ["accessibility", "seo"],
+ severities: ["error", "warning"],
+ pageId: undefined,
+ pagePath: "/pricing",
+ limit: 25,
+ cursor: "cursor-1",
+ verbose: true,
+ },
+ });
+});
+
+test("parses the documented repeated audit scope options", async () => {
+ const parsed = await auditCommandOptions(
+ makeCLI([]).exitProcess(false) as unknown as CommonYargsArgv
+ ).parseAsync([
+ "--scopes",
+ "accessibility",
+ "--scopes",
+ "seo",
+ "--page-path",
+ "/pricing",
+ ]);
+
+ expect(parsed).toMatchObject({
+ scopes: ["accessibility", "seo"],
+ pagePath: "/pricing",
+ });
+});
+
+test("prints a compact project audit without --json", async () => {
+ mockConfig();
+ apiCalls.audit.mockResolvedValueOnce({
+ summary: {
+ total: 1,
+ selectedTotal: 1,
+ bySeverity: { error: 1, warning: 0, info: 0 },
+ },
+ findings: [
+ {
+ severity: "error",
+ scope: "accessibility",
+ ruleId: "missing-alt",
+ message: "Image has no alt prop.",
+ location: { instanceId: "image-1" },
+ },
+ ],
+ skippedCheckCount: 0,
+ manualCheckCount: 3,
+ nextCursor: null,
+ });
+
+ await apiCommand({ command: "audit" }, dependencies);
+
+ expect(console.info).toHaveBeenCalledWith(
+ "Audit: 1 findings (1 errors, 0 warnings, 0 info)"
+ );
+ expect(console.info).toHaveBeenCalledWith(
+ "[ERROR] accessibility/missing-alt: Image has no alt prop. (image-1)"
+ );
+ expect(console.info).toHaveBeenCalledWith("3 manual checks recommended.");
+});
+
+test("labels filtered audit totals without implying hidden findings are returned", async () => {
+ mockConfig();
+ apiCalls.audit.mockResolvedValueOnce({
+ summary: {
+ total: 5,
+ selectedTotal: 1,
+ bySeverity: { error: 1, warning: 3, info: 1 },
+ },
+ findings: [],
+ skippedCheckCount: 0,
+ manualCheckCount: 0,
+ nextCursor: "next",
+ });
+
+ await apiCommand({ command: "audit" }, dependencies);
+
+ expect(console.info).toHaveBeenCalledWith(
+ "Audit: 1 selected findings (5 across all severities) (1 errors, 3 warnings, 1 info)"
+ );
+});
+
test("applies build patch transactions for configured project", async () => {
await expectCommandCall({
options: {
@@ -1539,6 +1637,14 @@ test("calls asset list with pagination", async () => {
});
});
+test("lists fonts with optional system stacks", async () => {
+ await expectCommandCall({
+ options: { command: "list-fonts", includeSystem: false },
+ call: apiCalls.listFonts,
+ connection: { includeSystem: false },
+ });
+});
+
test("uploads asset descriptor with local file reader", async () => {
mockConfig();
readFile.mockResolvedValueOnce(
@@ -1678,11 +1784,17 @@ test("lists design tokens with filters", async () => {
options: {
command: "list-design-tokens",
filter: "brand",
+ includeStyles: true,
withUsage: true,
sort: "usage",
},
call: apiCalls.listDesignTokens,
- connection: { filter: "brand", withUsage: true, sort: "usage" },
+ connection: {
+ filter: "brand",
+ includeStyles: true,
+ withUsage: true,
+ sort: "usage",
+ },
});
});
diff --git a/packages/cli/src/commands/api-command.ts b/packages/cli/src/commands/api-command.ts
index 749491a977..ca7a1b4fce 100644
--- a/packages/cli/src/commands/api-command.ts
+++ b/packages/cli/src/commands/api-command.ts
@@ -149,7 +149,7 @@ export const createPageCommandOptions = (yargs: CommonYargsArgv) =>
})
.option("title", {
type: "string",
- describe: "Page title expression; defaults to --name",
+ describe: "Page title text or expression; defaults to --name",
})
.option("parent-folder", {
type: "string",
@@ -173,15 +173,15 @@ export const updatePageCommandOptions = (yargs: CommonYargsArgv) =>
})
.option("title", {
type: "string",
- describe: "Update page title expression",
+ describe: "Update page title text or expression",
})
.option("description", {
type: "string",
- describe: "Update page meta description expression",
+ describe: "Update page meta description text or expression",
})
.option("language", {
type: "string",
- describe: "Update page language expression",
+ describe: "Update page language text or expression",
})
.option("redirect", {
type: "string",
@@ -404,17 +404,15 @@ const pageTemplateFieldsCommandOptions = (
})
.option("title", {
type: "string",
- describe:
- 'Page template title expression. For fixed text use a JavaScript string literal such as "\\"Landing\\""',
+ describe: "Page template title text or expression",
})
.option("description", {
type: "string",
- describe:
- 'Page template meta description expression. For fixed text use a JavaScript string literal such as "\\"Plans for teams\\""',
+ describe: "Page template meta description text or expression",
})
.option("language", {
type: "string",
- describe: 'Page template language expression, for example "\\"en\\""',
+ describe: "Page template language text or expression",
})
.option("social-image-url", {
type: "string",
@@ -789,8 +787,13 @@ export const designTokensCommandOptions = (yargs: CommonYargsArgv) =>
type: "string",
describe: "Only return design tokens whose name contains this text",
})
+ .option("include-styles", {
+ type: "boolean",
+ describe: "Include full inline style declarations for each design token",
+ })
.option("with-usage", {
type: "boolean",
+ default: true,
describe: "Include how many instances use each design token",
})
.option("sort", {
@@ -1146,6 +1149,61 @@ export const assetsCommandOptions = (yargs: CommonYargsArgv) =>
describe: "Maximum number of assets to return",
});
+export const auditCommandOptions = (yargs: CommonYargsArgv) =>
+ apiCommandOptions(yargs)
+ .option("scopes", {
+ type: "array",
+ string: true,
+ choices: [
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ] as const,
+ describe: "Audit only the selected project-quality scopes",
+ })
+ .option("severities", {
+ type: "array",
+ string: true,
+ choices: ["error", "warning", "info"] as const,
+ describe: "Return only findings with the selected severities",
+ })
+ .option("page-id", {
+ type: "string",
+ describe: "Audit page-owned findings for one page id",
+ })
+ .option("page-path", {
+ type: "string",
+ describe: "Audit page-owned findings for one page path",
+ })
+ .option("limit", {
+ type: "number",
+ describe: "Maximum findings to return, from 1 to 200",
+ })
+ .option("cursor", {
+ type: "string",
+ describe: "Pagination cursor returned by the previous audit call",
+ })
+ .option("verbose", {
+ type: "boolean",
+ describe:
+ "Include full finding evidence, remediation, skipped checks, and manual-check workflows",
+ })
+ .example("$0 audit --json", "Run every project audit")
+ .example(
+ "$0 audit --scopes accessibility --scopes seo --page-path /pricing --json",
+ "Audit accessibility and SEO for one page"
+ );
+
+export const fontsCommandOptions = (yargs: CommonYargsArgv) =>
+ apiCommandOptions(yargs).option("include-system", {
+ type: "boolean",
+ default: true,
+ describe: "Include built-in system font stacks",
+ });
+
export const uploadAssetCommandOptions = (yargs: CommonYargsArgv) =>
requiredInputOption(
apiCommandOptions(yargs).option("assets-dir", {
@@ -1291,11 +1349,18 @@ type ApiCommandOptions = {
position?: "before-local" | "after-local" | "before" | "after";
filter?: string;
withUsage?: boolean;
+ includeStyles?: boolean;
+ includeSystem?: boolean;
scopeInstance?: string;
type?: "image" | "font" | "file";
sort?: "name" | "usage" | "size" | "createdAt";
cursor?: string;
limit?: number;
+ scopes?: Array<"accessibility" | "security" | "seo" | "assets" | "styles">;
+ severities?: Array<"error" | "warning" | "info">;
+ pageId?: string;
+ pagePath?: string;
+ verbose?: boolean;
dryRun?: boolean;
refresh?: boolean;
};
@@ -1726,6 +1791,65 @@ type ApiCommandHandler = (
dependencies: ApiCommandDependencies
) => Promise<unknown>;
+const printAuditReport = (value: unknown) => {
+ if (typeof value !== "object" || value === null) {
+ console.info("Audit completed.");
+ return;
+ }
+ const result = value as {
+ summary?: {
+ total?: number;
+ selectedTotal?: number;
+ bySeverity?: Record<string, number>;
+ };
+ findings?: Array<{
+ severity?: string;
+ scope?: string;
+ ruleId?: string;
+ message?: string;
+ location?: Record<string, unknown>;
+ }>;
+ skippedChecks?: unknown[];
+ manualChecks?: unknown[];
+ skippedCheckCount?: number;
+ manualCheckCount?: number;
+ nextCursor?: string | null;
+ };
+ const severity = result.summary?.bySeverity ?? {};
+ const total = result.summary?.total ?? 0;
+ const selectedTotal = result.summary?.selectedTotal ?? total;
+ console.info(
+ `Audit: ${
+ selectedTotal === total
+ ? `${total} findings`
+ : `${selectedTotal} selected findings (${total} across all severities)`
+ } ` +
+ `(${severity.error ?? 0} errors, ${severity.warning ?? 0} warnings, ${severity.info ?? 0} info)`
+ );
+ for (const finding of result.findings ?? []) {
+ const location = Object.values(finding.location ?? {})
+ .flatMap((item) => (Array.isArray(item) ? item : [item]))
+ .filter((item) => item !== undefined)
+ .join(" ");
+ console.info(
+ `[${finding.severity?.toUpperCase() ?? "INFO"}] ${finding.scope ?? "audit"}/${finding.ruleId ?? "finding"}: ${finding.message ?? ""}${location === "" ? "" : ` (${location})`}`
+ );
+ }
+ const skippedCheckCount =
+ result.skippedCheckCount ?? result.skippedChecks?.length ?? 0;
+ const manualCheckCount =
+ result.manualCheckCount ?? result.manualChecks?.length ?? 0;
+ if (skippedCheckCount > 0) {
+ console.info(`${skippedCheckCount} checks skipped.`);
+ }
+ if (manualCheckCount > 0) {
+ console.info(`${manualCheckCount} manual checks recommended.`);
+ }
+ if (result.nextCursor != null) {
+ console.info(`More findings: rerun with --cursor '${result.nextCursor}'.`);
+ }
+};
+
const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
whoami: async (_options, connection, dependencies) =>
runProjectSessionCommand("whoami", {}, connection, dependencies),
@@ -1745,6 +1869,21 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
dependencies
);
},
+ audit: async (options, connection, dependencies) =>
+ runProjectSessionCommand(
+ "audit",
+ {
+ scopes: listOption(options.scopes),
+ severities: listOption(options.severities),
+ pageId: options.pageId,
+ pagePath: options.pagePath,
+ limit: options.limit,
+ cursor: options.cursor,
+ verbose: options.verbose,
+ },
+ connection,
+ dependencies
+ ),
"apply-patch": async (options, connection, dependencies) => {
const patchInput = await readJsonFile(
dependencies,
@@ -2361,6 +2500,7 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
const input = {
filter: options.filter,
withUsage: options.withUsage,
+ includeStyles: options.includeStyles,
sort: designTokenSortOption(options.sort),
};
return runProjectSessionCommand(
@@ -2709,6 +2849,13 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
dependencies
);
},
+ "list-fonts": async (options, connection, dependencies) =>
+ runProjectSessionCommand(
+ "list-fonts",
+ { includeSystem: options.includeSystem },
+ connection,
+ dependencies
+ ),
"upload-asset": async (options, connection, dependencies) => {
const input = createLocalUploadAssetInput({
asset: await readInputObject<UploadAssetInput>(dependencies, options),
@@ -2779,7 +2926,7 @@ export const apiCommand = async (
const start = Date.now();
let projectId: string | undefined;
try {
- if (options.json !== true) {
+ if (options.json !== true && options.command !== "audit") {
throw new Error(`${options.command} currently requires --json.`);
}
@@ -2809,16 +2956,23 @@ export const apiCommand = async (
const session = isProjectSessionEnvelope(response)
? getProjectSessionMeta(response)
: undefined;
- printJson({
- ok: true,
- data: isProjectSessionEnvelope(response) ? response.result : response,
- meta: {
- command: options.command,
- projectId: connection.projectId,
- durationMs: Date.now() - start,
- ...(session === undefined ? {} : { session }),
- },
- });
+ const result = isProjectSessionEnvelope(response)
+ ? response.result
+ : response;
+ if (options.command === "audit" && options.json !== true) {
+ printAuditReport(result);
+ } else {
+ printJson({
+ ok: true,
+ data: result,
+ meta: {
+ command: options.command,
+ projectId: connection.projectId,
+ durationMs: Date.now() - start,
+ ...(session === undefined ? {} : { session }),
+ },
+ });
+ }
} catch (error) {
const message = getCliErrorMessage(error);
if (options.json === true) {
diff --git a/packages/cli/src/commands/link.test.ts b/packages/cli/src/commands/link.test.ts
index 905c43fb82..18298da368 100644
--- a/packages/cli/src/commands/link.test.ts
+++ b/packages/cli/src/commands/link.test.ts
@@ -65,7 +65,7 @@ test("saves global credentials and local project config", async () => {
token: "token-1",
},
});
- expect(JSON.parse(await readFile(LOCAL_CONFIG_FILE, "utf8"))).toEqual({
- projectId,
- });
+ expect(await readFile(LOCAL_CONFIG_FILE, "utf8")).toBe(
+ `${JSON.stringify({ projectId }, undefined, 2)}\n`
+ );
});
diff --git a/packages/cli/src/commands/link.ts b/packages/cli/src/commands/link.ts
index 9b49c13f7e..05d3a43e01 100644
--- a/packages/cli/src/commands/link.ts
+++ b/packages/cli/src/commands/link.ts
@@ -129,7 +129,7 @@ export const saveShareLink = async (shareLink: string) => {
await mkdir(dirname(localConfigPath), { recursive: true });
await writeFile(
localConfigPath,
- JSON.stringify(localConfig, null, 2),
+ `${JSON.stringify(localConfig, null, 2)}\n`,
"utf8"
);
diff --git a/packages/cli/src/commands/man.test.ts b/packages/cli/src/commands/man.test.ts
index c12eac9ec8..f70b98e6b4 100644
--- a/packages/cli/src/commands/man.test.ts
+++ b/packages/cli/src/commands/man.test.ts
@@ -202,6 +202,7 @@ test("prints api manual as json", () => {
useCase: "Update project settings",
commands: [
'MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}',
+ 'MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}',
],
}),
])
@@ -326,12 +327,11 @@ test("prints llm manual with discovery rules", () => {
expect(output).toContain(
"Use `bind-props` only when the prop must stay dynamic"
);
- expect(output).toContain('"\\"Pricing | Acme\\""');
expect(output).toContain(
- '{"pageId":"page-id","values":{"title":"\\"Pricing | Acme\\"","meta":{"description":"\\"Plans for teams\\""}}}'
+ '{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}'
);
expect(output).toContain(
- '{"resourceId":"resource-id","values":{"url":"\\"https://api.example.com/items\\""}}'
+ '{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}'
);
expect(output).toContain(
"Make edits through Webstudio semantic commands/MCP tools"
@@ -427,7 +427,7 @@ test("prints llm manual as json with implementation process", () => {
"Use direct values for static strings and bindings only for dynamic expressions/resources/actions."
);
expect(output.rules).toContain(
- "For expression-backed fields that need fixed text, encode the fixed text as a quoted JavaScript string literal expression."
+ "Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value."
);
expect(output.visionVerificationLoop).toContain(
getVisionVerificationLoop({ includeDiff: true })[1]
@@ -502,8 +502,12 @@ test("prints mcp manual as json", () => {
expect.stringContaining("viewport"),
])
);
- expect(output.visionVerificationLoop).toContain(
- "When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair."
+ expect(output.visionVerificationLoop).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining(
+ "Add expectedText when a specific visible phrase must be present"
+ ),
+ ])
);
expect(output.screenshotVerification).toContain("screenshot.diff");
expect(output.screenshotVerification).toContain("OCR textAnalysis");
@@ -517,6 +521,16 @@ test("prints mcp manual as json", () => {
outputDir: "visual-diff",
threshold: 0.1,
ignoreTopNormalizedY: 0,
+ expectedText: ["Pricing", "Start free"],
+ expectedVisual: {
+ maxMismatchPercentage: 2,
+ maxChangedRegions: 3,
+ dominantColorChange: {
+ channel: "luminance",
+ direction: "increase",
+ minMagnitude: 10,
+ },
+ },
},
]);
expect(output.mcpArgumentExamples["update-text"]).toEqual([
diff --git a/packages/cli/src/commands/man.ts b/packages/cli/src/commands/man.ts
index acc0a75f99..13ebe5222d 100644
--- a/packages/cli/src/commands/man.ts
+++ b/packages/cli/src/commands/man.ts
@@ -435,6 +435,9 @@ const apiCommandsByArea = {
setupAndDiscovery: cliCommandMetadata
.filter(({ cliCommand }) => cliCommand === "permissions")
.map(({ cliCommand }) => cliCommand),
+ projectQuality: cliCommandMetadata
+ .filter(({ cliCommand }) => cliCommand === "audit")
+ .map(({ cliCommand }) => cliCommand),
publishAndDomains: cliCommandMetadata
.filter(
({ cliCommand }) =>
@@ -608,7 +611,9 @@ const createLlmManualJson = (
readCommands,
writeCommands,
sessionBehavior: [
- "Read meta.session.source and meta.session.namespaces to understand whether data came from local cache, remote refresh, dry-run, or server-only execution.",
+ "Read meta.session.source and meta.session.namespaceCounts to understand whether data came from local cache, remote refresh, dry-run, or server-only execution.",
+ "For a dry-run mutation, inspect meta.session.transaction for the computed Builder patch; meta.session.version is its base build version.",
+ "Use status with { verbose: true } only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.",
"Use --refresh before a local-capable command when the cached snapshot may be stale.",
"A mutation is durable only when meta.session.committed is true.",
],
@@ -700,7 +705,7 @@ const topics = {
refreshFlag:
"Use --refresh to refresh required namespaces before local-capable commands.",
metadata:
- "Successful command JSON includes meta.session with operationId, buildId, version, source, committed, compatibility, namespace metadata, and diagnostics.",
+ "Successful command JSON includes compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.",
},
},
apiDocSections
diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.ts
index abac90ad06..66f3a11024 100644
--- a/packages/cli/src/commands/mcp.test.ts
+++ b/packages/cli/src/commands/mcp.test.ts
@@ -689,6 +689,15 @@ const createCaptureScreenshotMock = (events: string[]) =>
fullPage: options.fullPage === true,
elapsedMs: 1,
warnings: [],
+ layout: {
+ viewportWidth: options.width,
+ viewportHeight: options.height,
+ contentWidth: options.width + 20,
+ contentHeight: options.height * 2,
+ horizontalOverflow: true,
+ images: [],
+ resources: [],
+ },
};
});
@@ -737,6 +746,13 @@ test("captures stale path screenshots through the restarted preview server", asy
)
).resolves.toMatchObject({
output: "screenshot.png",
+ layout: {
+ viewportWidth: 1440,
+ contentWidth: 1460,
+ horizontalOverflow: true,
+ images: [],
+ resources: [],
+ },
});
expect(captureScreenshot).toHaveBeenCalledWith(
diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.ts
index 8cce11c833..040555442f 100644
--- a/packages/cli/src/commands/mcp.ts
+++ b/packages/cli/src/commands/mcp.ts
@@ -86,6 +86,8 @@ type McpScreenshotInput = {
port?: number;
viewport: { width: number; height: number };
fullPage?: boolean;
+ includeImageMetrics?: boolean;
+ includeResourceMetrics?: boolean;
browser?: CaptureScreenshotInput["browser"];
browserPath?: string;
waitUntil?: CaptureScreenshotInput["waitUntil"];
@@ -368,6 +370,8 @@ const createMcpPreviewHandlers = ({
width: input.viewport.width,
height: input.viewport.height,
fullPage: input.fullPage,
+ includeImageMetrics: input.includeImageMetrics,
+ includeResourceMetrics: input.includeResourceMetrics,
browser: input.browser ?? "auto",
browserPath: input.browserPath,
waitUntil: input.waitUntil,
@@ -906,6 +910,7 @@ const createCliMcpHost = async () => {
fullPage: result.fullPage,
elapsedMs: result.elapsedMs,
warnings: result.warnings,
+ layout: result.layout,
};
},
async diffScreenshots(input) {
diff --git a/packages/cli/src/commands/preview.test.ts b/packages/cli/src/commands/preview.test.ts
index d7ad303c2c..95f51a866f 100644
--- a/packages/cli/src/commands/preview.test.ts
+++ b/packages/cli/src/commands/preview.test.ts
@@ -49,6 +49,10 @@ test("prepares preview by syncing missing data and generating the app template",
})),
spinner: vi.fn(),
writeFile: vi.fn(async () => undefined),
+ materializeManagedAgents: vi.fn(async () => ({
+ path: "/project/AGENTS.md",
+ status: "unchanged" as const,
+ })),
};
const accessLocalDataFile = vi.fn(async () => {
throw Object.assign(new Error("missing"), { code: "ENOENT" });
diff --git a/packages/cli/src/commands/registry.test.ts b/packages/cli/src/commands/registry.test.ts
new file mode 100644
index 0000000000..b3d7d5cea5
--- /dev/null
+++ b/packages/cli/src/commands/registry.test.ts
@@ -0,0 +1,231 @@
+import { expect, test, vi } from "vitest";
+import { inspectRegistry } from "./registry";
+
+test("inspects an item embedded in a local registry index", async () => {
+ const readFile = vi.fn(async () =>
+ JSON.stringify({
+ items: [
+ {
+ name: "button",
+ title: "Button",
+ type: "registry:ui",
+ dependencies: ["class-variance-authority"],
+ registryDependencies: ["utils"],
+ files: [
+ {
+ path: "registry/new-york/button/button.tsx",
+ target: "components/ui/button.tsx",
+ type: "registry:ui",
+ },
+ ],
+ docs: "https://example.com/button",
+ },
+ ],
+ })
+ );
+
+ await expect(
+ inspectRegistry(
+ { source: "/tmp/registry.json", item: "button" },
+ { readFile, fetch: async (source) => fetch(source) }
+ )
+ ).resolves.toEqual({
+ source: "/tmp/registry.json",
+ name: "button",
+ title: "Button",
+ description: undefined,
+ type: "registry:ui",
+ dependencies: ["class-variance-authority"],
+ devDependencies: [],
+ registryDependencies: ["utils"],
+ files: [
+ {
+ path: "registry/new-york/button/button.tsx",
+ target: "components/ui/button.tsx",
+ type: "registry:ui",
+ },
+ ],
+ docs: "https://example.com/button",
+ compatibility: {
+ status: "unsupported",
+ installation: {
+ status: "unsupported",
+ reason:
+ "Webstudio does not install external shadcn registry files into a project.",
+ },
+ conversion: {
+ status: "unsupported",
+ reason:
+ "Webstudio does not convert external React registry files into editable Webstudio components yet.",
+ },
+ requirements: {
+ dependencies: ["class-variance-authority"],
+ devDependencies: [],
+ registryDependencies: ["utils"],
+ },
+ sourceCode: {
+ status: "not-analyzed",
+ reason:
+ "Inspecting registry metadata does not execute or analyze arbitrary external source files.",
+ },
+ manualSteps: [
+ "Use the item metadata as a reference to recreate the UI with Webstudio components and styles.",
+ ],
+ },
+ });
+ expect(readFile).toHaveBeenCalledWith("/tmp/registry.json", "utf8");
+});
+
+test("loads a remote item file when the registry index only lists its name", async () => {
+ const fetch = vi.fn(async (source: string) => ({
+ ok: true,
+ status: 200,
+ text: async () =>
+ source.endsWith("registry.json")
+ ? JSON.stringify({ items: [{ name: "dialog" }] })
+ : JSON.stringify({
+ name: "dialog",
+ files: [
+ {
+ path: "registry/new-york/dialog/dialog.tsx",
+ type: "registry:ui",
+ },
+ ],
+ }),
+ }));
+
+ await expect(
+ inspectRegistry(
+ {
+ source: "https://registry.example.com/r/registry.json",
+ item: "dialog",
+ },
+ { readFile: vi.fn(), fetch: async (source) => fetch(source) }
+ )
+ ).resolves.toMatchObject({
+ source: "https://registry.example.com/r/dialog.json",
+ name: "dialog",
+ files: [
+ {
+ path: "registry/new-york/dialog/dialog.tsx",
+ type: "registry:ui",
+ },
+ ],
+ compatibility: {
+ status: "unsupported",
+ requirements: { registryDependencies: [] },
+ },
+ });
+ expect(fetch).toHaveBeenNthCalledWith(
+ 1,
+ "https://registry.example.com/r/registry.json"
+ );
+ expect(fetch).toHaveBeenNthCalledWith(
+ 2,
+ "https://registry.example.com/r/dialog.json"
+ );
+});
+
+test("preserves multi-file items and transitive registry dependencies", async () => {
+ await expect(
+ inspectRegistry(
+ { source: "/tmp/accordion.json" },
+ {
+ readFile: vi.fn(async () =>
+ JSON.stringify({
+ name: "accordion",
+ title: "Accordion",
+ type: "registry:ui",
+ dependencies: ["@radix-ui/react-accordion"],
+ devDependencies: ["tailwindcss-animate"],
+ registryDependencies: ["button", "separator"],
+ files: [
+ {
+ path: "registry/new-york/accordion/accordion.tsx",
+ target: "components/ui/accordion.tsx",
+ type: "registry:ui",
+ },
+ {
+ path: "registry/new-york/accordion/accordion-demo.tsx",
+ target: "components/accordion-demo.tsx",
+ type: "registry:example",
+ },
+ ],
+ docs: "https://example.com/accordion",
+ })
+ ),
+ fetch: async (source) => fetch(source),
+ }
+ )
+ ).resolves.toEqual({
+ source: "/tmp/accordion.json",
+ name: "accordion",
+ title: "Accordion",
+ description: undefined,
+ type: "registry:ui",
+ dependencies: ["@radix-ui/react-accordion"],
+ devDependencies: ["tailwindcss-animate"],
+ registryDependencies: ["button", "separator"],
+ files: [
+ {
+ path: "registry/new-york/accordion/accordion.tsx",
+ target: "components/ui/accordion.tsx",
+ type: "registry:ui",
+ },
+ {
+ path: "registry/new-york/accordion/accordion-demo.tsx",
+ target: "components/accordion-demo.tsx",
+ type: "registry:example",
+ },
+ ],
+ docs: "https://example.com/accordion",
+ compatibility: {
+ status: "unsupported",
+ installation: expect.objectContaining({ status: "unsupported" }),
+ conversion: expect.objectContaining({ status: "unsupported" }),
+ requirements: {
+ dependencies: ["@radix-ui/react-accordion"],
+ devDependencies: ["tailwindcss-animate"],
+ registryDependencies: ["button", "separator"],
+ },
+ sourceCode: expect.objectContaining({ status: "not-analyzed" }),
+ manualSteps: expect.any(Array),
+ },
+ });
+});
+
+test("accepts a matching item name for a direct registry item source", async () => {
+ await expect(
+ inspectRegistry(
+ { source: "/tmp/button.json", item: "button" },
+ {
+ readFile: vi.fn(async () => JSON.stringify({ name: "button" })),
+ fetch: async (source) => fetch(source),
+ }
+ )
+ ).resolves.toMatchObject({ source: "/tmp/button.json", name: "button" });
+
+ await expect(
+ inspectRegistry(
+ { source: "/tmp/button.json", item: "dialog" },
+ {
+ readFile: vi.fn(async () => JSON.stringify({ name: "button" })),
+ fetch: async (source) => fetch(source),
+ }
+ )
+ ).rejects.toThrow("contains item button, not dialog");
+});
+
+test("rejects a registry index without an item name", async () => {
+ await expect(
+ inspectRegistry(
+ { source: "/tmp/registry.json", item: undefined },
+ {
+ readFile: vi.fn(async () =>
+ JSON.stringify({ items: [{ name: "button" }] })
+ ),
+ fetch,
+ }
+ )
+ ).rejects.toThrow("Pass --item <name>");
+});
diff --git a/packages/cli/src/commands/registry.ts b/packages/cli/src/commands/registry.ts
new file mode 100644
index 0000000000..885a940a34
--- /dev/null
+++ b/packages/cli/src/commands/registry.ts
@@ -0,0 +1,255 @@
+import { readFile } from "node:fs/promises";
+import { dirname, isAbsolute, resolve } from "node:path";
+import { z } from "zod";
+import { printJson } from "../json-output";
+import type {
+ CommonYargsArgv,
+ StrictYargsOptionsToInterface,
+} from "./yargs-types";
+
+const registryFileSchema = z.object({
+ path: z.string(),
+ type: z.string().optional(),
+ target: z.string().optional(),
+});
+
+const registryItemSchema = z.object({
+ name: z.string(),
+ title: z.string().optional(),
+ description: z.string().optional(),
+ type: z.string().optional(),
+ dependencies: z.array(z.string()).optional(),
+ devDependencies: z.array(z.string()).optional(),
+ registryDependencies: z.array(z.string()).optional(),
+ files: z.array(registryFileSchema).optional(),
+ docs: z.unknown().optional(),
+});
+
+const registrySchema = z.object({
+ items: z.array(registryItemSchema).optional(),
+});
+
+type RegistryItem = z.infer<typeof registryItemSchema>;
+
+type RegistryDependencies = {
+ readFile: (source: string, encoding: "utf8") => Promise<string>;
+ fetch: (source: string) => Promise<{
+ ok: boolean;
+ status: number;
+ text: () => Promise<string>;
+ }>;
+};
+
+const defaultDependencies: RegistryDependencies = {
+ readFile: (source, encoding) => readFile(source, encoding),
+ fetch: async (source) => fetch(source),
+};
+
+const isRemoteSource = (source: string) => /^https?:\/\//i.test(source);
+
+const parseRegistryJson = (source: string, content: string) => {
+ try {
+ return JSON.parse(content) as unknown;
+ } catch {
+ throw new Error(`Registry source ${source} is not valid JSON.`);
+ }
+};
+
+const readRegistrySource = async ({
+ source,
+ dependencies,
+}: {
+ source: string;
+ dependencies: RegistryDependencies;
+}) => {
+ if (isRemoteSource(source)) {
+ const response = await dependencies.fetch(source);
+ if (response.ok === false) {
+ throw new Error(
+ `Could not read registry source ${source}: HTTP ${response.status}.`
+ );
+ }
+ return parseRegistryJson(source, await response.text());
+ }
+ return parseRegistryJson(source, await dependencies.readFile(source, "utf8"));
+};
+
+const getItemSource = ({ source, item }: { source: string; item: string }) => {
+ if (isRemoteSource(source)) {
+ return new URL(`${item}.json`, source).toString();
+ }
+ const absoluteSource = isAbsolute(source) ? source : resolve(source);
+ return resolve(dirname(absoluteSource), `${item}.json`);
+};
+
+const parseRegistryItem = (source: string, value: unknown) => {
+ const parsed = registryItemSchema.safeParse(value);
+ if (parsed.success === false) {
+ throw new Error(
+ `Registry item from ${source} is invalid: ${parsed.error.issues[0]?.message ?? "unknown error"}.`
+ );
+ }
+ return parsed.data;
+};
+
+const serializeRegistryItem = ({
+ source,
+ item,
+}: {
+ source: string;
+ item: RegistryItem;
+}) => ({
+ source,
+ name: item.name,
+ title: item.title,
+ description: item.description,
+ type: item.type,
+ dependencies: item.dependencies ?? [],
+ devDependencies: item.devDependencies ?? [],
+ registryDependencies: item.registryDependencies ?? [],
+ files: (item.files ?? []).map((file) => ({
+ path: file.path,
+ target: file.target,
+ type: file.type,
+ })),
+ docs: item.docs,
+});
+
+const getCompatibilityReport = (item: RegistryItem) => ({
+ status: "unsupported" as const,
+ installation: {
+ status: "unsupported" as const,
+ reason:
+ "Webstudio does not install external shadcn registry files into a project.",
+ },
+ conversion: {
+ status: "unsupported" as const,
+ reason:
+ "Webstudio does not convert external React registry files into editable Webstudio components yet.",
+ },
+ requirements: {
+ dependencies: item.dependencies ?? [],
+ devDependencies: item.devDependencies ?? [],
+ registryDependencies: item.registryDependencies ?? [],
+ },
+ sourceCode: {
+ status: "not-analyzed" as const,
+ reason:
+ "Inspecting registry metadata does not execute or analyze arbitrary external source files.",
+ },
+ manualSteps: [
+ "Use the item metadata as a reference to recreate the UI with Webstudio components and styles.",
+ ],
+});
+
+const serializeRegistryInspection = ({
+ source,
+ item,
+}: {
+ source: string;
+ item: RegistryItem;
+}) => ({
+ ...serializeRegistryItem({ source, item }),
+ compatibility: getCompatibilityReport(item),
+});
+
+export const inspectRegistry = async (
+ options: { source: string; item?: string },
+ dependencies: RegistryDependencies = defaultDependencies
+) => {
+ const sourceValue = await readRegistrySource({
+ source: options.source,
+ dependencies,
+ });
+ const directItem = registryItemSchema.safeParse(sourceValue);
+ const registry = registrySchema.safeParse(sourceValue);
+ if (
+ directItem.success &&
+ (registry.success === false || registry.data.items === undefined)
+ ) {
+ if (options.item !== undefined && options.item !== directItem.data.name) {
+ throw new Error(
+ `Registry source ${options.source} contains item ${directItem.data.name}, not ${options.item}.`
+ );
+ }
+ return serializeRegistryInspection({
+ source: options.source,
+ item: directItem.data,
+ });
+ }
+
+ if (registry.success === false || registry.data.items === undefined) {
+ throw new Error(
+ `Registry source ${options.source} is not an item. Pass --item <name> with a registry index.`
+ );
+ }
+ if (options.item === undefined) {
+ throw new Error(
+ `Registry source ${options.source} contains multiple items. Pass --item <name>.`
+ );
+ }
+ const indexedItem = registry.data.items.find(
+ (item) => item.name === options.item
+ );
+ if (indexedItem === undefined) {
+ throw new Error(
+ `Registry item ${options.item} was not found in ${options.source}.`
+ );
+ }
+ if (indexedItem.files !== undefined) {
+ return serializeRegistryInspection({
+ source: options.source,
+ item: indexedItem,
+ });
+ }
+ const itemSource = getItemSource({
+ source: options.source,
+ item: options.item,
+ });
+ return serializeRegistryInspection({
+ source: itemSource,
+ item: parseRegistryItem(
+ itemSource,
+ await readRegistrySource({ source: itemSource, dependencies })
+ ),
+ });
+};
+
+export const registryInspectOptions = (yargs: CommonYargsArgv) =>
+ yargs
+ .option("source", {
+ type: "string",
+ describe:
+ "Required local registry JSON path or remote registry/item URL. No files are installed; output includes a read-only compatibility report.",
+ demandOption: true,
+ })
+ .option("item", {
+ type: "string",
+ describe:
+ "Registry item name when --source is a registry index, for example button",
+ })
+ .option("json", {
+ type: "boolean",
+ describe: "Print machine-readable JSON output",
+ default: false,
+ })
+ .example(
+ "$0 registry inspect --source https://example.com/r/registry.json --item button --json",
+ "Inspect a remote shadcn registry item without installing it"
+ );
+
+type RegistryOptions = StrictYargsOptionsToInterface<
+ typeof registryInspectOptions
+>;
+
+export const registryInspect = async (options: RegistryOptions) => {
+ const data = await inspectRegistry({
+ source: options.source,
+ item: options.item,
+ });
+ if (options.json) {
+ printJson({ ok: true, data, meta: { command: "registry inspect" } });
+ return;
+ }
+ console.info(JSON.stringify(data, undefined, 2));
+};
diff --git a/packages/cli/src/commands/schema.test.ts b/packages/cli/src/commands/schema.test.ts
index 9cbfeb196d..4847966bd7 100644
--- a/packages/cli/src/commands/schema.test.ts
+++ b/packages/cli/src/commands/schema.test.ts
@@ -54,6 +54,16 @@ test("prints api command schema as json", () => {
name: "publish deploy",
operation: "publish",
method: "mutation",
+ inputSchema: expect.objectContaining({
+ type: "object",
+ properties: expect.objectContaining({
+ target: expect.objectContaining({
+ enum: expect.arrayContaining(["staging", "production"]),
+ }),
+ domains: expect.objectContaining({ type: "array" }),
+ message: expect.objectContaining({ type: "string" }),
+ }),
+ }),
}),
expect.objectContaining({
name: "domains list",
@@ -62,6 +72,11 @@ test("prints api command schema as json", () => {
}),
])
);
+ for (const command of output.commands) {
+ expect(command.inputSchema).toEqual(
+ expect.objectContaining({ type: "object" })
+ );
+ }
expect(output.commands).not.toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "apply-patch" }),
diff --git a/packages/cli/src/commands/schema.ts b/packages/cli/src/commands/schema.ts
index 6b4806cbbc..f9893344b9 100644
--- a/packages/cli/src/commands/schema.ts
+++ b/packages/cli/src/commands/schema.ts
@@ -73,6 +73,10 @@ const cliCommands = cliCommandMetadata.map((command) => ({
method: command.method,
permit: command.permit,
requiredOptions: command.requiredOptions ?? ["json"],
+ inputSchema: command.inputSchema,
+ ...(command.outputSchema === undefined
+ ? {}
+ : { outputSchema: command.outputSchema }),
examples: (command.examples ?? []).map(formatApiUseCaseCommand),
}));
@@ -100,6 +104,9 @@ const mcpToolSchema = listProjectSessionMcpTools(publicApiOperations, {
name: tool.name,
description: tool.description,
inputSchema: tool.inputSchema,
+ ...(tool.outputSchema === undefined
+ ? {}
+ : { outputSchema: tool.outputSchema }),
examples: tool.mcpExamples ?? [],
annotations: tool.annotations,
}));
@@ -258,7 +265,7 @@ const apiSchema = {
serverOnly:
"Server-only commands run remotely and invalidate/refetch namespaces declared by the public operation catalog.",
resultMetadata:
- "Successful command JSON includes meta.session with operationId, buildId, version, source, committed, compatibility, namespace metadata, and diagnostics.",
+ "Successful command JSON includes compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.",
},
useCases: topLevelUseCases,
patch: {
diff --git a/packages/cli/src/commands/screenshot.test.ts b/packages/cli/src/commands/screenshot.test.ts
index 6f0f97df05..b1d7f5e7b0 100644
--- a/packages/cli/src/commands/screenshot.test.ts
+++ b/packages/cli/src/commands/screenshot.test.ts
@@ -85,6 +85,130 @@ test("prints json result with a browser executable path", async () => {
});
});
+test("captures a project route through a temporary production preview", async () => {
+ const folder = await mkdtemp(join(tmpdir(), "webstudio-screenshot-test-"));
+ vi.spyOn(console, "info").mockImplementation(() => undefined);
+ const captureScreenshotWithBrowserInstall = vi.fn(async () => ({
+ output: join(folder, "pricing.png"),
+ browser: {
+ path: "/browser",
+ source: "option" as const,
+ browser: "chrome" as const,
+ },
+ viewport: { width: 800, height: 600 },
+ fullPage: false,
+ elapsedMs: 12,
+ warnings: [] as string[],
+ }));
+ const preview = {
+ startAndWait: vi.fn(async () => ({
+ url: "http://127.0.0.1:5180/",
+ running: true,
+ })),
+ stop: vi.fn(async () => ({
+ url: "http://127.0.0.1:5180/",
+ running: false,
+ })),
+ resolveUrl: vi.fn(() => "http://127.0.0.1:5180/pricing"),
+ };
+ const preparePreviewProject = vi.fn(async () => ({ cwd: "/tmp/preview" }));
+ const createPreviewController = vi.fn(() => preview);
+
+ try {
+ await screenshot(
+ {
+ path: "/pricing",
+ width: 800,
+ height: 600,
+ json: true,
+ },
+ {
+ captureScreenshotWithBrowserInstall,
+ preparePreviewProject,
+ createPreviewController,
+ }
+ );
+ } finally {
+ await rm(folder, { recursive: true, force: true });
+ }
+
+ expect(preparePreviewProject).toHaveBeenCalledWith({
+ assets: true,
+ template: ["defaults", "react-router"],
+ generate: true,
+ });
+ expect(createPreviewController).toHaveBeenCalledWith({
+ host: "127.0.0.1",
+ port: 5173,
+ });
+ expect(preview.startAndWait).toHaveBeenCalledWith({
+ cwd: "/tmp/preview",
+ host: "127.0.0.1",
+ port: 5173,
+ restart: true,
+ });
+ expect(preview.resolveUrl).toHaveBeenCalledWith("/pricing");
+ expect(captureScreenshotWithBrowserInstall).toHaveBeenCalledWith(
+ expect.objectContaining({ url: "http://127.0.0.1:5180/pricing" })
+ );
+ expect(preview.stop).toHaveBeenCalledOnce();
+});
+
+test("stops the temporary preview when project route capture fails", async () => {
+ const preview = {
+ startAndWait: vi.fn(async () => ({
+ url: "http://127.0.0.1:5173/",
+ running: true,
+ })),
+ stop: vi.fn(async () => ({
+ url: "http://127.0.0.1:5173/",
+ running: false,
+ })),
+ resolveUrl: vi.fn(() => "http://127.0.0.1:5173/"),
+ };
+
+ await expect(
+ screenshot(
+ { path: "/", width: 800, height: 600 },
+ {
+ captureScreenshotWithBrowserInstall: vi.fn(async () => {
+ throw new Error("capture failed");
+ }),
+ preparePreviewProject: vi.fn(async () => ({ cwd: "/tmp/preview" })),
+ createPreviewController: vi.fn(() => preview),
+ }
+ )
+ ).rejects.toThrow("capture failed");
+
+ expect(preview.stop).toHaveBeenCalledOnce();
+});
+
+test("stops the temporary preview when startup fails", async () => {
+ const preview = {
+ startAndWait: vi.fn(async () => {
+ throw new Error("preview failed");
+ }),
+ stop: vi.fn(async () => ({
+ url: "http://127.0.0.1:5173/",
+ running: false,
+ })),
+ resolveUrl: vi.fn(() => "http://127.0.0.1:5173/"),
+ };
+
+ await expect(
+ screenshot(
+ { path: "/", width: 800, height: 600 },
+ {
+ captureScreenshotWithBrowserInstall: vi.fn(),
+ preparePreviewProject: vi.fn(async () => ({ cwd: "/tmp/preview" })),
+ createPreviewController: vi.fn(() => preview),
+ }
+ )
+ ).rejects.toThrow("preview failed");
+
+ expect(preview.stop).toHaveBeenCalledOnce();
+});
+
test("rejects invalid screenshot readiness options", async () => {
const captureScreenshotWithBrowserInstall = vi.fn();
diff --git a/packages/cli/src/commands/screenshot.ts b/packages/cli/src/commands/screenshot.ts
index 64e7515f7a..d9aaa93718 100644
--- a/packages/cli/src/commands/screenshot.ts
+++ b/packages/cli/src/commands/screenshot.ts
@@ -19,6 +19,12 @@ import {
chromiumDownloadUrl,
getNoBrowserFoundMessage,
} from "../screenshot";
+import {
+ preparePreviewProject,
+ previewDefaultTemplate,
+ validatePreviewServerOptions,
+} from "./preview";
+import { createPreviewController } from "../preview-server";
import type {
CommonYargsArgv,
StrictYargsOptionsToInterface,
@@ -28,7 +34,22 @@ export const screenshotOptions = (yargs: CommonYargsArgv) =>
yargs
.positional("url", {
type: "string",
- describe: "URL to capture",
+ describe: "Absolute URL to capture",
+ })
+ .option("path", {
+ type: "string",
+ describe:
+ "Project route to capture by generating a local production preview, for example /pricing",
+ })
+ .option("host", {
+ type: "string",
+ default: "127.0.0.1",
+ describe: "Host used by the temporary project preview server",
+ })
+ .option("port", {
+ type: "number",
+ default: 5173,
+ describe: "Port used by the temporary project preview server",
})
.option("output", {
type: "string",
@@ -96,6 +117,7 @@ type ScreenshotOptions = StrictYargsOptionsToInterface<
typeof screenshotOptions
> & {
url?: string;
+ path?: string;
browser?: ScreenshotBrowser;
waitUntil?: ScreenshotWaitUntil;
waitForSelector?: string;
@@ -137,10 +159,19 @@ const printScreenshotError = ({
type ScreenshotCommandDependencies = {
captureScreenshotWithBrowserInstall: typeof captureScreenshotWithBrowserInstall;
+ preparePreviewProject?: typeof preparePreviewProject;
+ createPreviewController?: (
+ defaults: Parameters<typeof createPreviewController>[0]
+ ) => Pick<
+ ReturnType<typeof createPreviewController>,
+ "startAndWait" | "stop" | "resolveUrl"
+ >;
};
const defaultScreenshotCommandDependencies: ScreenshotCommandDependencies = {
captureScreenshotWithBrowserInstall,
+ preparePreviewProject,
+ createPreviewController,
};
export const screenshot = async (
@@ -148,8 +179,20 @@ export const screenshot = async (
dependencies = defaultScreenshotCommandDependencies
) => {
const options = rawOptions as ScreenshotOptions;
- if (options.url === undefined || options.url.length === 0) {
- throw new Error("Please specify a URL to capture.");
+ if (
+ (options.url === undefined || options.url.length === 0) &&
+ (options.path === undefined || options.path.length === 0)
+ ) {
+ throw new Error("Please specify a URL or project --path to capture.");
+ }
+ if (options.url !== undefined && options.path !== undefined) {
+ throw new Error("Specify either a URL or --path, not both.");
+ }
+ if (
+ options.path !== undefined &&
+ (options.path.startsWith("/") === false || options.path.startsWith("//"))
+ ) {
+ throw new Error("--path must start with one slash, for example /pricing.");
}
if (isPositiveInteger(options.width) === false) {
throw new Error("--width must be a positive integer.");
@@ -183,52 +226,85 @@ export const screenshot = async (
}
try {
- const result = await dependencies.captureScreenshotWithBrowserInstall({
- url: options.url,
- output: options.output,
- width: options.width,
- height: options.height,
- fullPage: options.fullPage,
- browser: options.browser ?? "auto",
- browserPath: options.browserPath,
- waitUntil: options.waitUntil ?? defaultScreenshotWaitUntil,
- waitForSelector: options.waitForSelector,
- waitForTimeout: options.waitForTimeout ?? defaultScreenshotWaitForTimeout,
- timeout: options.timeout ?? defaultScreenshotTimeout,
- isJson: options.json,
- isMcp: false,
- isInteractive:
- process.stdin.isTTY === true && process.stdout.isTTY === true,
- async confirmInstall(installCommand) {
- const answer = await confirm({
- message: `No supported browser was found. Install Chromium now with "${installCommand.label}"?`,
- initialValue: true,
- });
- if (isCancel(answer)) {
- cancel("Screenshot capture is cancelled.");
- throw new HandledCliError();
- }
- return answer;
- },
- });
-
- if (options.json) {
- printJson({
- ok: true,
- data: {
- output: result.output,
- browserPath: result.browser.path,
- browser: result.browser.browser,
- viewport: result.viewport,
- fullPage: result.fullPage,
- elapsedMs: result.elapsedMs,
- warnings: result.warnings,
+ const capture = async (url: string) => {
+ const result = await dependencies.captureScreenshotWithBrowserInstall({
+ url,
+ output: options.output,
+ width: options.width,
+ height: options.height,
+ fullPage: options.fullPage,
+ browser: options.browser ?? "auto",
+ browserPath: options.browserPath,
+ waitUntil: options.waitUntil ?? defaultScreenshotWaitUntil,
+ waitForSelector: options.waitForSelector,
+ waitForTimeout:
+ options.waitForTimeout ?? defaultScreenshotWaitForTimeout,
+ timeout: options.timeout ?? defaultScreenshotTimeout,
+ isJson: options.json,
+ isMcp: false,
+ isInteractive:
+ process.stdin.isTTY === true && process.stdout.isTTY === true,
+ async confirmInstall(installCommand) {
+ const answer = await confirm({
+ message: `No supported browser was found. Install Chromium now with "${installCommand.label}"?`,
+ initialValue: true,
+ });
+ if (isCancel(answer)) {
+ cancel("Screenshot capture is cancelled.");
+ throw new HandledCliError();
+ }
+ return answer;
},
- meta: { command: "screenshot" },
});
+
+ if (options.json) {
+ printJson({
+ ok: true,
+ data: {
+ output: result.output,
+ browserPath: result.browser.path,
+ browser: result.browser.browser,
+ viewport: result.viewport,
+ fullPage: result.fullPage,
+ elapsedMs: result.elapsedMs,
+ warnings: result.warnings,
+ },
+ meta: { command: "screenshot" },
+ });
+ return;
+ }
+ log.success(`Screenshot saved to ${result.output}`);
+ };
+
+ if (options.path === undefined) {
+ await capture(options.url!);
return;
}
- log.success(`Screenshot saved to ${result.output}`);
+
+ const host = options.host ?? "127.0.0.1";
+ const port = options.port ?? 5173;
+ validatePreviewServerOptions({ host, port });
+ const previewProject = await (
+ dependencies.preparePreviewProject ?? preparePreviewProject
+ )({
+ assets: true,
+ template: [...previewDefaultTemplate],
+ generate: true,
+ });
+ const preview = (
+ dependencies.createPreviewController ?? createPreviewController
+ )({ host, port });
+ try {
+ await preview.startAndWait({
+ cwd: previewProject.cwd,
+ host,
+ port,
+ restart: true,
+ });
+ await capture(preview.resolveUrl(options.path));
+ } finally {
+ await preview.stop();
+ }
} catch (error) {
if (error instanceof BrowserNotFoundError) {
printScreenshotError({
diff --git a/packages/cli/src/commands/sync.test.ts b/packages/cli/src/commands/sync.test.ts
index 6a7c52b68f..b735a40769 100644
--- a/packages/cli/src/commands/sync.test.ts
+++ b/packages/cli/src/commands/sync.test.ts
@@ -11,6 +11,7 @@ import { createFileIfNotExists, isFileExists } from "../fs-utils";
import { resolveApiConnection } from "../api-connection";
import { sync } from "./sync";
import { apiCompatibilityHeaders } from "./api";
+import { materializeManagedAgents } from "../managed-agents";
const originalCwd = process.cwd();
let tempDir: string;
@@ -32,6 +33,7 @@ const dependencies = {
resolveApiConnection,
spinner: () => indicator,
writeFile,
+ materializeManagedAgents,
};
type ProjectBundleFixtureOptions = Parameters<
@@ -80,7 +82,64 @@ test("writes current data version after synchronizing from the API", async () =>
bundleVersion,
});
expect(indicator.stop).toHaveBeenCalledWith(
- "Project bundle synchronized successfully"
+ "Project bundle synchronized successfully (AGENTS.md: unchanged)"
+ );
+});
+
+test("materializes project agent instructions during sync", async () => {
+ loadProjectBundleByBuildId.mockResolvedValue(
+ createProjectBundle({
+ build: {
+ projectSettings: {
+ meta: { agentInstructions: "Use existing design tokens." },
+ compiler: {},
+ },
+ },
+ })
+ );
+
+ await sync(
+ {
+ authToken: "token-1",
+ buildId: "build-1",
+ origin: "https://example.com",
+ },
+ dependencies
+ );
+
+ expect(await readFile("AGENTS.md", "utf8")).toContain(
+ "Use existing design tokens."
+ );
+ expect(indicator.stop).toHaveBeenCalledWith(
+ "Project bundle synchronized successfully (AGENTS.md: created)"
+ );
+});
+
+test("reports a user-owned AGENTS.md conflict without overwriting it", async () => {
+ await writeFile("AGENTS.md", "# User-owned\n", "utf8");
+ loadProjectBundleByBuildId.mockResolvedValue(
+ createProjectBundle({
+ build: {
+ projectSettings: {
+ meta: { agentInstructions: "Use existing design tokens." },
+ compiler: {},
+ },
+ },
+ })
+ );
+
+ await sync(
+ {
+ authToken: "token-1",
+ buildId: "build-1",
+ origin: "https://example.com",
+ },
+ dependencies
+ );
+
+ expect(await readFile("AGENTS.md", "utf8")).toBe("# User-owned\n");
+ expect(indicator.stop).toHaveBeenCalledWith(
+ expect.stringContaining("AGENTS.md blocked by user-owned file")
);
});
diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.ts
index 4f6da80c55..3a2df8ec01 100644
--- a/packages/cli/src/commands/sync.ts
+++ b/packages/cli/src/commands/sync.ts
@@ -19,6 +19,7 @@ import { HandledCliError } from "../errors";
import { apiCompatibilityHeaders, stopSpinnerWithError } from "./api";
import { downloadAssetFiles } from "../asset-files";
import { resolveApiConnection } from "../api-connection";
+import { materializeManagedAgents } from "../managed-agents";
export type SyncDependencies = {
createFileIfNotExists: typeof createFileIfNotExists;
@@ -30,6 +31,7 @@ export type SyncDependencies = {
resolveApiConnection: typeof resolveApiConnection;
spinner: typeof spinner;
writeFile: typeof writeFile;
+ materializeManagedAgents: typeof materializeManagedAgents;
};
export const defaultSyncDependencies: SyncDependencies = {
@@ -42,6 +44,7 @@ export const defaultSyncDependencies: SyncDependencies = {
resolveApiConnection,
spinner,
writeFile,
+ materializeManagedAgents,
};
export const syncOptions = (yargs: CommonYargsArgv) =>
@@ -189,5 +192,16 @@ export const sync = async (
"utf8"
);
- syncing.stop("Project bundle synchronized successfully");
+ const agents = await dependencies.materializeManagedAgents({
+ rootDir: cwd(),
+ instructions:
+ project.build.projectSettings?.meta.agentInstructions ??
+ project.build.pages.meta?.agentInstructions,
+ });
+
+ syncing.stop(
+ agents.status === "blocked-by-user-file"
+ ? `Project bundle synchronized; AGENTS.md blocked by user-owned file at ${agents.path}`
+ : `Project bundle synchronized successfully (AGENTS.md: ${agents.status})`
+ );
};
diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.ts
index d4c14c9a47..22540c969c 100644
--- a/packages/cli/src/docs.generated.ts
+++ b/packages/cli/src/docs.generated.ts
@@ -2,17 +2,17 @@
// Edit markdown files in src/docs instead.
export const cliDocs = {
"api-use-cases":
- '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n\nNotes:\n\n- Use `webstudio schema mcp` for a tiny machine-readable MCP tool overview. Use `webstudio schema mcp --detail summary` for all tool descriptions, and `webstudio schema mcp --detail full` or focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Use `resources/list` and `resources/read` for overview resources and read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused discovery is insufficient.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## 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- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Upload, replace, delete, and inspect asset usage.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: 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 refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations and after generated project files are current so a vision-capable AI can see the production-like generated site.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- After MCP mutations, path screenshots regenerate/restart preview as needed before capture; when preview is fresh, repeated path screenshots reuse the running server.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- Preview isolates generated app dependencies under `.webstudio/preview` by linking to the CLI package dependency tree.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If preview fails with a missing generated-app command/package such as react-router, react-router-serve, or vite, install dependencies for the CLI package and retry.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches.\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 preview, then webstudio screenshot <url> --output current.png.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"\\"Pricing\\"","meta":{"description":"\\"Plans for teams\\""}}\n\nNotes:\n\n- `name` and `path` are plain values.\n- Page `title` and metadata text fields store JavaScript expression source. For fixed text, send a string literal expression such as `"\\"Pricing\\""`. For computed values, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\"","status":"200"}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields store JavaScript expression source. For fixed text, send a string literal expression such as `"\\"Pricing\\""`. For computed values, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"\\"Landing\\""}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"\\"Reusable article layout\\""}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {"includePages":true}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown component ids fall back to a single-element instance when no template exists.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\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- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {"withUsage":true}\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","force":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts\\"","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts?tag=\\" + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"\\"https://api.example.com/posts\\"","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"page","value":"String(filters.page ?? 1)"}],"headers":[{"name":"Authorization","value":"\\"Bearer \\" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"\\"https://api.example.com/graphql\\"","headers":[{"name":"Content-Type","value":"\\"application/json\\""}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"\\"/$resources/current-date\\"","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url`, header values, search parameter values, and body are expressions. Literal URLs are JSON strings such as `"https://api.example.com/posts"`.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"\\"https://api.example.com/posts\\""}}\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use this for finding elements by label, type, href/resource patterns, HTML snippets, missing accessibility metadata, or asset usage.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\""}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"\\"https://api.example.com/posts\\""}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\""}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts\\"","searchParams":[{"name":"tag","value":"filters.tag"}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"\\"https://api.example.com/graphql\\"","headers":[{"name":"Content-Type","value":"\\"application/json\\""}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"\\"/$resources/current-date\\"","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"\\"https://api.example.com/posts\\""}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"\\"https://api.example.com/seats\\"","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use existing scripts/resources for behavior, then move presentational structure into editable Webstudio instances where possible.\n- There is no dedicated semantic command yet for converting script-generated UI into editable Webstudio structure.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"\\"https://api.example.com/session\\"","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still requires manual resources, props, embeds, or patches.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after external design interpretation. There is no dedicated import command for Figma, screenshots, Inception output, or design.md yet.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n- webstudio permissions --json\n- webstudio mcp\n\nNotes:\n\n- Public API and CLI intentionally operate on one configured project at a time. Use an external script to loop over projects.\n\n# Known CLI Gaps\n\n## General project search and audit\n\nMissing:\nNo single semantic command searches across instance labels, props, hrefs, resource URLs, HTML embeds, asset references, and missing accessibility metadata.\n\nCurrent fallback:\nUse focused MCP reads such as list-instances, list-texts, list-assets, find-asset-usage, and snapshot.\n\nSuggested commands:\n\n- search-project\n- audit-accessibility\n- find-prop-usage\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCreate the page, resources, variables, props, and embeds manually with existing MCP semantic tools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Dynamic script/runtime integration helpers\n\nMissing:\nCLI can manipulate props/resources/embeds, but has no semantic workflow for converting script-generated UI into editable Webstudio structures.\n\nCurrent fallback:\nUse MCP props, resources, and raw patch where necessary.\n\nSuggested commands:\n\n- integrate-runtime-ui\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nUse external generation, then apply semantic CLI commands or apply-patch.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',
+ '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n\nNotes:\n\n- Use `webstudio schema mcp` for a tiny machine-readable MCP tool overview. Use `webstudio schema mcp --detail summary` for all tool descriptions, and `webstudio schema mcp --detail full` or focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Use `resources/list` and `resources/read` for overview resources and read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused discovery is insufficient.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Upload, replace, delete, and inspect asset usage.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations and after generated project files are current so a vision-capable AI can see the production-like generated site.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- After MCP mutations, path screenshots regenerate/restart preview as needed before capture; when preview is fresh, repeated path screenshots reuse the running server.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- Preview isolates generated app dependencies under `.webstudio/preview` by linking to the CLI package dependency tree.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If preview fails with a missing generated-app command/package such as react-router, react-router-serve, or vite, install dependencies for the CLI package and retry.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":"200"}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {"includePages":true}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown component ids fall back to a single-element instance when no template exists.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- Store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"includeStyles":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `includeStyles:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","force":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts?tag=\\" + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\\"Bearer \\" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n\nNotes:\n\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility,seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use existing scripts/resources for behavior, then move presentational structure into editable Webstudio instances where possible.\n- There is no dedicated semantic command yet for converting script-generated UI into editable Webstudio structure.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still requires manual resources, props, embeds, or patches.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after external design interpretation. There is no dedicated import command for Figma, screenshots, Inception output, or design.md yet.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n- webstudio permissions --json\n- webstudio mcp\n\nNotes:\n\n- Public API and CLI intentionally operate on one configured project at a time. Use an external script to loop over projects.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCreate the page, resources, variables, props, and embeds manually with existing MCP semantic tools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Dynamic script/runtime integration helpers\n\nMissing:\nCLI can manipulate props/resources/embeds, but has no semantic workflow for converting script-generated UI into editable Webstudio structures.\n\nCurrent fallback:\nUse MCP props, resources, and raw patch where necessary.\n\nSuggested commands:\n\n- integrate-runtime-ui\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nUse external generation, then apply semantic CLI commands or apply-patch.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',
"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 meta.session with operationId, buildId, version, source, committed, compatibility, namespace freshness, and diagnostics.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "pages",\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: site metadata, redirects, page records, folders, compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand MCP tools expose it through two user-facing groups:\n\n- data variables: `list-variables`, `create-variable`, `update-variable`, and\n `delete-variable`\n- data resources: `list-resources`, `create-resource`, `update-resource`, and\n `delete-resource`\n\nFor raw `snapshot`, request the public `variables` namespace rather than the\ninternal `dataSources` name. Raw patch payloads still use `dataSources` when\napplying direct changes.\n\nVariables can be scoped to an instance. Expressions under that instance can use\nthe variable by name; nested variables with the same name mask outer variables.\nVariable values support `string`, `number`, `boolean`, `string[]`, and `json`.\nUse `string[]` for lists of strings such as tags or selected categories; use\n`json` for objects, arrays with mixed shapes, or nested API filter state.\nParameters are internal scoped runtime values provided by pages, collections,\nor components. They are not a public authoring surface: do not create, update,\nor delete parameter records. Public tools should preserve existing parameter\nrecords and may reference documented context values such as `system` in\nexpressions where they are already in scope.\n\nResource request fields are expressions too. Literal URLs must be JSON strings,\nfor example `"https://api.example.com/posts"`. Dynamic URLs can combine strings\nand variables, for example `"https://api.example.com/posts?tag=" + filters.tag`.\nPrefer `searchParams` for query parameters that should be encoded separately:\n`[{ "name": "tag", "value": "filters.tag" }]`. Header values and body are also\nexpressions, so headers can read variables such as `"Bearer " + auth.token`, and\nGraphQL bodies can return objects such as\n`{ query: "...", variables: { slug: system.params.slug } }`.\n\nCreate a resource with `scopeInstanceId`/`--scope-instance` when the fetched\nresource result should be available as a read data variable. Scoped resources\nare generated into the page resource `data` map and may be loaded during page\nrendering. Use this shape for read-oriented resources such as GET CMS/API data.\nUse `dataSourceName` or `--data-source-name` to choose the variable name.\n\nFor submit/write/action resources, create the resource without\n`scopeInstanceId`, then bind a component prop such as a Form `action` to the\nresource with `bind-props` and `binding.type: "resource"`. Prop-bound resources\nare generated into the page resource `action` map instead of the read `data`\nmap. Use this shape for POST, PUT, DELETE, webhook, and other resources that\nshould run only from an explicit form/action flow, not merely because the page\nrendered.\n\nResource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read\ndata. Use POST for creates, GraphQL requests, webhooks, and form submissions.\nUse PUT for full updates/replacements. Use DELETE for deletion actions.\nOptional `control` values are `graphql` and `system`: `graphql` marks a\nGraphQL-style resource, usually POST with a query body; `system` marks a\nresource intended to use the built-in `system` parameter or one of the built-in\nlocal resource URLs: `"/$resources/sitemap.xml"`,\n`"/$resources/current-date"`, and `"/$resources/assets"`. The system parameter\nfields are `system.origin`, `system.pathname`, `system.params`, and\n`system.search`.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "patch-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "patch-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',
+ '# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand MCP tools expose it through two user-facing groups:\n\n- data variables: `list-variables`, `create-variable`, `update-variable`, and\n `delete-variable`\n- data resources: `list-resources`, `create-resource`, `update-resource`, and\n `delete-resource`\n\nFor raw `snapshot`, request the public `variables` namespace rather than the\ninternal `dataSources` name. Raw patch payloads still use `dataSources` when\napplying direct changes.\n\nVariables can be scoped to an instance. Expressions under that instance can use\nthe variable by name; nested variables with the same name mask outer variables.\nVariable values support `string`, `number`, `boolean`, `string[]`, and `json`.\nUse `string[]` for lists of strings such as tags or selected categories; use\n`json` for objects, arrays with mixed shapes, or nested API filter state.\nParameters are internal scoped runtime values provided by pages, collections,\nor components. They are not a public authoring surface: do not create, update,\nor delete parameter records. Public tools should preserve existing parameter\nrecords and may reference documented context values such as `system` in\nexpressions where they are already in scope.\n\nResource `url` accepts plain fixed URLs and paths, for example\n`https://api.example.com/posts` or `/$resources/current-date`. Dynamic URLs can\ncombine strings and variables, for example\n`"https://api.example.com/posts?tag=" + filters.tag`. Prefer `searchParams` for\nquery parameters that should be encoded separately:\n`[{ "name": "tag", "value": "filters.tag" }]`. Header values, search parameter\nvalues, and bodies are expressions for dynamic content. For fixed text, use\n`{ "type": "literal", "value": "application/json" }`; Webstudio stores the\nrequired string expression. Headers can still read variables such as\n`"Bearer " + auth.token`, and GraphQL bodies can return objects such as\n`{ query: "...", variables: { slug: system.params.slug } }`.\n\nCreate a resource with `scopeInstanceId`/`--scope-instance` when the fetched\nresource result should be available as a read data variable. Scoped resources\nare generated into the page resource `data` map and may be loaded during page\nrendering. Use this shape for read-oriented resources such as GET CMS/API data.\nUse `dataSourceName` or `--data-source-name` to choose the variable name.\n\nFor submit/write/action resources, create the resource without\n`scopeInstanceId`, then bind a component prop such as a Form `action` to the\nresource with `bind-props` and `binding.type: "resource"`. Prop-bound resources\nare generated into the page resource `action` map instead of the read `data`\nmap. Use this shape for POST, PUT, DELETE, webhook, and other resources that\nshould run only from an explicit form/action flow, not merely because the page\nrendered.\n\nResource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read\ndata. Use POST for creates, GraphQL requests, webhooks, and form submissions.\nUse PUT for full updates/replacements. Use DELETE for deletion actions.\nOptional `control` values are `graphql` and `system`: `graphql` marks a\nGraphQL-style resource, usually POST with a query body; `system` marks a\nresource intended to use the built-in `system` parameter or one of the built-in\nlocal resource URLs: `"/$resources/sitemap.xml"`,\n`"/$resources/current-date"`, and `"/$resources/assets"`. The system parameter\nfields are `system.origin`, `system.pathname`, `system.params`, and\n`system.search`.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "patch-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "patch-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',
"manual-llm":
- '# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a tiny MCP tool overview. Use `webstudio schema mcp --detail summary` for all tool descriptions, and `webstudio schema mcp --detail full` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get_more_tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe same local shortcut form is shorter and preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor this simple path, do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in the block\'s `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <ws.element\n ws:tag="section"\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. Inspect current project state with semantic reads such as `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.\n5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n4. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\n- Use direct value tools for fixed content. For visible text, use `update-text` with plain `text`. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, `status`, and custom meta content store JavaScript expression source. For fixed text, pass a JavaScript string literal expression with JSON quoting, for example `JSON.stringify("Pricing | Acme")` in code or `"\\"Pricing | Acme\\""` in JSON. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"\\"Pricing | Acme\\"","meta":{"description":"\\"Plans for teams\\""}}}`.\n- Resource URL, header, search-param, and body fields also store JavaScript expression source. For a fixed URL, use a string literal expression such as `"\\"https://api.example.com/items\\""`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"\\"https://api.example.com/items\\""}}`.\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`. Use `string[]` only for arrays where every item is a string; use `json` for objects, mixed arrays, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A resource created with `scopeInstanceId`/`dataSourceName` becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Use this for GET CMS/API data and read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Header values can be expressions such as `"\\"Bearer \\" + auth.token"`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- For visual/design work, verify the rendered result with vision before finishing.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- For expression-backed fields that need fixed text, encode the fixed text as a quoted JavaScript string literal expression.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',
+ '# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a tiny MCP tool overview. Use `webstudio schema mcp --detail summary` for all tool descriptions, and `webstudio schema mcp --detail full` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get_more_tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe same local shortcut form is shorter and preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor this simple path, do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in the block\'s `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <ws.element\n ws:tag="section"\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. Inspect current project state with semantic reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.\n5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n4. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, `status`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`. Use `string[]` only for arrays where every item is a string; use `json` for objects, mixed arrays, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A resource created with `scopeInstanceId`/`dataSourceName` becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Use this for GET CMS/API data and read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can be expressions such as `"\\"Bearer \\" + auth.token"`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- For visual/design work, verify the rendered result with vision before finishing.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',
"manual-mcp":
- '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. For shell-driven agents, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. For MCP clients, start the server with `webstudio mcp`.\n5. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Prefer JSX for authored/styled content. Common `insert-fragment` inputs:\n\n```jsonl\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag="h2">Northstar Product OS</ws.element><ws.element ws:tag="p">Reusable patterns for teams.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" style={{ padding: 32, borderRadius: 16 }}><ws.element ws:tag="h2">Operations Console</ws.element><ws.element ws:tag="p">React-style object styles become editable Webstudio styles.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:tokens={[token(\\"accent\\", css`color: #0f766e;`)]}><ws.element ws:tag="button" onClick={new ActionValue([\\"event\\"], expression`console.log(event)`)}>Track launch</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\"><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n```\n\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, `mcp run` stops immediately before later calls and prints partial results with `CHECKPOINT_REQUIRED`. Stop now and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: shadcn-compatible registry items for visible components and templates\n- `components.summary`: compact structured component catalog with insertability and template hints\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: shadcn-compatible registry items for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, string list, and JSON variables.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List, upload, add, update, find usage for, replace, and delete assets.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale.\n- A mutation is durable only when `meta.session.committed` is true.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects:\n\n{{mcpArgumentExampleIndex}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',
+ '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. For shell-driven agents, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. For MCP clients, start the server with `webstudio mcp`.\n5. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Prefer JSX for authored/styled content. Common `insert-fragment` inputs:\n\n```jsonl\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag="h2">Northstar Product OS</ws.element><ws.element ws:tag="p">Reusable patterns for teams.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" style={{ padding: 32, borderRadius: 16 }}><ws.element ws:tag="h2">Operations Console</ws.element><ws.element ws:tag="p">React-style object styles become editable Webstudio styles.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:tokens={[token(\\"accent\\", css`color: #0f766e;`)]}><ws.element ws:tag="button" onClick={new ActionValue([\\"event\\"], expression`console.log(event)`)}>Track launch</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\"><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n```\n\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, `mcp run` stops immediately before later calls and prints partial results with `CHECKPOINT_REQUIRED`. Stop now and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: shadcn-compatible registry items for visible components and templates\n- `components.summary`: compact structured component catalog with insertability and template hints\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: shadcn-compatible registry items for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, string list, and JSON variables.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List, upload, add, update, find usage for, replace, and delete assets.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- A mutation is durable only when `meta.session.committed` is true.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects:\n\n{{mcpArgumentExampleIndex}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',
"mcp-startup-epilogue":
- 'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in the block\'s `ws:block-template` child. Templates themselves are protected; an editor\'s inserted copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get_more_tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, later one-shot calls fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nIf a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in the Webstudio Discord `#help` channel at https://wstd.us/community. Give the user a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n\nIf you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.\n',
+ 'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in the block\'s `ws:block-template` child. Templates themselves are protected; an editor\'s inserted copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get_more_tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, later one-shot calls fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nIf a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in the Webstudio Discord `#help` channel at https://wstd.us/community. Give the user a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n\nIf you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.\n',
"mcp-vision":
- '# MCP Vision Verification\n\n## Generated App Dependency Notes\n\n- `preview.start` and `webstudio preview` isolate generated app dependencies under `.webstudio/preview` by linking to the CLI package dependency tree.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If preview fails with a missing generated-app command/package such as react-router, react-router-serve, or vite, install dependencies for the CLI package and retry.\n\n## Visual Verification Rule\n\nFor visual/design work, use preview.start and screenshot after generated project files are current so vision can inspect the rendered result before finishing. `preview.start` is long-lived and cannot be used through one-shot `mcp single-op-call`; from a shell, use `webstudio mcp run` for preview.start/screenshot/preview.stop in one shared process, or use a long-running MCP server. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.\n\n## Vision Verification Loop\n\n- Make focused page/content/style changes with semantic MCP tools.\n- Make sure generated project files are current, then call preview.start to build the app and keep the production-like generated site running. In shell-driven workflows, run preview.start, screenshot, and preview.stop inside one `webstudio mcp run` call so they share the same preview owner.\n- {{dependency-notes}}\n- After MCP mutations, path-based screenshots regenerate/restart preview as needed before capture; when preview is fresh in the same long-running MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview without starting or restarting it. Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview; a separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.\n- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.\n- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baseUrl: "http://127.0.0.1:5177", path: "/" }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair.\n- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.\n- Inspect every viewport PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.\n- If the screenshot does not match, apply another focused mutation and repeat screenshot verification.\n\n## Workflow Summary With Diff\n\nFor visual/design work, make sure generated project files are current, call preview.start to build and start the production-like preview server, then screenshot({ path, viewport }) for every changed page path; for responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths; use screenshot.diff on each baseline/current page or viewport pair when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing.\n\n## Workflow Summary Without Diff\n\nFor visual/design work, make sure generated project files are current, call preview.start to build and start the production-like preview server, then screenshot({ path, viewport }) for every changed page path; for responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths; inspect every PNG with vision before finishing.\n\n## Screenshot Verification Summary\n\nInside a long-running MCP server, prefer preview.start plus screenshot({ path, viewport }) after generated project files are current, so a fresh production-like preview server is available for fast repeated checks across multiple pages. After MCP mutations, path screenshots restart preview as needed before capture; when preview is fresh in that same MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture viewport widths from Builder breakpoint edges plus mobile and desktop widths before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use webstudio preview and webstudio screenshot <url> --output current.png.\n\n## Screenshot Diff Evidence\n\n- Pixel evidence: total mismatch, changed regions, dominant color/luminance direction, diffPath, and contextDiffPath.\n- OCR evidence: textAnalysis.status, provider, and changes for appeared/disappeared/content_changed/moved/font_changed text.\n- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.\n- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.\n- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.\n',
+ '# MCP Vision Verification\n\n## Generated App Dependency Notes\n\n- `preview.start` and `webstudio preview` isolate generated app dependencies under `.webstudio/preview` by linking to the CLI package dependency tree.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If preview fails with a missing generated-app command/package such as react-router, react-router-serve, or vite, install dependencies for the CLI package and retry.\n\n## Visual Verification Rule\n\nFor visual/design work, use preview.start and screenshot after generated project files are current so vision can inspect the rendered result before finishing. `preview.start` is long-lived and cannot be used through one-shot `mcp single-op-call`; from a shell, use `webstudio mcp run` for preview.start/screenshot/preview.stop in one shared process, or use a long-running MCP server. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.\n\n## Vision Verification Loop\n\n- Make focused page/content/style changes with semantic MCP tools.\n- Make sure generated project files are current, then call preview.start to build the app and keep the production-like generated site running. In shell-driven workflows, run preview.start, screenshot, and preview.stop inside one `webstudio mcp run` call so they share the same preview owner.\n- {{dependency-notes}}\n- After MCP mutations, path-based screenshots regenerate/restart preview as needed before capture; when preview is fresh in the same long-running MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview without starting or restarting it. Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview; a separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.\n- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.\n- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baseUrl: "http://127.0.0.1:5177", path: "/" }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair. Add expectedText when a specific visible phrase must be present; its assertions report pass/fail plus found and missing text. Add expectedVisual to set pass/fail limits for mismatch percentage, the number of changed regions, or an overall dominant color/brightness direction.\n- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, expectedText assertions fail and textAnalysis reports why; ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.\n- Inspect every viewport PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.\n- If the screenshot does not match, apply another focused mutation and repeat screenshot verification.\n\n## Workflow Summary With Diff\n\nFor visual/design work, make sure generated project files are current, call preview.start to build and start the production-like preview server, then screenshot({ path, viewport }) for every changed page path; for responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths; use screenshot.diff on each baseline/current page or viewport pair when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing.\n\n## Workflow Summary Without Diff\n\nFor visual/design work, make sure generated project files are current, call preview.start to build and start the production-like preview server, then screenshot({ path, viewport }) for every changed page path; for responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths; inspect every PNG with vision before finishing.\n\nEach screenshot result includes rendered `layout` metrics when the local browser\nprovides them. `layout.horizontalOverflow: true` is deterministic evidence that\nthe rendered document exceeds the requested viewport width. Use vision for\nclipping, wrapping, hierarchy, and other judgments that layout dimensions alone\ncannot establish.\n\nPass `includeImageMetrics: true` when an ordinary screenshot needs\n`layout.images`; rendered audit enables it automatically. The array includes\neach rendered image\'s Webstudio instance id when available, loading mode,\ncompletion state, natural dimensions, rendered dimensions, and document\nposition. Rendered audits use this evidence to report broken images, eager\nloading below the fold, and sources more than 2x the rendered dimensions in\nboth axes. Oversized-source results are optimization evidence, not universal\nperformance conformance.\n\nPass `includeResourceMetrics: true` when an ordinary screenshot needs sanitized\nResource Timing evidence; rendered audit enables it automatically. Resource\nmetrics contain only the URL pathname, initiator type, transfer/body sizes,\nduration, and browser-provided render-blocking status. Origins and query strings\nare omitted. Rendered audits report explicitly blocking resources and legacy\n`.ttf`, `.otf`, or `.woff` font files without applying a universal byte-size\nbudget.\n\n## Screenshot Verification Summary\n\nInside a long-running MCP server, prefer preview.start plus screenshot({ path, viewport }) after generated project files are current, so a fresh production-like preview server is available for fast repeated checks across multiple pages. After MCP mutations, path screenshots restart preview as needed before capture; when preview is fresh in that same MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture viewport widths from Builder breakpoint edges plus mobile and desktop widths before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use `webstudio screenshot --path /pricing --output pricing.png` for one temporary generated preview capture, or keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot` for repeated captures.\n\n## Screenshot Diff Evidence\n\n- Pixel evidence: total mismatch, changed regions, dominant color/luminance direction, diffPath, and contextDiffPath.\n- OCR evidence: textAnalysis.status, provider, and changes for appeared/disappeared/content_changed/moved/font_changed text. expectedText adds pass/fail assertions plus found and missing current-screen text. expectedVisual adds pass/fail quantitative checks for mismatch percentage, changed-region count, and the overall dominant color/brightness direction.\n- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.\n- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.\n- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.\n',
} as const;
export const cliDocTitles = {
@@ -43,7 +43,7 @@ export const cliDocSections = {
"manual-llm": {
implementationProcess: [
'Discover capabilities with webstudio man --json, webstudio schema api, webstudio schema mcp, MCP meta.index, meta.guide, meta.get_more_tools, components.list, components.summary, components.coverage-plan, components.search, components.get, templates.list, and templates.get. From a shell, prefer shortcut calls such as webstudio meta.index and webstudio components.search \'{"brief":"button"}\' for these focused tool calls; use webstudio mcp single-op-call when you need the explicit MCP form. Read full resources such as webstudio://project/tools and webstudio://project/components only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.',
- "Inspect current project state with semantic reads such as list-pages, get-page-by-path, list-instances, inspect-instance, get-styles, list-assets, list-breakpoints, and snapshot only when needed.",
+ "Inspect current project state with semantic reads such as get-project-settings, list-pages, get-page-by-path, list-instances, inspect-instance, get-styles, list-assets, list-breakpoints, and snapshot only when needed. Before changing a project, read get-project-settings and follow any non-empty meta.agentInstructions. These are shared project instructions, not a place for secrets.",
"Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP insert-fragment for authored/styled sections, use insert-component only for one automatic component template, then update-text, update-props, update-styles, upload-asset, create-page, and page/project settings tools over raw patches.",
"Use apply-patch only when no semantic tool covers the required change, and only after reading the latest snapshot/version.",
"For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.",
@@ -72,19 +72,19 @@ export const cliDocSections = {
"If a task truly requires generated app customization, keep it outside app/__generated__ where possible and explain that it is not editable Webstudio content.",
],
valuesVsBindings: [
- "Use direct value tools for fixed content. For visible text, use update-text with plain text. For static props such as aria-label, alt, id, class, href, or button labels stored as props, use update-props with the prop's direct type/value.",
+ "Use direct value tools for fixed content. For one visible text child, use update-text with plain text. For a bounded multi-instance literal replacement, use replace-text with find, replace, pagePath or pageId, and limit; it does not change expression children. Use replace-prop-text for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as aria-label, alt, id, class, href, or button labels stored as props, use update-props with the prop's direct type/value.",
"Use bind-props only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as system. Do not use bind-props just to set a fixed string.",
'Direct prop string example: {"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}.',
'Expression binding example: {"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}.',
- 'Page metadata fields such as title, description, language, redirect, status, and custom meta content store JavaScript expression source. For fixed text, pass a JavaScript string literal expression with JSON quoting, for example JSON.stringify("Pricing | Acme") in code or "\\"Pricing | Acme\\"" in JSON. For computed values, pass JavaScript expression code such as pageTitle ?? "Pricing | Acme".',
- 'Page metadata update example: use update-page with {"pageId":"page-id","values":{"title":"\\"Pricing | Acme\\"","meta":{"description":"\\"Plans for teams\\""}}}.',
- 'Resource URL, header, search-param, and body fields also store JavaScript expression source. For a fixed URL, use a string literal expression such as "\\"https://api.example.com/items\\"".',
- 'Resource update example: use update-resource with {"resourceId":"resource-id","values":{"url":"\\"https://api.example.com/items\\""}}.',
+ 'Page metadata fields such as title, description, language, redirect, status, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as pageTitle ?? "Pricing | Acme".',
+ 'Page metadata update example: use update-page with {"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}.',
+ 'Resource url accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as "https://api.example.com/items?tag=" + filters.tag. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use { "type": "literal", "value": "application/json" }.',
+ 'Resource update example: use update-resource with {"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}.',
"Data variable values support string, number, boolean, string[], and json. Use string[] only for arrays where every item is a string; use json for objects, mixed arrays, filters, and nested data.",
"Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as system in expressions where they are already in scope.",
"Use scoped resources for read data. A resource created with scopeInstanceId/dataSourceName becomes a scoped resource data variable, is generated into the page resource data map, and may be loaded while rendering the page. Use this for GET CMS/API data and read the loaded resource result from its wrapper, usually .data.",
'Use prop-bound resources for actions. A resource created without scopeInstanceId and bound to a component prop such as Form action with bind-props and binding.type: "resource" becomes an action resource in the page resource action map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.',
- 'For dynamic resource query parameters prefer searchParams, for example {"name":"tag","value":"filters.tag"}. Header values can be expressions such as "\\"Bearer \\" + auth.token". Body can be an object expression, including GraphQL payloads such as { query: "...", variables: { slug: system.params.slug } }.',
+ 'For dynamic resource query parameters prefer searchParams, for example {"name":"tag","value":"filters.tag"}. Use {"type":"literal","value":"website"} for fixed request text. Header values can be expressions such as "\\"Bearer \\" + auth.token". Body can be an object expression, including GraphQL payloads such as { query: "...", variables: { slug: system.params.slug } }.',
'Resource methods are get, post, put, and delete. Optional resource controls are graphql and system. Use control:"graphql" for GraphQL POST resources with query bodies. Use control:"system" for built-in local resource URLs such as "/$resources/current-date" and for resources reading the built-in system parameter. The built-in system fields are system.origin, system.pathname, system.params, and system.search; do not use system.path.',
],
rules: [
@@ -97,7 +97,7 @@ export const cliDocSections = {
"For visual/design work, verify the rendered result with vision before finishing.",
"Do not edit generated files for normal Webstudio content/design requests.",
"Use direct values for static strings and bindings only for dynamic expressions/resources/actions.",
- "For expression-backed fields that need fixed text, encode the fixed text as a quoted JavaScript string literal expression.",
+ "Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.",
"Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.",
"Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.",
],
@@ -108,7 +108,7 @@ export const cliDocSections = {
"Operate on the configured project only.",
"Read ids before writing.",
"Prefer semantic tools over apply-patch.",
- "Use status and refresh when cached namespaces may be stale.",
+ 'Use status and refresh when cached namespaces may be stale. Pass status {"verbose":true} only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.',
"A mutation is durable only when meta.session.committed is true.",
"For visual/design work, verify the rendered result with vision before finishing.",
],
diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.md
index d2ca9f9143..560b9c69c8 100644
--- a/packages/cli/src/docs/api-use-cases.md
+++ b/packages/cli/src/docs/api-use-cases.md
@@ -61,6 +61,21 @@ Notes:
- 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`. Use `resources/list` and `resources/read` for overview resources and read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused discovery is insufficient.
- From a shell, call one MCP tool with the shortcut form `webstudio <tool> '<json>'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> '<json>'`. Use `--input-file` for large payloads.
+## Inspect external shadcn registry items
+
+Commands:
+
+- webstudio registry inspect --source https://example.com/r/registry.json --item button --json
+- webstudio registry inspect --source ./registry.json --item dialog --json
+- webstudio registry inspect --source https://example.com/r/button.json --json
+
+Notes:
+
+- Reads a local or remote registry item without installing files or changing the configured Webstudio project.
+- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.
+- 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.
+- This is an inspection step only. It does not install files or change the configured project.
+
## Understand what MCP can do
Commands:
@@ -73,6 +88,8 @@ MCP lets agents work on one configured Webstudio project. Agents can:
- Inspect the linked project, token permissions, and latest editable build.
- Read selected project data for audits, migrations, and repair.
+- Search labels, text, props, resource URLs, asset metadata, and styles.
+- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.
- Create and edit pages, folders, redirects, breakpoints, and page templates.
- Create pages from reusable templates.
- Update page metadata, SEO fields, auth settings, and marketplace metadata.
@@ -93,12 +110,14 @@ MCP lets agents work on one configured Webstudio project. Agents can:
Commands:
- MCP tool: status {}
+- MCP tool: status {"verbose":true}
- MCP tool: refresh {"namespaces":["pages","instances","styles"]}
- MCP tool: reset-session {}
Notes:
- Use status before a task to understand the cached ProjectSession state.
+- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.
- Use refresh when project data may have changed outside the current MCP session.
- Use reset-session when local cached state is corrupt or incompatible.
@@ -113,6 +132,8 @@ Commands:
- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}
- 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}
- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}
+- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}
+- 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}}}
- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}
- MCP tool: vision.install-ocr {"confirm":true}
@@ -128,10 +149,10 @@ Notes:
- Preview isolates generated app dependencies under `.webstudio/preview` by linking to the CLI package dependency tree.
- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.
- If preview fails with a missing generated-app command/package such as react-router, react-router-serve, or vite, install dependencies for the CLI package and retry.
-- 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.
+- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.
- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.
- Compare the PNG, OCR text evidence, and diff artifacts against the user's intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.
-- Root CLI equivalent: webstudio preview, then webstudio screenshot <url> --output current.png.
+- 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`.
## List pages
@@ -156,23 +177,24 @@ Commands:
Commands:
- MCP tool: create-page {"name":"Pricing","path":"/pricing"}
-- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"\"Pricing\"","meta":{"description":"\"Plans for teams\""}}
+- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}
Notes:
-- `name` and `path` are plain values.
-- Page `title` and metadata text fields store JavaScript expression source. For fixed text, send a string literal expression such as `"\"Pricing\""`. For computed values, send JavaScript expression code such as `pageTitle ?? "Pricing"`.
+- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.
+- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.
## Update page settings/metadata
Commands:
-- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"\"Pricing\"","meta":{"description":"\"Plans\"","status":"200"}}}
+- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":"200"}}}
- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}
Notes:
-- Page `title` and metadata text fields store JavaScript expression source. For fixed text, send a string literal expression such as `"\"Pricing\""`. For computed values, send JavaScript expression code such as `pageTitle ?? "Pricing"`.
+- Page `title` and metadata text fields accept plain fixed values.
+- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.
## Read project settings
@@ -180,11 +202,17 @@ Commands:
- MCP tool: get-project-settings {}
+Notes:
+
+- Read `meta.agentInstructions` before making project changes. It contains the project's own guidance for AI agents.
+- Agent instructions are shared project guidance. Do not store credentials or other secrets there.
+
## Update project settings
Commands:
- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}
+- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}
## Read marketplace product
@@ -271,13 +299,13 @@ Commands:
Commands:
-- MCP tool: create-page-template {"name":"Landing Template","title":"\"Landing\""}
+- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}
## Update page template
Commands:
-- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"\"Reusable article layout\""}}}
+- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}
## Delete page template
@@ -411,15 +439,63 @@ Commands:
- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}
+## Replace bounded literal text
+
+Commands:
+
+- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}
+
+Notes:
+
+- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.
+
+## Replace bounded static prop text
+
+Commands:
+
+- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}
+
+Notes:
+
+- 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.
+
+## Replace bounded resource text
+
+Commands:
+
+- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}
+
+Notes:
+
+- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.
+
## Update props
Commands:
- MCP tool: update-props {"updates":"props.json contents"}
+- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}
Notes:
- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.
+
+## Add JSON-LD structured data
+
+Commands:
+
+- MCP tool: components.get {"component":"JsonLd"}
+- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}
+- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\"@context\":\"https://schema.org\",\"@type\":\"Organization\",\"name\":\"Acme\"}"}]}
+- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}
+
+Notes:
+
+- Prefer placing `JsonLd` inside `HeadSlot`.
+- Store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.
+- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.
+- 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.
+- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.
- Do not use bindings just to set static text.
## Delete props
@@ -467,7 +543,14 @@ Commands:
Commands:
+- MCP tool: list-design-tokens {}
- MCP tool: list-design-tokens {"withUsage":true}
+- MCP tool: list-design-tokens {"includeStyles":true}
+
+Notes:
+
+- The default response is compact and includes token id, name, declaration count, and optional usage count.
+- Use `includeStyles:true` only when you need the full inline style declarations.
## Create design tokens
@@ -580,15 +663,17 @@ Commands:
Commands:
-- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\"https://api.example.com/posts\"","headers":[]}}
+- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}
- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\"https://api.example.com/posts?tag=\" + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}
-- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"\"https://api.example.com/posts\"","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"page","value":"String(filters.page ?? 1)"}],"headers":[{"name":"Authorization","value":"\"Bearer \" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}
-- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"\"https://api.example.com/graphql\"","headers":[{"name":"Content-Type","value":"\"application/json\""}],"body":"{ query: \"query Post($slug: String!) { post(slug: $slug) { title } }\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}
-- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"\"/$resources/current-date\"","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}
+- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\"Bearer \" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}
+- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \"query Post($slug: String!) { post(slug: $slug) { title } }\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}
+- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}
Notes:
-- Resource `url`, header values, search parameter values, and body are expressions. Literal URLs are JSON strings such as `"https://api.example.com/posts"`.
+- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.
+- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.
+- 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.
- 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.
- 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.
- 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.
@@ -599,7 +684,8 @@ Notes:
Commands:
-- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"\"https://api.example.com/posts\""}}
+- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}
+- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}
## Delete resource
@@ -613,6 +699,50 @@ Commands:
- MCP tool: list-assets {"withUsage":true}
+Notes:
+
+- Image asset descriptions are the default alt text for asset-backed Image components.
+- 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.
+
+## Update asset metadata
+
+Commands:
+
+- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}
+
+Notes:
+
+- Use an empty description only when the image is intentionally decorative.
+- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.
+
+## Generate missing image descriptions with an agent
+
+Commands:
+
+- MCP tool: audit {"scopes":["accessibility"],"verbose":true}
+- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}
+- MCP tool: audit {"scopes":["accessibility"]}
+
+Notes:
+
+- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.
+- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.
+- 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.
+- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.
+
+## Manage fonts
+
+Commands:
+
+- MCP tool: list-fonts {"includeSystem":true}
+- MCP tool: list-assets {"type":"font"}
+- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}
+- MCP tool: update-styles {"updates":"styles.json contents"}
+
+Notes:
+
+- 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.
+
## Upload one asset
Commands:
@@ -724,6 +854,8 @@ Patch namespaces:
Commands:
+- MCP tool: search-project {"query":"pricing"}
+- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}
- MCP tool: list-instances {"pagePath":"/","maxDepth":5}
- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}
- MCP tool: list-texts {"pagePath":"/"}
@@ -733,7 +865,45 @@ Commands:
Notes:
-- Use this for finding elements by label, type, href/resource patterns, HTML snippets, missing accessibility metadata, or asset usage.
+- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.
+
+## Audit project quality
+
+Commands:
+
+- webstudio audit --json
+- webstudio audit --scopes accessibility,seo --json
+- webstudio audit --page-path /pricing --json
+- webstudio audit --scopes accessibility --verbose --json
+- MCP tool: audit {}
+- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}
+- MCP tool: audit {"scopes":["accessibility"],"verbose":true}
+- MCP tool: audit {"rendered":true,"verbose":true}
+
+Notes:
+
+- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.
+- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.
+- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.
+- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.
+- `summary` counts all findings before severity filtering and pagination.
+- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.
+- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.
+- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.
+- Continue paginated results with `cursor`. Restart the audit if the project version changes.
+- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.
+- Focused audits return only manual checks relevant to their selected scopes.
+- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot
+ tools to capture every static page at mobile, desktop, and Builder breakpoint
+ edges. Compact output reports rendered check/issue/failure counts; verbose
+ output includes screenshot paths and measured layout dimensions.
+- Rendered checks also report broken images, eager images below the fold, and
+ image sources more than 2x their rendered dimensions in both axes, including
+ Webstudio instance ids and measured dimensions when available.
+- Rendered checks include sanitized Resource Timing evidence and report
+ browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and
+ `.woff` fonts without applying a universal transfer-size threshold.
+- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.
## Refactor targeted content
@@ -742,23 +912,24 @@ Commands:
- MCP tool: list-instances {"pagePath":"/"}
- MCP tool: list-texts {"pagePath":"/"}
- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}
+- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}
- MCP tool: update-props {"updates":"props.json contents"}
-- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"\"Pricing\"","meta":{"description":"\"Plans\""}}}
-- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"\"https://api.example.com/posts\""}}
+- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}
+- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}
- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}
- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}
- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}
Notes:
-- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references.
+- 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.
## Optimize existing project
Commands:
- MCP tool: list-pages {"includeFolders":true}
-- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"\"Pricing\"","meta":{"description":"\"Plans\""}}}
+- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}
- MCP tool: update-props {"updates":"props.json contents"}
- MCP tool: list-breakpoints {}
- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}
@@ -778,10 +949,10 @@ Commands:
- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}
- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}
- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}
-- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\"https://api.example.com/posts\"","searchParams":[{"name":"tag","value":"filters.tag"}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}
-- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"\"https://api.example.com/graphql\"","headers":[{"name":"Content-Type","value":"\"application/json\""}],"body":"{ query: \"query Post($slug: String!) { post(slug: $slug) { title } }\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}
-- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"\"/$resources/current-date\"","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}
-- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"\"https://api.example.com/posts\""}}
+- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}
+- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \"query Post($slug: String!) { post(slug: $slug) { title } }\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}
+- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}
+- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}
- MCP tool: bind-props {"bindings":"bindings.json contents"}
- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}
@@ -798,7 +969,7 @@ Commands:
- MCP tool: update-props {"updates":"props.json contents"}
- MCP tool: bind-props {"bindings":"bindings.json contents"}
-- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"\"https://api.example.com/seats\"","headers":[]}}
+- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}
- MCP tool: snapshot {"include":["instances","props","resources"]}
- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}
@@ -813,7 +984,7 @@ Commands:
- MCP tool: create-page {"name":"Account","path":"/account"}
- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}
-- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"\"https://api.example.com/session\"","headers":[]}}
+- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}
- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}
- MCP tool: update-props {"updates":"props.json contents"}
- MCP tool: bind-props {"bindings":"bindings.json contents"}
@@ -853,20 +1024,6 @@ Notes:
# Known CLI Gaps
-## General project search and audit
-
-Missing:
-No single semantic command searches across instance labels, props, hrefs, resource URLs, HTML embeds, asset references, and missing accessibility metadata.
-
-Current fallback:
-Use focused MCP reads such as list-instances, list-texts, list-assets, find-asset-usage, and snapshot.
-
-Suggested commands:
-
-- search-project
-- audit-accessibility
-- find-prop-usage
-
## Provider-specific authenticated pages
Missing:
diff --git a/packages/cli/src/docs/manual-api.md b/packages/cli/src/docs/manual-api.md
index 34807b9e26..a976381d20 100644
--- a/packages/cli/src/docs/manual-api.md
+++ b/packages/cli/src/docs/manual-api.md
@@ -29,7 +29,7 @@ The API commands operate on the single project configured by:
- Successful mutation commits update the local snapshot only after the remote commit succeeds.
- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.
- Use --refresh on local-capable commands to refresh required namespaces before running.
-- Successful JSON responses include meta.session with operationId, buildId, version, source, committed, compatibility, namespace freshness, and diagnostics.
+- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.
## CLI Capability Inventory
@@ -78,7 +78,7 @@ Each transaction has:
"id": "patch-transaction-label",
"payload": [
{
-"namespace": "pages",
+"namespace": "projectSettings",
"patches": [
{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }
]
@@ -94,7 +94,8 @@ Patch paths are JSON-patch-like paths into Builder store data. Map-like namespac
Supported namespaces:
-- pages: site metadata, redirects, page records, folders, compiler settings
+- pages: redirects, page records, and folders
+- projectSettings: project-wide metadata and compiler settings
- instances: element instances and children, including text/expression children
- props: element props, bindings, page references, resource bindings
- styles: CSS declarations keyed by style declaration key
@@ -131,13 +132,16 @@ or delete parameter records. Public tools should preserve existing parameter
records and may reference documented context values such as `system` in
expressions where they are already in scope.
-Resource request fields are expressions too. Literal URLs must be JSON strings,
-for example `"https://api.example.com/posts"`. Dynamic URLs can combine strings
-and variables, for example `"https://api.example.com/posts?tag=" + filters.tag`.
-Prefer `searchParams` for query parameters that should be encoded separately:
-`[{ "name": "tag", "value": "filters.tag" }]`. Header values and body are also
-expressions, so headers can read variables such as `"Bearer " + auth.token`, and
-GraphQL bodies can return objects such as
+Resource `url` accepts plain fixed URLs and paths, for example
+`https://api.example.com/posts` or `/$resources/current-date`. Dynamic URLs can
+combine strings and variables, for example
+`"https://api.example.com/posts?tag=" + filters.tag`. Prefer `searchParams` for
+query parameters that should be encoded separately:
+`[{ "name": "tag", "value": "filters.tag" }]`. Header values, search parameter
+values, and bodies are expressions for dynamic content. For fixed text, use
+`{ "type": "literal", "value": "application/json" }`; Webstudio stores the
+required string expression. Headers can still read variables such as
+`"Bearer " + auth.token`, and GraphQL bodies can return objects such as
`{ query: "...", variables: { slug: system.params.slug } }`.
Create a resource with `scopeInstanceId`/`--scope-instance` when the fetched
@@ -181,7 +185,7 @@ Rename the site:
"id": "patch-site-name",
"payload": [
{
-"namespace": "pages",
+"namespace": "projectSettings",
"patches": [
{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }
]
diff --git a/packages/cli/src/docs/manual-llm.md b/packages/cli/src/docs/manual-llm.md
index 1d57d7ba86..5217a3f116 100644
--- a/packages/cli/src/docs/manual-llm.md
+++ b/packages/cli/src/docs/manual-llm.md
@@ -346,11 +346,11 @@ For Video Animation, use the registered template via `insert-component` when pos
## Command Surface Boundary
-- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, man, and starting MCP.
+- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.
- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.
- From a shell, call MCP tools with the shortcut form `webstudio <tool> '<json>'`, for example `webstudio insert-fragment '<json>' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> '<json>'`. Use `--input-file` for large payloads.
- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.
-- For experiments, pass `--dry-run` to local-capable mutation calls. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.
+- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.
- For bounded multi-step shell work, run inline JSON with `webstudio mcp run '[{"tool":"components.find","input":{"brief":"button"}}]'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.
- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.
- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.
@@ -367,7 +367,7 @@ For Video Animation, use the registered template via `insert-component` when pos
Use this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:
1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search '{"brief":"button"}'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.
-2. Inspect current project state with semantic reads such as `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed.
+2. Inspect current project state with semantic reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.
3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.
4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.
5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.
@@ -412,19 +412,19 @@ For responsive page work, use Builder breakpoints as the source of truth:
## Values vs Bindings
-- Use direct value tools for fixed content. For visible text, use `update-text` with plain `text`. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop's direct type/value.
+- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop's direct type/value.
- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.
- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.
- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.
-- Page metadata fields such as `title`, `description`, `language`, `redirect`, `status`, and custom meta content store JavaScript expression source. For fixed text, pass a JavaScript string literal expression with JSON quoting, for example `JSON.stringify("Pricing | Acme")` in code or `"\"Pricing | Acme\""` in JSON. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.
-- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"\"Pricing | Acme\"","meta":{"description":"\"Plans for teams\""}}}`.
-- Resource URL, header, search-param, and body fields also store JavaScript expression source. For a fixed URL, use a string literal expression such as `"\"https://api.example.com/items\""`.
-- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"\"https://api.example.com/items\""}}`.
+- Page metadata fields such as `title`, `description`, `language`, `redirect`, `status`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.
+- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.
+- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.
+- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.
- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`. Use `string[]` only for arrays where every item is a string; use `json` for objects, mixed arrays, filters, and nested data.
- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.
- Use scoped resources for read data. A resource created with `scopeInstanceId`/`dataSourceName` becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Use this for GET CMS/API data and read the loaded resource result from its wrapper, usually `.data`.
- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.
-- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Header values can be expressions such as `"\"Bearer \" + auth.token"`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.
+- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can be expressions such as `"\"Bearer \" + auth.token"`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.
- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.
## Pick Read Command
@@ -460,7 +460,7 @@ MCP tools receive JSON argument objects, not CLI flags. Use these shapes:
- For visual/design work, verify the rendered result with vision before finishing.
- Do not edit generated files for normal Webstudio content/design requests.
- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.
-- For expression-backed fields that need fixed text, encode the fixed text as a quoted JavaScript string literal expression.
+- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.
- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.
- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.
diff --git a/packages/cli/src/docs/manual-mcp.md b/packages/cli/src/docs/manual-mcp.md
index 231e0fb847..8c4b3f59b0 100644
--- a/packages/cli/src/docs/manual-mcp.md
+++ b/packages/cli/src/docs/manual-mcp.md
@@ -71,7 +71,7 @@ Rules:
- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.
- The positional input is JSON and defaults to `{}`.
- Use `--input-file` for large mutation payloads.
-- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.
+- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.
- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.
- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.
- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.
@@ -236,12 +236,13 @@ terms, agents can:
Useful resources:
-- `webstudio://project/status`: current ProjectSession status
+- `webstudio://project/status`: compact current ProjectSession status
- `webstudio://project/tools-overview`: small operation overview by capability area
- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories
- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient
- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient
- `webstudio://project/guide`: concise discovery guide
+- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots
## MCP SDK Client Imports
@@ -295,7 +296,7 @@ Use `node packages/cli/local.js mcp` from the Webstudio monorepo root for local
- Operate on the configured project only.
- Read ids before writing.
- Prefer semantic tools over `apply-patch`.
-- Use `status` and `refresh` when cached namespaces may be stale.
+- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.
- A mutation is durable only when `meta.session.committed` is true.
- For visual/design work, verify the rendered result with vision before finishing.
diff --git a/packages/cli/src/docs/mcp-startup-epilogue.md b/packages/cli/src/docs/mcp-startup-epilogue.md
index ceb8c89271..ae218a3b16 100644
--- a/packages/cli/src/docs/mcp-startup-epilogue.md
+++ b/packages/cli/src/docs/mcp-startup-epilogue.md
@@ -24,7 +24,7 @@ When building for a Content-mode editor, use a Content Block (`ws:block`) around
Run it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.
-For experiments, pass `--dry-run` to local-capable mutation calls. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.
+For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.
Startup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.
diff --git a/packages/cli/src/docs/mcp-vision.md b/packages/cli/src/docs/mcp-vision.md
index 87678319be..64df951287 100644
--- a/packages/cli/src/docs/mcp-vision.md
+++ b/packages/cli/src/docs/mcp-vision.md
@@ -19,8 +19,8 @@ For visual/design work, use preview.start and screenshot after generated project
- For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.
- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.
- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baseUrl: "http://127.0.0.1:5177", path: "/" }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.
-- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair.
-- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.
+- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair. Add expectedText when a specific visible phrase must be present; its assertions report pass/fail plus found and missing text. Add expectedVisual to set pass/fail limits for mismatch percentage, the number of changed regions, or an overall dominant color/brightness direction.
+- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, expectedText assertions fail and textAnalysis reports why; ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.
- Inspect every viewport PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.
- If the screenshot does not match, apply another focused mutation and repeat screenshot verification.
@@ -32,14 +32,37 @@ For visual/design work, make sure generated project files are current, call prev
For visual/design work, make sure generated project files are current, call preview.start to build and start the production-like preview server, then screenshot({ path, viewport }) for every changed page path; for responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths; inspect every PNG with vision before finishing.
+Each screenshot result includes rendered `layout` metrics when the local browser
+provides them. `layout.horizontalOverflow: true` is deterministic evidence that
+the rendered document exceeds the requested viewport width. Use vision for
+clipping, wrapping, hierarchy, and other judgments that layout dimensions alone
+cannot establish.
+
+Pass `includeImageMetrics: true` when an ordinary screenshot needs
+`layout.images`; rendered audit enables it automatically. The array includes
+each rendered image's Webstudio instance id when available, loading mode,
+completion state, natural dimensions, rendered dimensions, and document
+position. Rendered audits use this evidence to report broken images, eager
+loading below the fold, and sources more than 2x the rendered dimensions in
+both axes. Oversized-source results are optimization evidence, not universal
+performance conformance.
+
+Pass `includeResourceMetrics: true` when an ordinary screenshot needs sanitized
+Resource Timing evidence; rendered audit enables it automatically. Resource
+metrics contain only the URL pathname, initiator type, transfer/body sizes,
+duration, and browser-provided render-blocking status. Origins and query strings
+are omitted. Rendered audits report explicitly blocking resources and legacy
+`.ttf`, `.otf`, or `.woff` font files without applying a universal byte-size
+budget.
+
## Screenshot Verification Summary
-Inside a long-running MCP server, prefer preview.start plus screenshot({ path, viewport }) after generated project files are current, so a fresh production-like preview server is available for fast repeated checks across multiple pages. After MCP mutations, path screenshots restart preview as needed before capture; when preview is fresh in that same MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture viewport widths from Builder breakpoint edges plus mobile and desktop widths before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use webstudio preview and webstudio screenshot <url> --output current.png.
+Inside a long-running MCP server, prefer preview.start plus screenshot({ path, viewport }) after generated project files are current, so a fresh production-like preview server is available for fast repeated checks across multiple pages. After MCP mutations, path screenshots restart preview as needed before capture; when preview is fresh in that same MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture viewport widths from Builder breakpoint edges plus mobile and desktop widths before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use `webstudio screenshot --path /pricing --output pricing.png` for one temporary generated preview capture, or keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot` for repeated captures.
## Screenshot Diff Evidence
- Pixel evidence: total mismatch, changed regions, dominant color/luminance direction, diffPath, and contextDiffPath.
-- OCR evidence: textAnalysis.status, provider, and changes for appeared/disappeared/content_changed/moved/font_changed text.
+- OCR evidence: textAnalysis.status, provider, and changes for appeared/disappeared/content_changed/moved/font_changed text. expectedText adds pass/fail assertions plus found and missing current-screen text. expectedVisual adds pass/fail quantitative checks for mismatch percentage, changed-region count, and the overall dominant color/brightness direction.
- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.
- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.
- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.
diff --git a/packages/cli/src/managed-agents.test.ts b/packages/cli/src/managed-agents.test.ts
new file mode 100644
index 0000000000..c46ba7464c
--- /dev/null
+++ b/packages/cli/src/managed-agents.test.ts
@@ -0,0 +1,50 @@
+import { afterEach, beforeEach, expect, test } from "vitest";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import {
+ managedAgentsHeader,
+ materializeManagedAgents,
+} from "./managed-agents";
+
+let rootDir: string;
+
+beforeEach(async () => {
+ rootDir = await mkdtemp(join(tmpdir(), "webstudio-agents-"));
+});
+
+afterEach(async () => {
+ await rm(rootDir, { recursive: true, force: true });
+});
+
+test("creates, updates, and removes the managed AGENTS.md", async () => {
+ await expect(
+ materializeManagedAgents({ rootDir, instructions: "Use tokens." })
+ ).resolves.toMatchObject({ status: "created" });
+ expect(await readFile(join(rootDir, "AGENTS.md"), "utf8")).toBe(
+ `${managedAgentsHeader}\n\nUse tokens.\n`
+ );
+
+ await expect(
+ materializeManagedAgents({ rootDir, instructions: "Use components." })
+ ).resolves.toMatchObject({ status: "updated" });
+ await expect(
+ materializeManagedAgents({ rootDir, instructions: "Use components." })
+ ).resolves.toMatchObject({ status: "unchanged" });
+ await expect(
+ materializeManagedAgents({ rootDir, instructions: "" })
+ ).resolves.toMatchObject({ status: "removed" });
+});
+
+test("never overwrites or removes a user-owned AGENTS.md", async () => {
+ const path = join(rootDir, "AGENTS.md");
+ await writeFile(path, "# User instructions\n", "utf8");
+
+ await expect(
+ materializeManagedAgents({ rootDir, instructions: "Use tokens." })
+ ).resolves.toMatchObject({ status: "blocked-by-user-file", path });
+ await expect(
+ materializeManagedAgents({ rootDir, instructions: "" })
+ ).resolves.toMatchObject({ status: "unchanged", path });
+ expect(await readFile(path, "utf8")).toBe("# User instructions\n");
+});
diff --git a/packages/cli/src/managed-agents.ts b/packages/cli/src/managed-agents.ts
new file mode 100644
index 0000000000..84fe438649
--- /dev/null
+++ b/packages/cli/src/managed-agents.ts
@@ -0,0 +1,69 @@
+import { readFile, rm } from "node:fs/promises";
+import { join } from "node:path";
+import { isFileExists, writeFileAtomic } from "./fs-utils";
+
+export const managedAgentsHeader = [
+ "<!-- Webstudio-managed project agent instructions. -->",
+ "<!-- Source: Project Settings > Agents. Do not edit this file directly. -->",
+].join("\n");
+
+export type ManagedAgentsResult =
+ | "created"
+ | "updated"
+ | "removed"
+ | "unchanged"
+ | "blocked-by-user-file";
+
+export type ManagedAgentsDependencies = {
+ isFileExists: typeof isFileExists;
+ readFile: typeof readFile;
+ removeFile: typeof rm;
+ writeFileAtomic: typeof writeFileAtomic;
+};
+
+const defaultDependencies: ManagedAgentsDependencies = {
+ isFileExists,
+ readFile,
+ removeFile: rm,
+ writeFileAtomic,
+};
+
+const createManagedContent = (instructions: string) =>
+ `${managedAgentsHeader}\n\n${instructions.trim()}\n`;
+
+export const materializeManagedAgents = async ({
+ rootDir,
+ instructions,
+ dependencies = defaultDependencies,
+}: {
+ rootDir: string;
+ instructions: string | undefined;
+ dependencies?: ManagedAgentsDependencies;
+}): Promise<{ path: string; status: ManagedAgentsResult }> => {
+ const path = join(rootDir, "AGENTS.md");
+ const exists = await dependencies.isFileExists(path);
+ const current = exists
+ ? await dependencies.readFile(path, "utf8")
+ : undefined;
+ const isManaged = current?.startsWith(managedAgentsHeader) === true;
+ const normalizedInstructions = instructions?.trim() ?? "";
+
+ if (normalizedInstructions === "") {
+ if (isManaged) {
+ await dependencies.removeFile(path, { force: true });
+ return { path, status: "removed" };
+ }
+ return { path, status: "unchanged" };
+ }
+
+ if (current !== undefined && isManaged === false) {
+ return { path, status: "blocked-by-user-file" };
+ }
+
+ const next = createManagedContent(normalizedInstructions);
+ if (current === next) {
+ return { path, status: "unchanged" };
+ }
+ await dependencies.writeFileAtomic(path, next);
+ return { path, status: current === undefined ? "created" : "updated" };
+};
diff --git a/packages/cli/src/mcp-guidance.test.ts b/packages/cli/src/mcp-guidance.test.ts
index ee96e12287..d3dca8a6e4 100644
--- a/packages/cli/src/mcp-guidance.test.ts
+++ b/packages/cli/src/mcp-guidance.test.ts
@@ -33,6 +33,12 @@ test("builds vision loop with optional screenshot diff guidance", () => {
expect(visionLoopWithDiff).toEqual(
expect.arrayContaining([expect.stringContaining("vision.install-ocr")])
);
+ expect(visionLoopWithDiff).toEqual(
+ expect.arrayContaining([expect.stringContaining("expectedText")])
+ );
+ expect(visionLoopWithDiff).toEqual(
+ expect.arrayContaining([expect.stringContaining("expectedVisual")])
+ );
expect(visionLoopWithDiff).toEqual(
expect.arrayContaining([
expect.stringContaining("list-breakpoints"),
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index 71e936d927..2c2c29fd1a 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -43,7 +43,10 @@ import {
} from "@webstudio-is/sdk";
import { migratePages } from "@webstudio-is/project-migrations/pages";
import { collectFontFamiliesFromStyleDecls } from "@webstudio-is/project-build/runtime/style-utils";
-import { publishedProjectBundle } from "@webstudio-is/protocol";
+import {
+ publishedProjectBundle,
+ type PublishedProjectBundle,
+} from "@webstudio-is/protocol";
import { createAuthConfigResources, LOCAL_AUTH_FILE } from "./auth-config";
import { LOCAL_DATA_FILE } from "./config";
import {
@@ -130,8 +133,12 @@ const readAssetBaseUrl = async (constantsPath: string) => {
);
};
-const writeWsAuthResources = async (generatedDir: string, pages: Pages) => {
- const { content, module } = createAuthConfigResources(pages);
+const writeWsAuthResources = async (
+ generatedDir: string,
+ pages: Pages,
+ projectSettings?: PublishedProjectBundle["build"]["projectSettings"]
+) => {
+ const { content, module } = createAuthConfigResources(pages, projectSettings);
await createFolderIfNotExists(dirname(LOCAL_AUTH_FILE));
await writeFile(LOCAL_AUTH_FILE, content);
await createFileIfNotExists(
@@ -322,7 +329,11 @@ export const prebuild = async (options: {
);
const pages = migratePages(siteData.build.pages);
const allPages = getAllPages(pages);
- await writeWsAuthResources(generatedDir, pages);
+ await writeWsAuthResources(
+ generatedDir,
+ pages,
+ siteData.build.projectSettings
+ );
const siteDataByPage: SiteDataByPage = {};
const fontAssetsByPage: Record<Page["id"], string[]> = {};
const backgroundImageAssetsByPage: Record<Page["id"], string[]> = {};
@@ -472,7 +483,10 @@ export const prebuild = async (options: {
// pass only used metas to not generate unused preset styles
componentMetas: usedMetas,
assetBaseUrl,
- atomic: pages.compiler?.atomicStyles ?? true,
+ atomic:
+ siteData.build.projectSettings?.compiler.atomicStyles ??
+ pages.compiler?.atomicStyles ??
+ true,
});
await createFileIfNotExists(join(generatedDir, "index.css"), cssText);
@@ -585,7 +599,7 @@ export const prebuild = async (options: {
tagsOverrides: framework.tags,
});
- const projectMeta = pages.meta;
+ const projectMeta = siteData.build.projectSettings?.meta ?? pages.meta;
const contactEmail: undefined | string =
// fallback to user email when contact email is empty string
projectMeta?.contactEmail || siteData.user?.email || undefined;
diff --git a/packages/cli/src/project-session-api.test.ts b/packages/cli/src/project-session-api.test.ts
index ac49956152..59d25a5956 100644
--- a/packages/cli/src/project-session-api.test.ts
+++ b/packages/cli/src/project-session-api.test.ts
@@ -94,6 +94,48 @@ describe("project session api adapter", () => {
);
});
+ test("does not inject project id into strict audit input", async () => {
+ const session = {
+ initialize: vi.fn(async () => undefined),
+ read: vi.fn(async () => ({
+ operationId: "project.audit",
+ projectId: "project-1",
+ source: "local",
+ result: { findings: [] },
+ state: { committed: false, freshness: {} },
+ namespaces: {
+ read: [],
+ write: [],
+ invalidated: [],
+ missing: [],
+ },
+ diagnostics: [],
+ })),
+ mutate: vi.fn(),
+ refresh: vi.fn(),
+ executeServerOperation: vi.fn(),
+ };
+
+ await executeProjectSessionApiOperation({
+ command: "audit",
+ input: { scopes: ["seo"] },
+ connection: {
+ projectId: "project-1",
+ origin: "https://example.com",
+ authToken: "token",
+ },
+ createProjectSession: vi.fn(
+ () => session
+ ) as unknown as CreateProjectSession,
+ });
+
+ expect(session.read).toHaveBeenCalledWith(
+ "project.audit",
+ { scopes: ["seo"] },
+ { permit: "view" }
+ );
+ });
+
test("routes server-only commands through project session transport", async () => {
const session = {
initialize: vi.fn(async () => undefined),
@@ -172,7 +214,7 @@ describe("project session api adapter", () => {
refresh: true,
});
- expect(session.refresh).toHaveBeenCalledWith(["pages"]);
+ expect(session.refresh).toHaveBeenCalledWith(["pages", "projectSettings"]);
});
test("explains dry-run is only for local-capable mutations", async () => {
diff --git a/packages/cli/src/project-session-api.ts b/packages/cli/src/project-session-api.ts
index 45d6ac4e01..458fdf6adc 100644
--- a/packages/cli/src/project-session-api.ts
+++ b/packages/cli/src/project-session-api.ts
@@ -4,7 +4,10 @@ import {
} from "@webstudio-is/protocol";
import type { RuntimeOperationId } from "@webstudio-is/project-build/contracts/builder-runtime";
import type { BuilderNamespace } from "@webstudio-is/project-build/contracts/namespaces";
-import type { ProjectSessionEnvelope } from "@webstudio-is/project-build/project-session";
+import {
+ serializeProjectSessionMeta,
+ type ProjectSessionEnvelope,
+} from "@webstudio-is/project-build/project-session";
import { createCliProjectSession } from "./project-session";
export type ProjectSessionApiConnection = {
@@ -59,17 +62,7 @@ export const isProjectSessionEnvelope = (
"namespaces" in value &&
"diagnostics" in value;
-export const getProjectSessionMeta = (envelope: ProjectSessionEnvelope) => ({
- operationId: envelope.operationId,
- projectId: envelope.projectId,
- buildId: envelope.buildId,
- version: envelope.version,
- source: envelope.source,
- committed: envelope.state.committed,
- compatibility: envelope.state.compatibility,
- namespaces: envelope.namespaces,
- diagnostics: envelope.diagnostics,
-});
+export const getProjectSessionMeta = serializeProjectSessionMeta;
export const executeProjectSessionApiOperation = async ({
command,
@@ -122,7 +115,9 @@ export const executeProjectSessionApiOperation = async ({
: operation.method === "query"
? await session.read(
runtimeOperationId,
- withProjectId(input, connection.projectId),
+ command === "audit"
+ ? input
+ : withProjectId(input, connection.projectId),
{ permit: operation.permit }
)
: await session.mutate(
diff --git a/packages/cli/src/project-session.test.ts b/packages/cli/src/project-session.test.ts
index 732b7c6945..5aae08cba9 100644
--- a/packages/cli/src/project-session.test.ts
+++ b/packages/cli/src/project-session.test.ts
@@ -126,7 +126,18 @@ describe("cli project session storage", () => {
});
test("creates preview bundle from project session snapshot", () => {
+ const marketplaceProduct = {
+ category: "pageTemplates" as const,
+ name: "Session template",
+ thumbnailAssetId: "asset-1",
+ author: "Webstudio",
+ email: "[email protected]",
+ website: "https://example.com",
+ issues: "",
+ description: "A reusable project-session template.",
+ };
const state = createBuilderStateFromSnapshot({
+ marketplaceProduct,
pages: {
homePageId: "home",
rootFolderId: "root",
@@ -210,6 +221,7 @@ test("creates preview bundle from project session snapshot", () => {
"body",
"design-system-body",
]);
+ expect(bundle.build.marketplaceProduct).toEqual(marketplaceProduct);
});
describe("cli project session transport", () => {
@@ -221,7 +233,12 @@ describe("cli project session transport", () => {
authToken: "token",
},
getBuildSnapshot: async (input) => {
- expect(input.include).toEqual(["pages", "folders", "instances"]);
+ expect(input.include).toEqual([
+ "pages",
+ "folders",
+ "instances",
+ "projectSettings",
+ ]);
return {
projectId: "project-1",
buildId: "build-1",
@@ -241,6 +258,10 @@ describe("cli project session transport", () => {
meta: { siteName: "Acme" },
compiler: { atomicStyles: true },
redirects: [{ old: "/old", new: "/new", status: "301" }],
+ projectSettings: {
+ meta: { siteName: "Canonical Acme" },
+ compiler: { atomicStyles: false },
+ },
folders: [
{
id: "root",
@@ -263,12 +284,12 @@ describe("cli project session transport", () => {
const snapshot = await transport.fetchNamespaces({
projectId: "project-1",
- namespaces: ["pages", "instances"],
+ namespaces: ["pages", "instances", "projectSettings"],
});
expect(snapshot.state.pages?.pages.get("home")?.name).toBe("Home");
- expect(snapshot.state.pages?.meta).toEqual({ siteName: "Acme" });
- expect(snapshot.state.pages?.compiler).toEqual({ atomicStyles: true });
+ expect(snapshot.state.pages?.meta).toBeUndefined();
+ expect(snapshot.state.pages?.compiler).toBeUndefined();
expect(snapshot.state.pages?.redirects).toEqual([
{ old: "/old", new: "/new", status: "301" },
]);
@@ -276,6 +297,10 @@ describe("cli project session transport", () => {
"home",
]);
expect(snapshot.state.instances?.get("body")?.component).toBe("Body");
+ expect(snapshot.state.projectSettings).toEqual({
+ meta: { siteName: "Canonical Acme" },
+ compiler: { atomicStyles: false },
+ });
});
test("adapts injected permission reader to project session transport", async () => {
diff --git a/packages/cli/src/project-session.ts b/packages/cli/src/project-session.ts
index 9fb100e342..df47f3ab55 100644
--- a/packages/cli/src/project-session.ts
+++ b/packages/cli/src/project-session.ts
@@ -31,6 +31,7 @@ import {
type BuilderBuildDataSnapshot,
type SerializedBuilderStateSnapshot,
} from "@webstudio-is/project-build/state/adapters";
+import { removeLegacyProjectSettingsFromPages } from "@webstudio-is/project-build/shared/project-settings";
import type { BuilderStateFreshness } from "@webstudio-is/project-build/state/freshness";
import { LOCAL_CONFIG_FILE, LOCAL_DATA_FILE } from "./config";
import { getStableErrorCode } from "./error-codes";
@@ -57,6 +58,7 @@ type PublicBuildSnapshot = Omit<
meta?: unknown;
compiler?: unknown;
redirects?: unknown;
+ projectSettings?: BuilderBuildDataSnapshot["projectSettings"];
dataSources?: BuilderBuildDataSnapshot["dataSources"];
variables?: BuilderBuildDataSnapshot["dataSources"];
};
@@ -87,6 +89,9 @@ const toPublicApiInclude = (namespaces: readonly BuilderNamespace[]) => [
if (namespace === "pages") {
return ["pages", "folders"];
}
+ if (namespace === "projectSettings") {
+ return ["projectSettings"];
+ }
return [namespace];
})
),
@@ -328,15 +333,22 @@ export const createLocalProjectBundleFromSessionSnapshot = (
if (pages === undefined) {
throw new Error("Project session pages namespace is missing.");
}
- const serializedPages = serializePages(pages);
- const homePage = getHomePage(pages);
+ const projectSettings = snapshot.state.projectSettings;
+ const persistedPages = removeLegacyProjectSettingsFromPages(
+ structuredClone(pages)
+ );
+ const serializedPages = serializePages(persistedPages);
+ const homePage = getHomePage(persistedPages);
return {
bundleVersion,
origin: options.origin,
projectDomain: "local-preview",
- projectTitle: pages.meta?.siteName ?? "Webstudio Preview",
+ projectTitle:
+ projectSettings?.meta.siteName ??
+ persistedPages.meta?.siteName ??
+ "Webstudio Preview",
page: homePage,
- pages: Array.from(pages.pages.values()),
+ pages: Array.from(persistedPages.pages.values()),
assets: Array.from(snapshot.state.assets?.values() ?? []),
build: {
id: snapshot.buildId,
@@ -355,6 +367,8 @@ export const createLocalProjectBundleFromSessionSnapshot = (
instances: Array.from(snapshot.state.instances?.entries() ?? []),
dataSources: Array.from(snapshot.state.dataSources?.entries() ?? []),
resources: Array.from(snapshot.state.resources?.entries() ?? []),
+ marketplaceProduct: snapshot.state.marketplaceProduct,
+ projectSettings,
},
};
};
diff --git a/packages/cli/src/screenshot-browser-cdp.test.ts b/packages/cli/src/screenshot-browser-cdp.test.ts
index 03d5cb5700..0948fbfdcb 100644
--- a/packages/cli/src/screenshot-browser-cdp.test.ts
+++ b/packages/cli/src/screenshot-browser-cdp.test.ts
@@ -74,6 +74,69 @@ class FakeWebSocket {
setTimeout(() => respond({ result: { value: true } }), 0);
return;
}
+ if (
+ message.method === "Runtime.evaluate" &&
+ typeof message.params?.expression === "string" &&
+ message.params.expression.includes(
+ 'performance.getEntriesByType("resource")'
+ )
+ ) {
+ setTimeout(
+ () =>
+ respond({
+ result: {
+ value: [
+ {
+ pathname: "/styles.css",
+ initiatorType: "link",
+ transferSize: 12000,
+ encodedBodySize: 11000,
+ decodedBodySize: 40000,
+ duration: 25,
+ renderBlockingStatus: "blocking",
+ },
+ {
+ pathname: "/fonts/brand.ttf",
+ initiatorType: "css",
+ transferSize: 80000,
+ encodedBodySize: 79000,
+ decodedBodySize: 79000,
+ duration: 40,
+ },
+ ],
+ },
+ }),
+ 0
+ );
+ return;
+ }
+ if (
+ message.method === "Runtime.evaluate" &&
+ typeof message.params?.expression === "string" &&
+ message.params.expression.includes("Array.from(document.images")
+ ) {
+ setTimeout(
+ () =>
+ respond({
+ result: {
+ value: [
+ {
+ instanceId: "hero-image",
+ loading: "eager",
+ complete: true,
+ naturalWidth: 2400,
+ naturalHeight: 1600,
+ renderedWidth: 600,
+ renderedHeight: 400,
+ top: 1000,
+ },
+ ],
+ },
+ }),
+ 0
+ );
+ return;
+ }
if (message.method === "Page.captureScreenshot") {
setTimeout(
() =>
@@ -94,6 +157,10 @@ class FakeWebSocket {
width: 812.4,
height: 2345.6,
},
+ cssLayoutViewport: {
+ clientWidth: 800,
+ clientHeight: 600,
+ },
}),
0
);
@@ -167,13 +234,11 @@ const createDependencies = ({
} = {}): BrowserScreenshotDependencies => {
const defaultFetch = vi.fn(async (url: string) => ({
json: async () =>
- url.endsWith("/json/list")
- ? [
- {
- type: "page",
- webSocketDebuggerUrl: "ws://127.0.0.1:9222/page/1",
- },
- ]
+ url.includes("/json/new?")
+ ? {
+ type: "page",
+ webSocketDebuggerUrl: "ws://127.0.0.1:9222/page/created",
+ }
: {},
})) as unknown as typeof globalThis.fetch;
return {
@@ -229,11 +294,8 @@ test("captures through DevTools with lifecycle and selector waits", async () =>
"http://127.0.0.1:9222/json/new?about:blank",
{ method: "PUT" }
);
- expect(dependencies.fetch).toHaveBeenCalledWith(
- "http://127.0.0.1:9222/json/list"
- );
expect(dependencies.createWebSocket).toHaveBeenCalledWith(
- "ws://127.0.0.1:9222/page/1"
+ "ws://127.0.0.1:9222/page/created"
);
expect(socket.sentMethods).toEqual(
expect.arrayContaining([
@@ -258,18 +320,20 @@ test("captures through DevTools with lifecycle and selector waits", async () =>
});
});
-test("captures full page through DevTools layout metrics", async () => {
+test("captures full page and returns DevTools layout metrics", async () => {
const browserProcess = new FakeBrowserProcess();
const socket = new FakeWebSocket();
const dependencies = createDependencies({ browserProcess, socket });
- await captureBrowserScreenshot(
+ const layout = await captureBrowserScreenshot(
{
url: "https://example.com",
output: "/tmp/full-page.png",
width: 800,
height: 600,
fullPage: true,
+ includeImageMetrics: true,
+ includeResourceMetrics: true,
browserPath: "/usr/bin/chromium",
uid: 1000,
waitUntil: "networkidle",
@@ -279,6 +343,45 @@ test("captures full page through DevTools layout metrics", async () => {
dependencies
);
+ expect(layout).toEqual({
+ viewportWidth: 800,
+ viewportHeight: 600,
+ contentWidth: 813,
+ contentHeight: 2346,
+ horizontalOverflow: true,
+ images: [
+ {
+ instanceId: "hero-image",
+ loading: "eager",
+ complete: true,
+ naturalWidth: 2400,
+ naturalHeight: 1600,
+ renderedWidth: 600,
+ renderedHeight: 400,
+ top: 1000,
+ },
+ ],
+ resources: [
+ {
+ pathname: "/styles.css",
+ initiatorType: "link",
+ transferSize: 12000,
+ encodedBodySize: 11000,
+ decodedBodySize: 40000,
+ duration: 25,
+ renderBlockingStatus: "blocking",
+ },
+ {
+ pathname: "/fonts/brand.ttf",
+ initiatorType: "css",
+ transferSize: 80000,
+ encodedBodySize: 79000,
+ decodedBodySize: 79000,
+ duration: 40,
+ },
+ ],
+ });
+
expect(socket.sentMethods).toEqual(
expect.arrayContaining(["Page.getLayoutMetrics", "Page.captureScreenshot"])
);
diff --git a/packages/cli/src/screenshot-browser-cdp.ts b/packages/cli/src/screenshot-browser-cdp.ts
index 5e5499ee2a..a656f13877 100644
--- a/packages/cli/src/screenshot-browser-cdp.ts
+++ b/packages/cli/src/screenshot-browser-cdp.ts
@@ -13,6 +13,8 @@ export type BrowserScreenshotOptions = {
width: number;
height: number;
fullPage?: boolean;
+ includeImageMetrics?: boolean;
+ includeResourceMetrics?: boolean;
url: string;
uid?: number;
waitUntil: ScreenshotWaitUntil;
@@ -218,27 +220,17 @@ const getPageWebSocketUrl = async ({
dependencies: BrowserScreenshotDependencies;
timeout: number;
}) => {
- await withDeadline(
- dependencies.fetch(`http://127.0.0.1:${port}/json/new?about:blank`, {
- method: "PUT",
- }),
- "Browser page target could not be created",
- timeout
- );
- const targets = (await withDeadline(
+ const target = (await withDeadline(
dependencies
- .fetch(`http://127.0.0.1:${port}/json/list`)
+ .fetch(`http://127.0.0.1:${port}/json/new?about:blank`, {
+ method: "PUT",
+ })
.then((response) => response.json()),
- "Browser targets were not available",
+ "Browser page target could not be created",
timeout
- )) as Array<{ type?: string; webSocketDebuggerUrl?: string }>;
- const target = targets.find(
- (candidate) =>
- candidate.type === "page" &&
- typeof candidate.webSocketDebuggerUrl === "string"
- );
+ )) as { webSocketDebuggerUrl?: string };
if (target?.webSocketDebuggerUrl === undefined) {
- throw new Error("Browser did not expose a page target.");
+ throw new Error("Browser did not expose the created page target.");
}
return target.webSocketDebuggerUrl;
};
@@ -337,14 +329,206 @@ const createBrowserLaunchArgs = ({
"about:blank",
];
-const getScreenshotCaptureParams = async ({
- send,
- fullPage,
-}: {
+type BrowserLayoutMetricsResponse = {
+ cssContentSize?: {
+ x?: number;
+ y?: number;
+ width?: number;
+ height?: number;
+ };
+ cssLayoutViewport?: {
+ clientWidth?: number;
+ clientHeight?: number;
+ };
+};
+
+export type BrowserScreenshotLayout = {
+ viewportWidth: number;
+ viewportHeight: number;
+ contentWidth: number;
+ contentHeight: number;
+ horizontalOverflow: boolean;
+ images?: BrowserScreenshotImage[];
+ resources?: BrowserScreenshotResource[];
+};
+
+export type BrowserScreenshotImage = {
+ instanceId?: string;
+ loading: string;
+ complete: boolean;
+ naturalWidth: number;
+ naturalHeight: number;
+ renderedWidth: number;
+ renderedHeight: number;
+ top: number;
+};
+
+export type BrowserScreenshotResource = {
+ pathname: string;
+ initiatorType: string;
+ transferSize: number;
+ encodedBodySize: number;
+ decodedBodySize: number;
+ duration: number;
+ renderBlockingStatus?: string;
+};
+
+const getBrowserScreenshotResources = async (
+ send: <Result = unknown>(
+ method: string,
+ params?: Record<string, unknown>
+ ) => Promise<Result>
+): Promise<BrowserScreenshotResource[]> => {
+ const response = await send<{
+ result?: { value?: unknown };
+ }>("Runtime.evaluate", {
+ expression: `performance.getEntriesByType("resource").map((entry) => {
+ let pathname = "";
+ try { pathname = new URL(entry.name).pathname; } catch {}
+ return {
+ pathname,
+ initiatorType: entry.initiatorType || "other",
+ transferSize: entry.transferSize || 0,
+ encodedBodySize: entry.encodedBodySize || 0,
+ decodedBodySize: entry.decodedBodySize || 0,
+ duration: entry.duration || 0,
+ renderBlockingStatus: entry.renderBlockingStatus || undefined,
+ };
+ })`,
+ returnByValue: true,
+ });
+ if (Array.isArray(response.result?.value) === false) {
+ return [];
+ }
+ return response.result.value.flatMap((value) => {
+ if (typeof value !== "object" || value === null) {
+ return [];
+ }
+ const resource = value as Record<string, unknown>;
+ if (
+ typeof resource.pathname !== "string" ||
+ typeof resource.initiatorType !== "string" ||
+ typeof resource.transferSize !== "number" ||
+ typeof resource.encodedBodySize !== "number" ||
+ typeof resource.decodedBodySize !== "number" ||
+ typeof resource.duration !== "number"
+ ) {
+ return [];
+ }
+ return [
+ {
+ pathname: resource.pathname,
+ initiatorType: resource.initiatorType,
+ transferSize: resource.transferSize,
+ encodedBodySize: resource.encodedBodySize,
+ decodedBodySize: resource.decodedBodySize,
+ duration: resource.duration,
+ ...(typeof resource.renderBlockingStatus === "string"
+ ? { renderBlockingStatus: resource.renderBlockingStatus }
+ : {}),
+ },
+ ];
+ });
+};
+
+const getBrowserScreenshotImages = async (
send: <Result = unknown>(
method: string,
params?: Record<string, unknown>
- ) => Promise<Result>;
+ ) => Promise<Result>
+): Promise<BrowserScreenshotImage[]> => {
+ const response = await send<{
+ result?: { value?: unknown };
+ }>("Runtime.evaluate", {
+ expression: `Array.from(document.images, (image) => {
+ const rect = image.getBoundingClientRect();
+ return {
+ instanceId: image.getAttribute("data-ws-id") || undefined,
+ loading: image.loading || "eager",
+ complete: image.complete,
+ naturalWidth: image.naturalWidth,
+ naturalHeight: image.naturalHeight,
+ renderedWidth: rect.width,
+ renderedHeight: rect.height,
+ top: rect.top + window.scrollY,
+ };
+ })`,
+ returnByValue: true,
+ });
+ if (Array.isArray(response.result?.value) === false) {
+ return [];
+ }
+ return response.result.value.flatMap((value) => {
+ if (typeof value !== "object" || value === null) {
+ return [];
+ }
+ const image = value as Record<string, unknown>;
+ if (
+ typeof image.loading !== "string" ||
+ typeof image.complete !== "boolean" ||
+ typeof image.naturalWidth !== "number" ||
+ typeof image.naturalHeight !== "number" ||
+ typeof image.renderedWidth !== "number" ||
+ typeof image.renderedHeight !== "number" ||
+ typeof image.top !== "number"
+ ) {
+ return [];
+ }
+ return [
+ {
+ ...(typeof image.instanceId === "string"
+ ? { instanceId: image.instanceId }
+ : {}),
+ loading: image.loading,
+ complete: image.complete,
+ naturalWidth: image.naturalWidth,
+ naturalHeight: image.naturalHeight,
+ renderedWidth: image.renderedWidth,
+ renderedHeight: image.renderedHeight,
+ top: image.top,
+ },
+ ];
+ });
+};
+
+const getBrowserScreenshotLayout = (
+ metrics: BrowserLayoutMetricsResponse,
+ viewport: { width: number; height: number },
+ images: BrowserScreenshotImage[],
+ resources: BrowserScreenshotResource[]
+): BrowserScreenshotLayout => {
+ const contentWidth = metrics.cssContentSize?.width;
+ const contentHeight = metrics.cssContentSize?.height;
+ const viewportWidth =
+ metrics.cssLayoutViewport?.clientWidth ?? viewport.width;
+ const viewportHeight =
+ metrics.cssLayoutViewport?.clientHeight ?? viewport.height;
+ if (
+ typeof contentWidth !== "number" ||
+ typeof contentHeight !== "number" ||
+ contentWidth <= 0 ||
+ contentHeight <= 0 ||
+ viewportWidth <= 0 ||
+ viewportHeight <= 0
+ ) {
+ throw new Error("Browser did not report valid page layout metrics.");
+ }
+ return {
+ viewportWidth: Math.round(viewportWidth),
+ viewportHeight: Math.round(viewportHeight),
+ contentWidth: Math.ceil(contentWidth),
+ contentHeight: Math.ceil(contentHeight),
+ horizontalOverflow: contentWidth > viewportWidth + 1,
+ images,
+ resources,
+ };
+};
+
+const getScreenshotCaptureParams = async ({
+ metrics,
+ fullPage,
+}: {
+ metrics: BrowserLayoutMetricsResponse;
fullPage?: boolean;
}) => {
if (fullPage !== true) {
@@ -353,14 +537,6 @@ const getScreenshotCaptureParams = async ({
captureBeyondViewport: false,
};
}
- const metrics = await send<{
- cssContentSize?: {
- x?: number;
- y?: number;
- width?: number;
- height?: number;
- };
- }>("Page.getLayoutMetrics");
const { x = 0, y = 0, width, height } = metrics.cssContentSize ?? {};
if (
typeof width !== "number" ||
@@ -404,6 +580,7 @@ export const captureBrowserScreenshot = async (
browserProcess.once("error", () => resolveClosed());
});
let cdp: CdpSession | undefined;
+ let layout: BrowserScreenshotLayout | undefined;
try {
await Promise.race([
new Promise<never>((_, reject) => {
@@ -474,8 +651,34 @@ export const captureBrowserScreenshot = async (
if (options.waitForTimeout > 0) {
await delay(options.waitForTimeout);
}
+ const metrics = await send<BrowserLayoutMetricsResponse>(
+ "Page.getLayoutMetrics"
+ );
+ const images =
+ options.includeImageMetrics === true
+ ? await getBrowserScreenshotImages(send)
+ : undefined;
+ const resources =
+ options.includeResourceMetrics === true
+ ? await getBrowserScreenshotResources(send)
+ : undefined;
+ layout = getBrowserScreenshotLayout(
+ metrics,
+ {
+ width: options.width,
+ height: options.height,
+ },
+ images ?? [],
+ resources ?? []
+ );
+ if (images === undefined) {
+ delete layout.images;
+ }
+ if (resources === undefined) {
+ delete layout.resources;
+ }
const captureParams = await getScreenshotCaptureParams({
- send,
+ metrics,
fullPage: options.fullPage,
});
const screenshot = await send<{ data: string }>(
@@ -498,4 +701,8 @@ export const captureBrowserScreenshot = async (
).catch(() => undefined);
await dependencies.rm(userDataDir, { recursive: true, force: true });
}
+ if (layout === undefined) {
+ throw new Error("Browser did not report page layout metrics.");
+ }
+ return layout;
};
diff --git a/packages/cli/src/screenshot.test.ts b/packages/cli/src/screenshot.test.ts
index 97ddd02697..9aa5fa7941 100644
--- a/packages/cli/src/screenshot.test.ts
+++ b/packages/cli/src/screenshot.test.ts
@@ -224,7 +224,15 @@ test("formats actionable browser installation guidance", () => {
describe("captureScreenshot", () => {
test("captures with browser readiness defaults", async () => {
- const captureBrowserScreenshot = vi.fn(async () => undefined);
+ const captureBrowserScreenshot = vi.fn(async () => ({
+ viewportWidth: 1440,
+ viewportHeight: 900,
+ contentWidth: 1440,
+ contentHeight: 1200,
+ horizontalOverflow: false,
+ images: [],
+ resources: [],
+ }));
const output = `${tmpdir()}/webstudio-screenshot-123.png`;
const dependencies = createDependencies({
which: vi.fn(async (command) =>
@@ -250,6 +258,15 @@ describe("captureScreenshot", () => {
fullPage: false,
elapsedMs: 0,
warnings: [],
+ layout: {
+ viewportWidth: 1440,
+ viewportHeight: 900,
+ contentWidth: 1440,
+ contentHeight: 1200,
+ horizontalOverflow: false,
+ images: [],
+ resources: [],
+ },
});
expect(captureBrowserScreenshot).toHaveBeenCalledWith({
browserPath: "/usr/bin/chromium",
@@ -257,6 +274,8 @@ describe("captureScreenshot", () => {
width: 1440,
height: 900,
fullPage: undefined,
+ includeImageMetrics: undefined,
+ includeResourceMetrics: undefined,
url: "https://example.com",
uid: 1000,
waitUntil: "load",
diff --git a/packages/cli/src/screenshot.ts b/packages/cli/src/screenshot.ts
index 2d76e84bf0..7afc5cdeee 100644
--- a/packages/cli/src/screenshot.ts
+++ b/packages/cli/src/screenshot.ts
@@ -16,6 +16,7 @@ import {
captureBrowserScreenshot,
defaultBrowserScreenshotDependencies,
type BrowserScreenshotDependencies,
+ type BrowserScreenshotLayout,
type BrowserScreenshotOptions,
} from "./screenshot-browser-cdp";
@@ -54,7 +55,7 @@ export type ScreenshotDependencies = {
} & BrowserScreenshotDependencies & {
captureBrowserScreenshot?: (
options: BrowserScreenshotOptions
- ) => Promise<void>;
+ ) => Promise<BrowserScreenshotLayout | undefined>;
installCommand: (file: string, args: readonly string[]) => Promise<void>;
getuid: () => number | undefined;
now: () => number;
@@ -497,6 +498,8 @@ export const captureScreenshot = async (
width: number;
height: number;
fullPage?: boolean;
+ includeImageMetrics?: boolean;
+ includeResourceMetrics?: boolean;
browser: ScreenshotBrowser;
browserPath?: string;
waitUntil?: ScreenshotWaitUntil;
@@ -519,6 +522,8 @@ export const captureScreenshot = async (
width: options.width,
height: options.height,
fullPage: options.fullPage,
+ includeImageMetrics: options.includeImageMetrics,
+ includeResourceMetrics: options.includeResourceMetrics,
url: options.url,
uid: dependencies.getuid(),
waitUntil: options.waitUntil ?? defaultScreenshotWaitUntil,
@@ -526,11 +531,10 @@ export const captureScreenshot = async (
waitForTimeout: options.waitForTimeout ?? defaultScreenshotWaitForTimeout,
timeout: options.timeout ?? defaultScreenshotTimeout,
};
- if (dependencies.captureBrowserScreenshot !== undefined) {
- await dependencies.captureBrowserScreenshot(browserScreenshotOptions);
- } else {
- await captureBrowserScreenshot(browserScreenshotOptions, dependencies);
- }
+ const layout =
+ dependencies.captureBrowserScreenshot !== undefined
+ ? await dependencies.captureBrowserScreenshot(browserScreenshotOptions)
+ : await captureBrowserScreenshot(browserScreenshotOptions, dependencies);
return {
output,
browser,
@@ -541,6 +545,7 @@ export const captureScreenshot = async (
fullPage: options.fullPage === true,
elapsedMs: dependencies.now() - startedAt,
warnings: [] as string[],
+ ...(layout === undefined ? {} : { layout }),
};
};
@@ -551,6 +556,8 @@ export const captureScreenshotWithBrowserInstall = async (
width: number;
height: number;
fullPage?: boolean;
+ includeImageMetrics?: boolean;
+ includeResourceMetrics?: boolean;
browser: ScreenshotBrowser;
browserPath?: string;
waitUntil?: ScreenshotWaitUntil;
diff --git a/packages/cli/vite.config.ts b/packages/cli/vite.config.ts
index 5926d7b68f..9ea26a694c 100644
--- a/packages/cli/vite.config.ts
+++ b/packages/cli/vite.config.ts
@@ -25,7 +25,7 @@ const getPackageName = (id: string) => {
return id.split("/")[0];
};
-const isExternal = (id: string) => {
+export const isExternal = (id: string) => {
const packageName = getPackageName(id);
return (
id.startsWith("node:") ||
diff --git a/packages/domain/src/project-domain-api.server.test.ts b/packages/domain/src/project-domain-api.server.test.ts
index 407c6e0ebc..5c6b86e902 100644
--- a/packages/domain/src/project-domain-api.server.test.ts
+++ b/packages/domain/src/project-domain-api.server.test.ts
@@ -104,6 +104,7 @@ const devBuildRow = {
]),
deployment: null,
marketplaceProduct: JSON.stringify({}),
+ projectSettings: JSON.stringify({ meta: {}, compiler: {} }),
};
const devBuildHandler = (row: typeof devBuildRow = devBuildRow) =>
diff --git a/packages/html-data/src/index.ts b/packages/html-data/src/index.ts
index abd0c7bb38..0a0d396c6b 100644
--- a/packages/html-data/src/index.ts
+++ b/packages/html-data/src/index.ts
@@ -2,3 +2,4 @@ export * from "./__generated__/elements";
export * from "./__generated__/attributes";
export * from "./__generated__/aria";
export * from "./pseudo-classes";
+export { roles as ariaRoles } from "aria-query";
diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.ts
index d742f97a8b..45e2952197 100644
--- a/packages/http-client/src/index.test.ts
+++ b/packages/http-client/src/index.test.ts
@@ -175,6 +175,23 @@ test("reports non-json api responses", async () => {
expect(message).toContain("The request may be too large for the API.");
});
+test("sends the bundle contract when loading by project id", async () => {
+ const project = createPublishedProjectBundleFixture();
+ const fetch = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify([{ result: { data: project } }]), {
+ headers: { "content-type": "application/json" },
+ })
+ );
+ vi.stubGlobal("fetch", fetch);
+
+ await loadProjectBundleByProjectId(apiParams);
+
+ const [url] = fetch.mock.calls[0] as [RequestInfo | URL, RequestInit];
+ expect(decodeURIComponent(String(url))).toContain(
+ `"bundleVersion":"${bundleVersion}"`
+ );
+});
+
test("creates api client compatibility headers", () => {
expect(createApiClientHeaders({ name: "cli", version: "1.2.3" })).toEqual({
"x-webstudio-client": "cli",
@@ -1058,7 +1075,10 @@ test("loads project bundle by build id without auth headers", async () => {
});
expect(fetch).toHaveBeenCalledOnce();
- const [_url, init] = fetch.mock.calls[0] as [URL, RequestInit];
+ const [url, init] = fetch.mock.calls[0] as [RequestInfo | URL, RequestInit];
+ expect(decodeURIComponent(String(url))).toContain(
+ `"bundleVersion":"${bundleVersion}"`
+ );
expect(init.headers).toMatchObject({
"content-type": "application/json",
});
diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.ts
index c73a363912..95cd605df2 100644
--- a/packages/http-client/src/index.ts
+++ b/packages/http-client/src/index.ts
@@ -579,6 +579,7 @@ export const loadProjectBundleByBuildId = async (
...headers,
}).query("build.loadProjectBundleByBuildId", {
buildId: params.buildId,
+ bundleVersion: currentBundleVersion,
});
return publishedProjectBundle.parse(data);
};
@@ -590,6 +591,7 @@ export const loadProjectBundleByProjectId = async (
"build.loadProjectBundleByProjectId",
{
projectId: params.projectId,
+ bundleVersion: currentBundleVersion,
}
);
return publishedProjectBundle.parse(data);
@@ -1046,6 +1048,34 @@ export const deleteFolder = projectMutationInput<
}
>("delete-folder");
+export const searchProject = projectQueryInput<
+ AuthProjectParams & Record<string, unknown>
+>("search-project");
+
+export const audit = projectQueryInput<
+ AuthProjectParams & Record<string, unknown>
+>("audit");
+
+export const listFonts = projectQueryInput<
+ AuthProjectParams & Record<string, unknown>
+>("list-fonts");
+
+export const replacePropText = projectMutationInput<
+ AuthProjectParams & Record<string, unknown>
+>("replace-prop-text");
+
+export const replaceText = projectMutationInput<
+ AuthProjectParams & Record<string, unknown>
+>("replace-text");
+
+export const replaceResourceText = projectMutationInput<
+ AuthProjectParams & Record<string, unknown>
+>("replace-resource-text");
+
+export const setImageDescriptions = projectMutationInput<
+ AuthProjectParams & Record<string, unknown>
+>("set-image-descriptions");
+
export const listInstances = projectQueryInput<
AuthProjectParams & {
pageId?: string;
diff --git a/packages/icons/icons/json-ld.svg b/packages/icons/icons/json-ld.svg
new file mode 100644
index 0000000000..d2f80ec037
--- /dev/null
+++ b/packages/icons/icons/json-ld.svg
@@ -0,0 +1,29 @@
+<svg
+ width="16"
+ height="16"
+ viewBox="0 0 16 16"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+>
+ <path
+ d="M4.75 2.25H4.25C3.56 2.25 3 2.81 3 3.5V6.25C3 7.22 2.22 8 1.25 8C2.22 8 3 8.78 3 9.75V12.5C3 13.19 3.56 13.75 4.25 13.75H4.75"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M11.25 2.25H11.75C12.44 2.25 13 2.81 13 3.5V6.25C13 7.22 13.78 8 14.75 8C13.78 8 13 8.78 13 9.75V12.5C13 13.19 12.44 13.75 11.75 13.75H11.25"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M8 5.25L6.25 9.75M8 5.25L9.75 9.75M6.25 9.75H9.75"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <circle cx="8" cy="5.25" r="1" fill="currentColor" />
+ <circle cx="6.25" cy="9.75" r="1" fill="currentColor" />
+ <circle cx="9.75" cy="9.75" r="1" fill="currentColor" />
+</svg>
diff --git a/packages/icons/src/__generated__/components.tsx b/packages/icons/src/__generated__/components.tsx
index 74b895fd10..3119bb717e 100644
--- a/packages/icons/src/__generated__/components.tsx
+++ b/packages/icons/src/__generated__/components.tsx
@@ -3333,6 +3333,33 @@ export const JCSpaceBetweenIcon: IconComponent = forwardRef(
);
JCSpaceBetweenIcon.displayName = "JCSpaceBetweenIcon";
+export const JsonLdIcon: IconComponent = forwardRef(
+ ({ fill = "none", size = 16, ...props }, forwardedRef) => {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 16 16"
+ width={size}
+ height={size}
+ fill={fill}
+ {...props}
+ ref={forwardedRef}
+ >
+ <path
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ d="M4.75 2.25h-.5C3.56 2.25 3 2.81 3 3.5v2.75C3 7.22 2.22 8 1.25 8 2.22 8 3 8.78 3 9.75v2.75c0 .69.56 1.25 1.25 1.25h.5M11.25 2.25h.5c.69 0 1.25.56 1.25 1.25v2.75c0 .97.78 1.75 1.75 1.75-.97 0-1.75.78-1.75 1.75v2.75c0 .69-.56 1.25-1.25 1.25h-.5M8 5.25l-1.75 4.5M8 5.25l1.75 4.5m-3.5 0h3.5"
+ />
+ <circle cx="8" cy="5.25" r="1" fill="currentColor" />
+ <circle cx="6.25" cy="9.75" r="1" fill="currentColor" />
+ <circle cx="9.75" cy="9.75" r="1" fill="currentColor" />
+ </svg>
+ );
+ }
+);
+JsonLdIcon.displayName = "JsonLdIcon";
+
export const LabelIcon: IconComponent = forwardRef(
({ fill = "none", size = 16, ...props }, forwardedRef) => {
return (
diff --git a/packages/icons/src/__generated__/svg.ts b/packages/icons/src/__generated__/svg.ts
index 4f369bd0b1..b585241411 100644
--- a/packages/icons/src/__generated__/svg.ts
+++ b/packages/icons/src/__generated__/svg.ts
@@ -248,6 +248,8 @@ export const JCSpaceAroundIcon = `<svg xmlns="http://www.w3.org/2000/svg" viewBo
export const JCSpaceBetweenIcon = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" width="100%" height="100%" style="display: block;"><path fill-rule="evenodd" d="M2.2 1.5c.442 0 .8.344.8.768v11.464c0 .424-.358.768-.8.768-.442 0-.8-.344-.8-.768V2.268c0-.424.358-.768.8-.768Z" clip-rule="evenodd"/><path d="M4 4.8a.8.8 0 0 1 .8-.8h1.4a.8.8 0 0 1 .8.8v6.4a.8.8 0 0 1-.8.8H4.8a.8.8 0 0 1-.8-.8V4.8ZM9 4.8a.8.8 0 0 1 .8-.8h1.4a.8.8 0 0 1 .8.8v6.4a.8.8 0 0 1-.8.8H9.8a.8.8 0 0 1-.8-.8V4.8Z"/><path fill-rule="evenodd" d="M13.8 1.5c.442 0 .8.344.8.768v11.464c0 .424-.358.768-.8.768-.442 0-.8-.344-.8-.768V2.268c0-.424.358-.768.8-.768Z" clip-rule="evenodd"/></svg>`;
+export const JsonLdIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M4.75 2.25h-.5C3.56 2.25 3 2.81 3 3.5v2.75C3 7.22 2.22 8 1.25 8 2.22 8 3 8.78 3 9.75v2.75c0 .69.56 1.25 1.25 1.25h.5M11.25 2.25h.5c.69 0 1.25.56 1.25 1.25v2.75c0 .97.78 1.75 1.75 1.75-.97 0-1.75.78-1.75 1.75v2.75c0 .69-.56 1.25-1.25 1.25h-.5M8 5.25l-1.75 4.5M8 5.25l1.75 4.5m-3.5 0h3.5"/><circle cx="8" cy="5.25" r="1" fill="currentColor"/><circle cx="6.25" cy="9.75" r="1" fill="currentColor"/><circle cx="9.75" cy="9.75" r="1" fill="currentColor"/></svg>`;
+
export const LabelIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M12.667 2H3.333C2.597 2 2 2.597 2 3.333v9.334C2 13.403 2.597 14 3.333 14h9.334c.736 0 1.333-.597 1.333-1.333V3.333C14 2.597 13.403 2 12.667 2Z"/><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M6.476 11.074V4.926m0 6.148h3.77v-.615m-3.77.615h-.722m.722-6.148h.632m-.632 0h-.722"/></svg>`;
export const LargeXIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M12.5 3 3 12.5M3 3l9.5 9.5"/></svg>`;
diff --git a/packages/postgrest/src/__generated__/db-types.ts b/packages/postgrest/src/__generated__/db-types.ts
index 0b312bf3a2..7e242e3b8f 100644
--- a/packages/postgrest/src/__generated__/db-types.ts
+++ b/packages/postgrest/src/__generated__/db-types.ts
@@ -162,6 +162,7 @@ export type Database = {
lastTransactionId: string | null;
marketplaceProduct: string;
pages: string;
+ projectSettings: string;
projectId: string;
props: string;
publishStatus: Database["public"]["Enums"]["PublishStatus"];
@@ -183,6 +184,7 @@ export type Database = {
lastTransactionId?: string | null;
marketplaceProduct?: string;
pages: string;
+ projectSettings?: string;
projectId: string;
props?: string;
publishStatus?: Database["public"]["Enums"]["PublishStatus"];
@@ -204,6 +206,7 @@ export type Database = {
lastTransactionId?: string | null;
marketplaceProduct?: string;
pages?: string;
+ projectSettings?: string;
projectId?: string;
props?: string;
publishStatus?: Database["public"]["Enums"]["PublishStatus"];
diff --git a/packages/prisma-client/prisma/migrations/20260712000000_project_settings/migration.sql b/packages/prisma-client/prisma/migrations/20260712000000_project_settings/migration.sql
new file mode 100644
index 0000000000..d23c15aadd
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20260712000000_project_settings/migration.sql
@@ -0,0 +1,126 @@
+ALTER TABLE "Build"
+ADD COLUMN "projectSettings" TEXT;
+
+UPDATE "Build"
+SET "projectSettings" = json_build_object(
+ 'meta', COALESCE(pages::json->'meta', '{}'::json),
+ 'compiler', COALESCE(pages::json->'compiler', '{}'::json)
+)::text;
+
+ALTER TABLE "Build"
+ALTER COLUMN "projectSettings" SET DEFAULT '{"meta":{},"compiler":{}}',
+ALTER COLUMN "projectSettings" SET NOT NULL;
+
+CREATE OR REPLACE FUNCTION create_production_build(
+ project_id text,
+ deployment text
+) RETURNS text AS $$
+DECLARE
+ new_build_id text;
+BEGIN
+ INSERT INTO "Build" (
+ version,
+ "lastTransactionId",
+ pages,
+ breakpoints,
+ styles,
+ "styleSources",
+ "styleSourceSelections",
+ props,
+ "dataSources",
+ resources,
+ instances,
+ "marketplaceProduct",
+ "projectSettings",
+ "publishStatus",
+ "projectId",
+ id,
+ deployment
+ )
+ SELECT
+ version,
+ "lastTransactionId",
+ pages,
+ breakpoints,
+ styles,
+ "styleSources",
+ "styleSourceSelections",
+ props,
+ "dataSources",
+ resources,
+ instances,
+ "marketplaceProduct",
+ "projectSettings",
+ "publishStatus",
+ "projectId",
+ extensions.uuid_generate_v4(),
+ create_production_build.deployment
+ FROM "Build"
+ WHERE "projectId" = project_id AND "Build".deployment IS NULL
+ RETURNING id INTO new_build_id;
+
+ RETURN new_build_id;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE OR REPLACE FUNCTION database_cleanup(
+ from_date timestamp DEFAULT '2020-01-01 00:00:00',
+ to_date timestamp DEFAULT '2099-12-31 23:59:59'
+) RETURNS void AS $$
+BEGIN
+ WITH latest_builds AS (
+ SELECT "buildId" FROM "Project" p, LATERAL "latestProjectDomainBuildVirtual"(p)
+ UNION
+ SELECT "buildId" FROM "Project" p, LATERAL "latestBuildVirtual"(p)
+ UNION
+ SELECT lb."buildId"
+ FROM "Project" p, LATERAL "domainsVirtual"(p) dv, LATERAL "latestBuildVirtual"(dv) lb
+ )
+ UPDATE "Build"
+ SET
+ "styleSources" = '[]',
+ styles = '[]',
+ breakpoints = '[]',
+ "styleSourceSelections" = '[]',
+ props = '[]',
+ instances = '[]',
+ "dataSources" = '[]',
+ resources = '[]',
+ "marketplaceProduct" = '{}',
+ "projectSettings" = '{"meta":{},"compiler":{}}',
+ "isCleaned" = true
+ WHERE deployment IS NOT NULL
+ AND id NOT IN (SELECT "buildId" FROM latest_builds)
+ AND "isCleaned" = false
+ AND "createdAt" BETWEEN from_date AND to_date;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE OR REPLACE FUNCTION restore_development_build(
+ project_id text,
+ from_build_id text
+) RETURNS text AS $$
+BEGIN
+ UPDATE "Build"
+ SET
+ version = source.version,
+ "lastTransactionId" = source."lastTransactionId",
+ pages = source.pages,
+ breakpoints = source.breakpoints,
+ styles = source.styles,
+ "styleSources" = source."styleSources",
+ "styleSourceSelections" = source."styleSourceSelections",
+ props = source.props,
+ "dataSources" = source."dataSources",
+ resources = source.resources,
+ instances = source.instances,
+ "marketplaceProduct" = source."marketplaceProduct",
+ "projectSettings" = source."projectSettings"
+ FROM (
+ SELECT * FROM "Build"
+ WHERE "projectId" = project_id AND id = from_build_id
+ ) AS source
+ WHERE "Build"."projectId" = project_id AND "Build".deployment IS NULL;
+ RETURN 'OK';
+END;
+$$ LANGUAGE plpgsql;
diff --git a/packages/prisma-client/prisma/schema.prisma b/packages/prisma-client/prisma/schema.prisma
index de56a12022..cc7b9579c6 100644
--- a/packages/prisma-client/prisma/schema.prisma
+++ b/packages/prisma-client/prisma/schema.prisma
@@ -197,6 +197,7 @@ model Build {
resources String @default("[]")
instances String @default("[]")
marketplaceProduct String @default("{}")
+ projectSettings String @default("{\"meta\":{},\"compiler\":{}}")
deployment String?
publishStatus PublishStatus @default(PENDING)
diff --git a/packages/project-build/package.json b/packages/project-build/package.json
index c7888d9df4..78e8d042ba 100644
--- a/packages/project-build/package.json
+++ b/packages/project-build/package.json
@@ -17,6 +17,11 @@
"import": "./src/schema.ts",
"default": "./src/schema.ts"
},
+ "./shared/project-settings": {
+ "webstudio": "./src/shared/project-settings.ts",
+ "import": "./src/shared/project-settings.ts",
+ "default": "./src/shared/project-settings.ts"
+ },
"./contracts/builder-runtime": {
"webstudio": "./src/contracts/builder-runtime.ts",
"import": "./src/contracts/builder-runtime.ts",
@@ -333,6 +338,7 @@
"@webstudio-is/authorization-token": "workspace:*",
"@webstudio-is/css-data": "workspace:*",
"@webstudio-is/css-engine": "workspace:*",
+ "@webstudio-is/fonts": "workspace:*",
"@webstudio-is/html-data": "workspace:*",
"@webstudio-is/postgrest": "workspace:*",
"@webstudio-is/project": "workspace:*",
diff --git a/packages/project-build/scripts/generate-runtime-operation-contracts.ts b/packages/project-build/scripts/generate-runtime-operation-contracts.ts
index 02ac111170..c198391723 100644
--- a/packages/project-build/scripts/generate-runtime-operation-contracts.ts
+++ b/packages/project-build/scripts/generate-runtime-operation-contracts.ts
@@ -18,6 +18,7 @@ const contractData = builderRuntimeOperations.map(
permit,
kind,
inputJsonSchema,
+ outputJsonSchema,
readNamespaces,
writeNamespaces,
invalidatesNamespaces,
@@ -31,6 +32,9 @@ const contractData = builderRuntimeOperations.map(
permit,
kind,
inputSchema: inputJsonSchema,
+ ...(outputJsonSchema === undefined
+ ? {}
+ : { outputSchema: outputJsonSchema }),
readNamespaces,
writeNamespaces,
invalidatesNamespaces,
diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
index cb91a1f014..522f266622 100644
--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
@@ -16,7 +16,7 @@ export const runtimeOperationContractData = [
},
required: [],
},
- readNamespaces: ["pages"],
+ readNamespaces: ["pages", "projectSettings"],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
@@ -78,7 +78,7 @@ export const runtimeOperationContractData = [
},
title: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
parentFolderId: {
@@ -89,22 +89,22 @@ export const runtimeOperationContractData = [
properties: {
description: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
language: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
redirect: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
socialImageUrl: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
socialImageAssetId: {
@@ -117,7 +117,7 @@ export const runtimeOperationContractData = [
},
{
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
],
@@ -128,12 +128,12 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
status: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
auth: {
@@ -182,7 +182,7 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
},
@@ -232,7 +232,7 @@ export const runtimeOperationContractData = [
},
title: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
parentFolderId: {
@@ -243,22 +243,22 @@ export const runtimeOperationContractData = [
properties: {
description: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
language: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
redirect: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
socialImageUrl: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
socialImageAssetId: {
@@ -271,7 +271,7 @@ export const runtimeOperationContractData = [
},
{
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
],
@@ -282,12 +282,12 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
status: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
auth: {
@@ -336,7 +336,7 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
},
@@ -1157,7 +1157,7 @@ export const runtimeOperationContractData = [
},
title: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
meta: {
@@ -1165,22 +1165,22 @@ export const runtimeOperationContractData = [
properties: {
description: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
language: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
redirect: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
socialImageUrl: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
socialImageAssetId: {
@@ -1193,7 +1193,7 @@ export const runtimeOperationContractData = [
},
{
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
],
@@ -1204,12 +1204,12 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
status: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
auth: {
@@ -1258,7 +1258,7 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
},
@@ -1330,7 +1330,7 @@ export const runtimeOperationContractData = [
},
title: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
meta: {
@@ -1338,22 +1338,22 @@ export const runtimeOperationContractData = [
properties: {
description: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
language: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
redirect: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
socialImageUrl: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
socialImageAssetId: {
@@ -1366,7 +1366,7 @@ export const runtimeOperationContractData = [
},
{
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
],
@@ -1377,12 +1377,12 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
status: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
auth: {
@@ -1431,7 +1431,7 @@ export const runtimeOperationContractData = [
},
content: {
description:
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.',
type: "string",
},
},
@@ -23886,7 +23886,14 @@ export const runtimeOperationContractData = [
type: "array",
items: {
type: "string",
- enum: ["props", "styles", "bindings", "children", "sources"],
+ enum: [
+ "props",
+ "styles",
+ "bindings",
+ "children",
+ "sources",
+ "ancestors",
+ ],
},
},
childDepth: {
@@ -23908,6 +23915,1277 @@ export const runtimeOperationContractData = [
invalidatesNamespaces: [],
retryOnConflict: false,
},
+ {
+ id: "project.search",
+ command: "search-project",
+ client: "searchProject",
+ kind: "read",
+ inputSchema: {
+ type: "object",
+ properties: {
+ query: {
+ type: "string",
+ minLength: 1,
+ },
+ scopes: {
+ minItems: 1,
+ type: "array",
+ items: {
+ type: "string",
+ enum: [
+ "instances",
+ "text",
+ "props",
+ "resources",
+ "assets",
+ "styles",
+ ],
+ },
+ },
+ pageId: {
+ type: "string",
+ },
+ pagePath: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ },
+ required: ["query"],
+ additionalProperties: false,
+ },
+ readNamespaces: [
+ "pages",
+ "projectSettings",
+ "instances",
+ "props",
+ "styles",
+ "styleSources",
+ "styleSourceSelections",
+ "resources",
+ "dataSources",
+ "assets",
+ "breakpoints",
+ ],
+ writeNamespaces: [],
+ invalidatesNamespaces: [],
+ retryOnConflict: false,
+ requiresAssets: true,
+ },
+ {
+ id: "project.audit",
+ command: "audit",
+ client: "audit",
+ kind: "read",
+ inputSchema: {
+ type: "object",
+ properties: {
+ scopes: {
+ description:
+ "Audit scopes. Omit to run all scopes. accessibility errors: missing-alt, missing-image-input-alt, missing-iframe-title, missing-accessible-name, missing-form-label, invalid-aria-role, missing-required-aria-role-property, role-interactive-not-focusable, aria-hidden-focusable, invalid-aria-state, invalid-aria-number, autoplay-media-with-sound, invalid-label-reference, duplicate-id, and missing-aria-reference; warnings: missing-image-description, unsupported-aria-role-property, positive-tabindex, missing-page-heading, skipped-heading-level, missing-main-landmark, and multiple-main-landmarks. Documentation: https://www.w3.org/WAI/WCAG22/understanding/. security errors: non-get-resource-exposed-as-data-source; warning: target-blank-without-noopener. Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/noopener. seo errors: empty-page-title, invalid-json-ld, and json-ld-in-custom-metadata; warnings: missing-page-description, empty-page-description, invalid-page-language, missing-social-image-asset, duplicate-page-title, duplicate-page-description, missing-json-ld-context, unknown-schema-org-type, deprecated-schema-org-type, unknown-schema-org-property, deprecated-schema-org-property, unsupported-schema-org-property, and incompatible-schema-org-value. Documentation: https://developers.google.com/search/docs/fundamentals/seo-starter-guide. assets info: unused-asset. Documentation: https://docs.webstudio.is/university/foundations/anatomy-of-the-webstudio-builder. styles warning: style-on-dom-transparent-component; info: unused-design-token, unused-css-variable, unused-local-style-source, unused-breakpoint, and duplicate-design-token-declarations. Documentation: https://docs.webstudio.is/university/foundations/design-tokens. performance info: atomic-css-disabled. Rendered checks add image loading/sizing, render-blocking resource, and legacy font-format evidence. Documentation: https://docs.webstudio.is/university/foundations/project-settings#atomic-css.",
+ minItems: 1,
+ type: "array",
+ items: {
+ type: "string",
+ enum: [
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ],
+ },
+ },
+ pageId: {
+ type: "string",
+ },
+ pagePath: {
+ type: "string",
+ },
+ severities: {
+ description:
+ "Filter returned findings by default rule severity: error, warning, or info. Summary counts remain unfiltered.",
+ minItems: 1,
+ type: "array",
+ items: {
+ type: "string",
+ enum: ["error", "warning", "info"],
+ },
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ cursor: {
+ type: "string",
+ minLength: 1,
+ },
+ verbose: {
+ description:
+ "Include explanations, remediation, evidence, skipped-check details, and manual-check workflows.",
+ type: "boolean",
+ },
+ },
+ additionalProperties: false,
+ required: [],
+ },
+ outputSchema: {
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ contractVersion: {
+ type: "number",
+ const: 1,
+ },
+ projectVersion: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ scopes: {
+ type: "array",
+ items: {
+ type: "string",
+ enum: [
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ],
+ },
+ },
+ pageFilter: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ pagePath: {
+ type: "string",
+ },
+ projectWideScopes: {
+ type: "array",
+ items: {
+ type: "string",
+ enum: [
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ],
+ },
+ },
+ },
+ required: ["pageId", "pagePath", "projectWideScopes"],
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ summary: {
+ type: "object",
+ properties: {
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ selectedTotal: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ bySeverity: {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ enum: ["error", "warning", "info"],
+ },
+ additionalProperties: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ required: ["error", "warning", "info"],
+ },
+ byScope: {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ enum: [
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ],
+ },
+ additionalProperties: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ required: [
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ],
+ },
+ },
+ required: ["total", "selectedTotal", "bySeverity", "byScope"],
+ },
+ skippedCheckCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ manualCheckCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ renderedCheckCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ renderedIssueCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ renderedFailureCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ verbose: {
+ type: "boolean",
+ const: false,
+ },
+ findings: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ scope: {
+ type: "string",
+ enum: [
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ],
+ },
+ ruleId: {
+ type: "string",
+ enum: [
+ "missing-alt",
+ "missing-image-description",
+ "missing-image-input-alt",
+ "missing-iframe-title",
+ "missing-accessible-name",
+ "missing-form-label",
+ "invalid-aria-role",
+ "unsupported-aria-role-property",
+ "missing-required-aria-role-property",
+ "role-interactive-not-focusable",
+ "aria-hidden-focusable",
+ "positive-tabindex",
+ "invalid-aria-state",
+ "invalid-aria-number",
+ "autoplay-media-with-sound",
+ "invalid-label-reference",
+ "missing-page-heading",
+ "skipped-heading-level",
+ "missing-main-landmark",
+ "multiple-main-landmarks",
+ "duplicate-id",
+ "missing-aria-reference",
+ "target-blank-without-noopener",
+ "non-get-resource-exposed-as-data-source",
+ "missing-page-description",
+ "empty-page-description",
+ "invalid-page-language",
+ "missing-social-image-asset",
+ "empty-page-title",
+ "duplicate-page-title",
+ "duplicate-page-description",
+ "invalid-json-ld",
+ "missing-json-ld-context",
+ "json-ld-in-custom-metadata",
+ "unknown-schema-org-type",
+ "deprecated-schema-org-type",
+ "unknown-schema-org-property",
+ "deprecated-schema-org-property",
+ "unsupported-schema-org-property",
+ "incompatible-schema-org-value",
+ "unused-asset",
+ "unused-design-token",
+ "unused-css-variable",
+ "unused-local-style-source",
+ "unused-breakpoint",
+ "duplicate-design-token-declarations",
+ "style-on-dom-transparent-component",
+ "atomic-css-disabled",
+ ],
+ },
+ severity: {
+ type: "string",
+ enum: ["error", "warning", "info"],
+ },
+ message: {
+ type: "string",
+ },
+ location: {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ pageIds: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ pagePath: {
+ type: "string",
+ },
+ pagePaths: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ instanceId: {
+ type: "string",
+ },
+ instanceIds: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ propName: {
+ type: "string",
+ },
+ assetId: {
+ type: "string",
+ },
+ styleSourceId: {
+ type: "string",
+ },
+ designTokenId: {
+ type: "string",
+ },
+ designTokenIds: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ cssVariableName: {
+ type: "string",
+ },
+ cssVariableScope: {
+ type: "string",
+ },
+ breakpointId: {
+ type: "string",
+ },
+ resourceId: {
+ type: "string",
+ },
+ dataSourceId: {
+ type: "string",
+ },
+ htmlId: {
+ type: "string",
+ },
+ jsonLdPath: {
+ type: "string",
+ },
+ },
+ additionalProperties: false,
+ required: [],
+ },
+ },
+ required: [
+ "id",
+ "scope",
+ "ruleId",
+ "severity",
+ "message",
+ "location",
+ ],
+ },
+ },
+ },
+ required: [
+ "contractVersion",
+ "projectVersion",
+ "scopes",
+ "pageFilter",
+ "summary",
+ "skippedCheckCount",
+ "manualCheckCount",
+ "renderedCheckCount",
+ "renderedIssueCount",
+ "renderedFailureCount",
+ "nextCursor",
+ "verbose",
+ "findings",
+ ],
+ },
+ {
+ type: "object",
+ properties: {
+ contractVersion: {
+ type: "number",
+ const: 1,
+ },
+ projectVersion: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ scopes: {
+ type: "array",
+ items: {
+ type: "string",
+ enum: [
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ],
+ },
+ },
+ pageFilter: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ pagePath: {
+ type: "string",
+ },
+ projectWideScopes: {
+ type: "array",
+ items: {
+ type: "string",
+ enum: [
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ],
+ },
+ },
+ },
+ required: ["pageId", "pagePath", "projectWideScopes"],
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ summary: {
+ type: "object",
+ properties: {
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ selectedTotal: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ bySeverity: {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ enum: ["error", "warning", "info"],
+ },
+ additionalProperties: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ required: ["error", "warning", "info"],
+ },
+ byScope: {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ enum: [
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ],
+ },
+ additionalProperties: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ required: [
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ],
+ },
+ },
+ required: ["total", "selectedTotal", "bySeverity", "byScope"],
+ },
+ skippedCheckCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ manualCheckCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ renderedCheckCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ renderedIssueCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ renderedFailureCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ verbose: {
+ type: "boolean",
+ const: true,
+ },
+ findings: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ },
+ scope: {
+ type: "string",
+ enum: [
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ],
+ },
+ ruleId: {
+ type: "string",
+ enum: [
+ "missing-alt",
+ "missing-image-description",
+ "missing-image-input-alt",
+ "missing-iframe-title",
+ "missing-accessible-name",
+ "missing-form-label",
+ "invalid-aria-role",
+ "unsupported-aria-role-property",
+ "missing-required-aria-role-property",
+ "role-interactive-not-focusable",
+ "aria-hidden-focusable",
+ "positive-tabindex",
+ "invalid-aria-state",
+ "invalid-aria-number",
+ "autoplay-media-with-sound",
+ "invalid-label-reference",
+ "missing-page-heading",
+ "skipped-heading-level",
+ "missing-main-landmark",
+ "multiple-main-landmarks",
+ "duplicate-id",
+ "missing-aria-reference",
+ "target-blank-without-noopener",
+ "non-get-resource-exposed-as-data-source",
+ "missing-page-description",
+ "empty-page-description",
+ "invalid-page-language",
+ "missing-social-image-asset",
+ "empty-page-title",
+ "duplicate-page-title",
+ "duplicate-page-description",
+ "invalid-json-ld",
+ "missing-json-ld-context",
+ "json-ld-in-custom-metadata",
+ "unknown-schema-org-type",
+ "deprecated-schema-org-type",
+ "unknown-schema-org-property",
+ "deprecated-schema-org-property",
+ "unsupported-schema-org-property",
+ "incompatible-schema-org-value",
+ "unused-asset",
+ "unused-design-token",
+ "unused-css-variable",
+ "unused-local-style-source",
+ "unused-breakpoint",
+ "duplicate-design-token-declarations",
+ "style-on-dom-transparent-component",
+ "atomic-css-disabled",
+ ],
+ },
+ severity: {
+ type: "string",
+ enum: ["error", "warning", "info"],
+ },
+ message: {
+ type: "string",
+ },
+ explanation: {
+ type: "string",
+ },
+ remediation: {
+ type: "string",
+ },
+ location: {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ pageIds: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ pagePath: {
+ type: "string",
+ },
+ pagePaths: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ instanceId: {
+ type: "string",
+ },
+ instanceIds: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ propName: {
+ type: "string",
+ },
+ assetId: {
+ type: "string",
+ },
+ styleSourceId: {
+ type: "string",
+ },
+ designTokenId: {
+ type: "string",
+ },
+ designTokenIds: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ cssVariableName: {
+ type: "string",
+ },
+ cssVariableScope: {
+ type: "string",
+ },
+ breakpointId: {
+ type: "string",
+ },
+ resourceId: {
+ type: "string",
+ },
+ dataSourceId: {
+ type: "string",
+ },
+ htmlId: {
+ type: "string",
+ },
+ jsonLdPath: {
+ type: "string",
+ },
+ },
+ additionalProperties: false,
+ required: [],
+ },
+ evidence: {
+ type: "object",
+ propertyNames: {
+ type: "string",
+ },
+ additionalProperties: {},
+ },
+ documentationUrl: {
+ type: "string",
+ format: "uri",
+ },
+ },
+ required: [
+ "id",
+ "scope",
+ "ruleId",
+ "severity",
+ "message",
+ "explanation",
+ "remediation",
+ "location",
+ "evidence",
+ ],
+ },
+ },
+ skippedChecks: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ scope: {
+ type: "string",
+ enum: [
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ],
+ },
+ checkId: {
+ type: "string",
+ },
+ reason: {
+ type: "string",
+ enum: [
+ "dynamic-value",
+ "missing-build-data",
+ "unsupported-component",
+ ],
+ },
+ message: {
+ type: "string",
+ },
+ location: {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ pageIds: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ pagePath: {
+ type: "string",
+ },
+ pagePaths: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ instanceId: {
+ type: "string",
+ },
+ instanceIds: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ propName: {
+ type: "string",
+ },
+ assetId: {
+ type: "string",
+ },
+ styleSourceId: {
+ type: "string",
+ },
+ designTokenId: {
+ type: "string",
+ },
+ designTokenIds: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ cssVariableName: {
+ type: "string",
+ },
+ cssVariableScope: {
+ type: "string",
+ },
+ breakpointId: {
+ type: "string",
+ },
+ resourceId: {
+ type: "string",
+ },
+ dataSourceId: {
+ type: "string",
+ },
+ htmlId: {
+ type: "string",
+ },
+ jsonLdPath: {
+ type: "string",
+ },
+ },
+ additionalProperties: false,
+ required: [],
+ },
+ },
+ required: ["scope", "checkId", "reason", "message", "location"],
+ },
+ },
+ manualChecks: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ checkId: {
+ type: "string",
+ },
+ message: {
+ type: "string",
+ },
+ workflow: {
+ type: "string",
+ },
+ },
+ required: ["checkId", "message", "workflow"],
+ },
+ },
+ renderedChecks: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ pagePath: {
+ type: "string",
+ },
+ viewport: {
+ type: "object",
+ properties: {
+ width: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ height: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["width", "height"],
+ },
+ screenshotPath: {
+ type: "string",
+ },
+ layout: {
+ type: "object",
+ properties: {
+ viewportWidth: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ viewportHeight: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ contentWidth: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ contentHeight: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ horizontalOverflow: {
+ type: "boolean",
+ },
+ images: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ instanceId: {
+ type: "string",
+ },
+ loading: {
+ type: "string",
+ },
+ complete: {
+ type: "boolean",
+ },
+ naturalWidth: {
+ type: "number",
+ minimum: 0,
+ },
+ naturalHeight: {
+ type: "number",
+ minimum: 0,
+ },
+ renderedWidth: {
+ type: "number",
+ minimum: 0,
+ },
+ renderedHeight: {
+ type: "number",
+ minimum: 0,
+ },
+ top: {
+ type: "number",
+ },
+ },
+ required: [
+ "loading",
+ "complete",
+ "naturalWidth",
+ "naturalHeight",
+ "renderedWidth",
+ "renderedHeight",
+ "top",
+ ],
+ },
+ },
+ resources: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ pathname: {
+ type: "string",
+ },
+ initiatorType: {
+ type: "string",
+ },
+ transferSize: {
+ type: "number",
+ minimum: 0,
+ },
+ encodedBodySize: {
+ type: "number",
+ minimum: 0,
+ },
+ decodedBodySize: {
+ type: "number",
+ minimum: 0,
+ },
+ duration: {
+ type: "number",
+ minimum: 0,
+ },
+ renderBlockingStatus: {
+ type: "string",
+ },
+ },
+ required: [
+ "pathname",
+ "initiatorType",
+ "transferSize",
+ "encodedBodySize",
+ "decodedBodySize",
+ "duration",
+ ],
+ },
+ },
+ },
+ required: [
+ "viewportWidth",
+ "viewportHeight",
+ "contentWidth",
+ "contentHeight",
+ "horizontalOverflow",
+ "images",
+ "resources",
+ ],
+ },
+ issues: {
+ type: "array",
+ items: {
+ type: "string",
+ enum: [
+ "horizontal-overflow",
+ "broken-image",
+ "eager-below-fold-image",
+ "oversized-image",
+ "render-blocking-resource",
+ "legacy-font-format",
+ ],
+ },
+ },
+ imageIssues: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ kind: {
+ type: "string",
+ enum: [
+ "broken-image",
+ "eager-below-fold-image",
+ "oversized-image",
+ ],
+ },
+ instanceId: {
+ type: "string",
+ },
+ loading: {
+ type: "string",
+ },
+ naturalWidth: {
+ type: "number",
+ minimum: 0,
+ },
+ naturalHeight: {
+ type: "number",
+ minimum: 0,
+ },
+ renderedWidth: {
+ type: "number",
+ minimum: 0,
+ },
+ renderedHeight: {
+ type: "number",
+ minimum: 0,
+ },
+ top: {
+ type: "number",
+ },
+ },
+ required: [
+ "kind",
+ "loading",
+ "naturalWidth",
+ "naturalHeight",
+ "renderedWidth",
+ "renderedHeight",
+ "top",
+ ],
+ },
+ },
+ resourceIssues: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ kind: {
+ type: "string",
+ enum: [
+ "render-blocking-resource",
+ "legacy-font-format",
+ ],
+ },
+ pathname: {
+ type: "string",
+ },
+ initiatorType: {
+ type: "string",
+ },
+ transferSize: {
+ type: "number",
+ minimum: 0,
+ },
+ encodedBodySize: {
+ type: "number",
+ minimum: 0,
+ },
+ decodedBodySize: {
+ type: "number",
+ minimum: 0,
+ },
+ duration: {
+ type: "number",
+ minimum: 0,
+ },
+ renderBlockingStatus: {
+ type: "string",
+ },
+ },
+ required: [
+ "kind",
+ "pathname",
+ "initiatorType",
+ "transferSize",
+ "encodedBodySize",
+ "decodedBodySize",
+ "duration",
+ ],
+ },
+ },
+ },
+ required: [
+ "pageId",
+ "pagePath",
+ "viewport",
+ "screenshotPath",
+ "layout",
+ "issues",
+ "imageIssues",
+ "resourceIssues",
+ ],
+ },
+ },
+ renderedFailures: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ pageId: {
+ type: "string",
+ },
+ pagePath: {
+ type: "string",
+ },
+ viewport: {
+ type: "object",
+ properties: {
+ width: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ height: {
+ type: "integer",
+ exclusiveMinimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ required: ["width", "height"],
+ },
+ message: {
+ type: "string",
+ },
+ },
+ required: ["message"],
+ },
+ },
+ },
+ required: [
+ "contractVersion",
+ "projectVersion",
+ "scopes",
+ "pageFilter",
+ "summary",
+ "skippedCheckCount",
+ "manualCheckCount",
+ "renderedCheckCount",
+ "renderedIssueCount",
+ "renderedFailureCount",
+ "nextCursor",
+ "verbose",
+ "findings",
+ "skippedChecks",
+ "manualChecks",
+ "renderedChecks",
+ "renderedFailures",
+ ],
+ },
+ ],
+ },
+ readNamespaces: [
+ "pages",
+ "projectSettings",
+ "instances",
+ "props",
+ "styles",
+ "styleSources",
+ "styleSourceSelections",
+ "resources",
+ "dataSources",
+ "assets",
+ "breakpoints",
+ ],
+ writeNamespaces: [],
+ invalidatesNamespaces: [],
+ retryOnConflict: false,
+ requiresAssets: true,
+ },
{
id: "instances.insertComponent",
command: "insert-component",
@@ -30568,6 +31846,63 @@ export const runtimeOperationContractData = [
invalidatesNamespaces: ["props"],
retryOnConflict: false,
},
+ {
+ id: "instances.replacePropText",
+ command: "replace-prop-text",
+ client: "replacePropText",
+ permit: "edit",
+ kind: "mutation",
+ inputSchema: {
+ type: "object",
+ properties: {
+ find: {
+ type: "string",
+ minLength: 1,
+ description: "Fixed prop text to find.",
+ },
+ replace: {
+ type: "string",
+ description: "Replacement fixed prop text.",
+ },
+ match: {
+ default: "exact",
+ description:
+ 'Use "exact" to replace complete prop values, or "substring" to replace every literal occurrence in matching prop values.',
+ type: "string",
+ enum: ["exact", "substring"],
+ },
+ instanceIds: {
+ description: "Optional instance ids to limit the replacement scope.",
+ minItems: 1,
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ names: {
+ description:
+ "Optional prop names to limit the replacement scope, such as href or code.",
+ minItems: 1,
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ limit: {
+ default: 50,
+ description: "Maximum number of prop values to change.",
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ },
+ required: ["find", "replace"],
+ },
+ readNamespaces: ["instances", "props"],
+ writeNamespaces: ["props"],
+ invalidatesNamespaces: ["props"],
+ retryOnConflict: true,
+ },
{
id: "instances.deleteProps",
command: "delete-props",
@@ -30784,6 +32119,52 @@ export const runtimeOperationContractData = [
invalidatesNamespaces: ["instances"],
retryOnConflict: true,
},
+ {
+ id: "instances.replaceText",
+ command: "replace-text",
+ client: "replaceText",
+ permit: "edit",
+ kind: "mutation",
+ inputSchema: {
+ type: "object",
+ properties: {
+ find: {
+ type: "string",
+ minLength: 1,
+ description: "Literal text to find.",
+ },
+ replace: {
+ type: "string",
+ description: "Replacement literal text.",
+ },
+ match: {
+ default: "exact",
+ description:
+ 'Use "exact" to replace complete text children, or "substring" to replace every literal occurrence inside matching text children.',
+ type: "string",
+ enum: ["exact", "substring"],
+ },
+ pageId: {
+ type: "string",
+ },
+ pagePath: {
+ type: "string",
+ },
+ limit: {
+ default: 50,
+ description: "Maximum number of text children to replace.",
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ },
+ required: ["find", "replace"],
+ },
+ readNamespaces: ["pages", "instances"],
+ writeNamespaces: ["instances"],
+ invalidatesNamespaces: ["instances"],
+ retryOnConflict: true,
+ },
{
id: "instances.setTextContent",
command: "set-text-content",
@@ -30934,9 +32315,32 @@ export const runtimeOperationContractData = [
},
required: ["rootInstanceId", "instances"],
},
- readNamespaces: ["instances"],
- writeNamespaces: ["instances"],
- invalidatesNamespaces: ["instances"],
+ readNamespaces: [
+ "instances",
+ "props",
+ "dataSources",
+ "styleSources",
+ "styleSourceSelections",
+ "styles",
+ ],
+ writeNamespaces: [
+ "instances",
+ "props",
+ "dataSources",
+ "resources",
+ "styleSourceSelections",
+ "styleSources",
+ "styles",
+ ],
+ invalidatesNamespaces: [
+ "instances",
+ "props",
+ "dataSources",
+ "resources",
+ "styleSourceSelections",
+ "styleSources",
+ "styles",
+ ],
retryOnConflict: true,
},
{
@@ -31275,6 +32679,11 @@ export const runtimeOperationContractData = [
type: "string",
},
withUsage: {
+ description: "Include usage counts. Defaults to true.",
+ type: "boolean",
+ },
+ includeStyles: {
+ description: "Include full inline style declarations for each token.",
type: "boolean",
},
sort: {
@@ -34966,7 +36375,26 @@ export const runtimeOperationContractData = [
type: "string",
},
value: {
- type: "string",
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
},
},
required: ["name", "value"],
@@ -34981,14 +36409,52 @@ export const runtimeOperationContractData = [
type: "string",
},
value: {
- type: "string",
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
},
},
required: ["name", "value"],
},
},
body: {
- type: "string",
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
},
},
required: ["name", "method", "url", "headers"],
@@ -35090,7 +36556,26 @@ export const runtimeOperationContractData = [
type: "string",
},
value: {
- type: "string",
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
},
},
required: ["name", "value"],
@@ -35105,14 +36590,52 @@ export const runtimeOperationContractData = [
type: "string",
},
value: {
- type: "string",
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
},
},
required: ["name", "value"],
},
},
body: {
- type: "string",
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
},
},
required: [],
@@ -35161,6 +36684,63 @@ export const runtimeOperationContractData = [
],
retryOnConflict: false,
},
+ {
+ id: "resources.replaceText",
+ command: "replace-resource-text",
+ client: "replaceResourceText",
+ kind: "mutation",
+ inputSchema: {
+ type: "object",
+ properties: {
+ find: {
+ type: "string",
+ minLength: 1,
+ description: "Fixed resource text to find.",
+ },
+ replace: {
+ type: "string",
+ description: "Replacement fixed resource text.",
+ },
+ match: {
+ default: "exact",
+ description:
+ 'Use "exact" to replace complete values, or "substring" to replace every literal occurrence in matching values.',
+ type: "string",
+ enum: ["exact", "substring"],
+ },
+ fields: {
+ default: ["name", "url"],
+ description: "Resource text fields to replace.",
+ minItems: 1,
+ type: "array",
+ items: {
+ type: "string",
+ enum: ["name", "url"],
+ },
+ },
+ resourceIds: {
+ description: "Optional resource ids to limit scope.",
+ minItems: 1,
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ limit: {
+ default: 50,
+ description: "Maximum number of resource fields to change.",
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ },
+ required: ["find", "replace"],
+ },
+ readNamespaces: ["resources"],
+ writeNamespaces: ["resources"],
+ invalidatesNamespaces: ["resources"],
+ retryOnConflict: true,
+ },
{
id: "resources.upsert",
command: "upsert-resource",
@@ -35214,7 +36794,26 @@ export const runtimeOperationContractData = [
type: "string",
},
value: {
- type: "string",
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
},
},
required: ["name", "value"],
@@ -35229,14 +36828,52 @@ export const runtimeOperationContractData = [
type: "string",
},
value: {
- type: "string",
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
},
},
required: ["name", "value"],
},
},
body: {
- type: "string",
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
},
},
required: ["name", "method", "url", "headers"],
@@ -35347,7 +36984,26 @@ export const runtimeOperationContractData = [
type: "string",
},
value: {
- type: "string",
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
},
},
required: ["name", "value"],
@@ -35362,14 +37018,52 @@ export const runtimeOperationContractData = [
type: "string",
},
value: {
- type: "string",
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
},
},
required: ["name", "value"],
},
},
body: {
- type: "string",
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "literal",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ ],
+ description:
+ 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.',
},
},
required: ["name", "method", "url", "headers"],
@@ -35473,6 +37167,7 @@ export const runtimeOperationContractData = [
readNamespaces: [
"assets",
"pages",
+ "projectSettings",
"props",
"styles",
"resources",
@@ -35483,6 +37178,28 @@ export const runtimeOperationContractData = [
retryOnConflict: false,
requiresAssets: true,
},
+ {
+ id: "fonts.list",
+ command: "list-fonts",
+ client: "listFonts",
+ kind: "read",
+ inputSchema: {
+ type: "object",
+ properties: {
+ includeSystem: {
+ default: true,
+ description: "Include built-in system font stacks.",
+ type: "boolean",
+ },
+ },
+ required: [],
+ },
+ readNamespaces: ["assets"],
+ writeNamespaces: [],
+ invalidatesNamespaces: [],
+ retryOnConflict: false,
+ requiresAssets: true,
+ },
{
id: "assets.findUsage",
command: "find-asset-usage",
@@ -35500,6 +37217,7 @@ export const runtimeOperationContractData = [
readNamespaces: [
"assets",
"pages",
+ "projectSettings",
"props",
"styles",
"resources",
@@ -35549,6 +37267,69 @@ export const runtimeOperationContractData = [
retryOnConflict: false,
requiresAssets: true,
},
+ {
+ id: "assets.setImageDescriptions",
+ command: "set-image-descriptions",
+ client: "setImageDescriptions",
+ kind: "mutation",
+ inputSchema: {
+ type: "object",
+ properties: {
+ updates: {
+ minItems: 1,
+ type: "array",
+ items: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ assetId: {
+ type: "string",
+ },
+ description: {
+ type: "string",
+ minLength: 1,
+ description:
+ "Concise alt description generated after inspecting the rendered image in context.",
+ },
+ decorative: {
+ type: "boolean",
+ const: false,
+ },
+ },
+ required: ["assetId", "description"],
+ additionalProperties: false,
+ },
+ {
+ type: "object",
+ properties: {
+ assetId: {
+ type: "string",
+ },
+ decorative: {
+ type: "boolean",
+ const: true,
+ description:
+ "Mark the image decorative and intentionally store an empty alt description.",
+ },
+ },
+ required: ["assetId", "decorative"],
+ additionalProperties: false,
+ },
+ ],
+ },
+ description:
+ "Descriptions or decorative decisions for image assets reported by the accessibility audit.",
+ },
+ },
+ required: ["updates"],
+ },
+ readNamespaces: ["assets"],
+ writeNamespaces: ["assets"],
+ invalidatesNamespaces: ["assets"],
+ retryOnConflict: false,
+ requiresAssets: true,
+ },
{
id: "assets.add",
command: "add-asset",
@@ -35828,13 +37609,20 @@ export const runtimeOperationContractData = [
readNamespaces: [
"assets",
"pages",
+ "projectSettings",
"props",
"styles",
"resources",
"dataSources",
],
- writeNamespaces: ["pages", "props", "styles", "assets"],
- invalidatesNamespaces: ["pages", "props", "styles", "assets"],
+ writeNamespaces: ["pages", "projectSettings", "props", "styles", "assets"],
+ invalidatesNamespaces: [
+ "pages",
+ "projectSettings",
+ "props",
+ "styles",
+ "assets",
+ ],
retryOnConflict: false,
requiresAssets: true,
},
@@ -35862,6 +37650,7 @@ export const runtimeOperationContractData = [
readNamespaces: [
"assets",
"pages",
+ "projectSettings",
"props",
"styles",
"resources",
diff --git a/packages/project-build/src/contracts/builder-runtime.test.ts b/packages/project-build/src/contracts/builder-runtime.test.ts
index e05385c89d..fc754924de 100644
--- a/packages/project-build/src/contracts/builder-runtime.test.ts
+++ b/packages/project-build/src/contracts/builder-runtime.test.ts
@@ -81,7 +81,7 @@ describe("builder runtime operation contracts", () => {
expect(
runtimeOperationContracts.find((contract) => contract.id === "pages.list")
?.readNamespaces
- ).toEqual(["pages"]);
+ ).toEqual(["pages", "projectSettings"]);
});
test("derives required public input fields without generated ids", () => {
diff --git a/packages/project-build/src/contracts/builder-runtime.ts b/packages/project-build/src/contracts/builder-runtime.ts
index 66ac6ee40d..b7a08ca241 100644
--- a/packages/project-build/src/contracts/builder-runtime.ts
+++ b/packages/project-build/src/contracts/builder-runtime.ts
@@ -17,6 +17,7 @@ export type RuntimeOperationStateContract = {
id: string;
kind: RuntimeOperationKind;
inputSchema: InputJsonSchema;
+ outputSchema?: InputJsonSchema;
readNamespaces: readonly BuilderNamespace[];
writeNamespaces: readonly BuilderNamespace[];
invalidatesNamespaces: readonly BuilderNamespace[];
diff --git a/packages/project-build/src/contracts/namespaces.test.ts b/packages/project-build/src/contracts/namespaces.test.ts
index 0e850369db..07a7cea0d1 100644
--- a/packages/project-build/src/contracts/namespaces.test.ts
+++ b/packages/project-build/src/contracts/namespaces.test.ts
@@ -13,6 +13,7 @@ test("defines the shared builder namespace catalog", () => {
"resources",
"assets",
"breakpoints",
+ "projectSettings",
"marketplaceProduct",
]);
});
diff --git a/packages/project-build/src/contracts/namespaces.ts b/packages/project-build/src/contracts/namespaces.ts
index 54f36fc719..19e5783dc2 100644
--- a/packages/project-build/src/contracts/namespaces.ts
+++ b/packages/project-build/src/contracts/namespaces.ts
@@ -1,3 +1,13 @@
+/**
+ * Builder namespaces are the durable, editable state synchronized in the CLI
+ * project bundle. Mutations to these namespaces use patches so Builder history,
+ * collaboration, CLI sync, and persisted build versions share one transaction
+ * model.
+ *
+ * State that is not synchronized in the CLI project bundle does not belong in
+ * this list. Account, permission, deployment, domain, and other server-owned
+ * state must use a dedicated tRPC API instead of Builder patches.
+ */
export const builderNamespaces = [
"pages",
"instances",
@@ -9,6 +19,7 @@ export const builderNamespaces = [
"resources",
"assets",
"breakpoints",
+ "projectSettings",
"marketplaceProduct",
] as const;
diff --git a/packages/project-build/src/contracts/patch.test.ts b/packages/project-build/src/contracts/patch.test.ts
index 6218d3b80b..0fdc800603 100644
--- a/packages/project-build/src/contracts/patch.test.ts
+++ b/packages/project-build/src/contracts/patch.test.ts
@@ -51,7 +51,9 @@ describe("builder patch contracts", () => {
test("rejects raw patches that create or replace generated records", () => {
const generatedRecordNamespaceChanges = builderNamespaces.flatMap(
(namespace) =>
- namespace === "pages" || namespace === "marketplaceProduct"
+ namespace === "pages" ||
+ namespace === "projectSettings" ||
+ namespace === "marketplaceProduct"
? []
: [
{
@@ -250,7 +252,9 @@ describe("builder patch contracts", () => {
test("rejects raw patches that mutate generated record id fields", () => {
const generatedRecordNamespaceChanges = builderNamespaces.flatMap(
(namespace) =>
- namespace === "pages" || namespace === "marketplaceProduct"
+ namespace === "pages" ||
+ namespace === "projectSettings" ||
+ namespace === "marketplaceProduct"
? []
: [
{
diff --git a/packages/project-build/src/contracts/patch.ts b/packages/project-build/src/contracts/patch.ts
index 9007589160..09becc3116 100644
--- a/packages/project-build/src/contracts/patch.ts
+++ b/packages/project-build/src/contracts/patch.ts
@@ -49,7 +49,10 @@ export const builderPatchSchema: z.ZodType<BuilderPatch, unknown> = z
const pageGeneratedRecordPaths = new Set(["pages", "folders", "pageTemplates"]);
const generatedRecordNamespaces = new Set<BuilderNamespace>(
builderNamespaces.filter(
- (namespace) => namespace !== "pages" && namespace !== "marketplaceProduct"
+ (namespace) =>
+ namespace !== "pages" &&
+ namespace !== "projectSettings" &&
+ namespace !== "marketplaceProduct"
)
);
diff --git a/packages/project-build/src/db/build.test.ts b/packages/project-build/src/db/build.test.ts
index fd281fb738..4a157c6cd3 100644
--- a/packages/project-build/src/db/build.test.ts
+++ b/packages/project-build/src/db/build.test.ts
@@ -71,6 +71,7 @@ const buildRow = {
]),
deployment: null,
marketplaceProduct: JSON.stringify({}),
+ projectSettings: JSON.stringify({ meta: {}, compiler: {} }),
};
// ---------------------------------------------------------------------------
@@ -111,6 +112,34 @@ describe("loadBuildById (msw)", () => {
const result = await loadBuildById(createContext(), "build-1");
expect(result.id).toBe("build-1");
expect(result.projectId).toBe("proj-1");
+ expect(result.marketplaceProduct).toBeUndefined();
+ });
+
+ test("migrates project settings from legacy pages", async () => {
+ server.use(
+ db.get("Build", () =>
+ json([
+ {
+ ...buildRow,
+ pages: JSON.stringify({
+ ...JSON.parse(buildRow.pages),
+ meta: { siteName: "Legacy site" },
+ compiler: { atomicStyles: false },
+ }),
+ projectSettings: undefined,
+ },
+ ])
+ )
+ );
+
+ const result = await loadBuildById(createContext(), "build-1");
+
+ expect(result.projectSettings).toEqual({
+ meta: { siteName: "Legacy site" },
+ compiler: { atomicStyles: false },
+ });
+ expect(result.pages.meta).toBeUndefined();
+ expect(result.pages.compiler).toBeUndefined();
});
});
diff --git a/packages/project-build/src/db/build.ts b/packages/project-build/src/db/build.ts
index 8687b25cfc..8b025d872b 100644
--- a/packages/project-build/src/db/build.ts
+++ b/packages/project-build/src/db/build.ts
@@ -22,7 +22,12 @@ import {
} from "@webstudio-is/project-migrations/pages";
import type { Build, CompactBuild } from "../types";
import { parseDeployment } from "./deployment";
-import type { MarketplaceProduct } from "../shared//marketplace";
+import { marketplaceProduct } from "../shared/marketplace";
+import {
+ createProjectSettingsFromPages,
+ projectSettings,
+ removeLegacyProjectSettingsFromPages,
+} from "../shared/project-settings";
import { breakCyclesMutable } from "../shared/graph-utils";
import { createPages } from "../template";
import { serializeStyles } from "./styles";
@@ -49,16 +54,38 @@ const parseCompactInstanceData = (serialized: string) => {
return instances;
};
+const parseMarketplaceProduct = (serialized: string | null | undefined) => {
+ const value =
+ serialized === undefined || serialized === null
+ ? undefined
+ : parseConfig<unknown>(serialized);
+ if (
+ value === undefined ||
+ (typeof value === "object" &&
+ value !== null &&
+ Object.keys(value).length === 0)
+ ) {
+ return undefined;
+ }
+ return marketplaceProduct.parse(value);
+};
+
const parseCompactBuild = async (
build: Database["public"]["Tables"]["Build"]["Row"]
) => {
+ const pages = migratePages(parseConfig<unknown>(build.pages));
+ const parsedProjectSettings =
+ build.projectSettings === undefined || build.projectSettings === null
+ ? createProjectSettingsFromPages(pages)
+ : projectSettings.parse(parseConfig<unknown>(build.projectSettings));
return {
id: build.id,
projectId: build.projectId,
version: build.version,
createdAt: build.createdAt,
updatedAt: build.updatedAt,
- pages: migratePages(parseConfig<unknown>(build.pages)),
+ pages: removeLegacyProjectSettingsFromPages(pages),
+ projectSettings: parsedProjectSettings,
breakpoints: parseCompactData<Breakpoint>(build.breakpoints),
styles: parseCompactData<StyleDecl>(build.styles),
styleSources: parseCompactData<StyleSource>(build.styleSources),
@@ -70,9 +97,7 @@ const parseCompactBuild = async (
resources: parseCompactData<Resource>(build.resources),
instances: parseCompactInstanceData(build.instances),
deployment: parseDeployment(build.deployment),
- marketplaceProduct: parseConfig<MarketplaceProduct>(
- build.marketplaceProduct
- ),
+ marketplaceProduct: parseMarketplaceProduct(build.marketplaceProduct),
} satisfies CompactBuild;
};
@@ -204,10 +229,12 @@ export const createBuild = async (
context: AppContext
): Promise<void> => {
const data = createPages();
+ const pages = removeLegacyProjectSettingsFromPages(data.pages);
const newBuild = await context.postgrest.client.from("Build").insert({
id: crypto.randomUUID(),
projectId: props.projectId,
- pages: JSON.stringify(serializePages(data.pages)),
+ pages: JSON.stringify(serializePages(pages)),
+ projectSettings: JSON.stringify({ meta: {}, compiler: {} }),
breakpoints: serializeData<Breakpoint>(data.breakpoints),
styles: serializeStyles(data.styles),
styleSources: serializeData<StyleSource>(data.styleSources),
diff --git a/packages/project-build/src/docs.generated.ts b/packages/project-build/src/docs.generated.ts
index c206c3870b..174cb66885 100644
--- a/packages/project-build/src/docs.generated.ts
+++ b/packages/project-build/src/docs.generated.ts
@@ -1,8 +1,10 @@
// This file is generated by scripts/generate-docs.mjs.
// Edit markdown files in src/docs instead.
export const projectBuildDocs = {
+ "accessibility-review":
+ '<!-- Adapted for Webstudio MCP from Community-Access/accessibility-agents, web-accessibility-wizard/SKILL.md (MIT): https://github.com/Community-Access/accessibility-agents/blob/main/codex-skills/web-accessibility-wizard/SKILL.md -->\n\n# Webstudio Accessibility Review\n\nUse this workflow when creating or reviewing a page, component, form, menu,\ndialog, or responsive layout. It is an LLM-assisted review, not proof of WCAG\nconformance. Do not claim that a page is accessible solely because this review\nhas no findings.\n\n## Evidence First\n\n1. Read `meta.index` and use focused project tools. Do not inspect Webstudio\n source code or generated files for normal project reviews.\n2. Run `audit` with `{"scopes":["accessibility"]}` before changing\n anything. It detects deterministic metadata issues such as labels, landmark\n structure, positive tabindex values, invalid static ARIA states, and unmuted\n autoplay. Fix confirmed static findings first.\n3. For each changed route, use `preview.start` and capture screenshots with\n `screenshot` at desktop, tablet, and mobile widths. Use `waitForSelector`\n or `waitForTimeout` only when the page has an actual delayed ready state.\n4. Use `get-page-by-path`, `list-instances`, `inspect-instance`, and focused\n prop/style reads to verify semantics and authored state that screenshots\n cannot prove.\n5. Make only supported, evidence-based fixes with semantic MCP tools. Recheck\n the affected route and the static accessibility search after every fix.\n\n## Review Areas\n\nReview these areas in priority order. Record the evidence for every finding.\n\n### 1. Names, Semantics, and Structure\n\n- Every image has purposeful alternative text or an explicitly empty alt when\n decorative. Image-submit inputs need a non-empty alt label describing their\n action.\n- For `missing-image-description` findings, inspect the rendered image in its\n page context and call `set-image-descriptions` with either a concise generated\n description or `decorative: true`. Re-run the audit after saving the decision.\n- Buttons, links, icon-only controls, and form controls have accessible names.\n- Prefer native HTML semantics over ARIA roles.\n- Non-native elements using `role="button"` or `role="link"` must be\n keyboard-focusable.\n- Use one sensible page h1, ordered heading levels, meaningful link text, and\n a main landmark.\n- Iframes have titles. Static HTML ids are unique, ARIA reference props point\n to real ids, and static boolean/select/numeric ARIA values are valid.\n- Focusable controls must not be hidden from assistive technology with\n `aria-hidden`.\n\n### 2. Keyboard and Focus\n\n- Interactive controls should be native or have a documented keyboard model.\n- Visible focus must not be removed without a visible replacement.\n- Hover-only information or controls need a keyboard-accessible equivalent.\n- Do not use positive tabindex values.\n- Mark keyboard behavior as **manual verification required** when the available\n evidence cannot prove tab order, Escape handling, or focus restoration.\n\n### 3. Dialogs, Menus, and Other Overlays\n\n- Dialogs need an accessible name and a close action.\n- Opening an overlay should move focus into it, trap focus where appropriate,\n and restore focus to its trigger on close.\n- Menus, popovers, disclosures, and tabs must expose their expanded/selected\n state and remain usable without a pointer.\n- If the current MCP/browser tools cannot exercise the interaction, report it\n as a manual verification item instead of guessing.\n\n### 4. Forms and Errors\n\n- Inputs have labels, required state, helpers, and errors associated with the\n right control.\n- Invalid controls expose `aria-invalid` when applicable.\n- Error, loading, and success feedback is not conveyed only by color or a\n transient visual toast.\n- Submit controls do not become unexplained dead ends when disabled.\n\n### 5. Visual, Responsive, Media, and Motion\n\n- At each target width, text remains readable, controls remain reachable, and\n no content is clipped, overlapped, or dependent on hover alone.\n- Do not rely only on color, position, shape, or iconography to convey meaning.\n- Keep non-text contrast, text contrast, focus indicators, and small text as\n visual review items unless measured evidence is available.\n- Videos with meaningful speech need captions; non-essential motion should\n respect reduced-motion preferences. Do not autoplay sound.\n\n### 6. Dynamic Content and Data\n\n- Loading, empty, error, and success states have understandable visible text.\n- Important dynamic updates and validation feedback need an appropriate\n announcement strategy.\n- Check repeated resource-driven content for unique labels, headings, ids, and\n meaningful empty states.\n\n## Findings and Fixes\n\nClassify every item as one of:\n\n- **Confirmed:** directly shown by `audit`, project data, or a rendered\n screenshot.\n- **Likely:** a credible issue inferred from rendered evidence; explain what\n would confirm it.\n- **Manual verification required:** needs keyboard, screen-reader, contrast, or\n interaction testing that the available tools cannot prove.\n\nFor each item include: severity (`critical`, `high`, `medium`, or `low`), page\npath, affected element or instance id when known, evidence, short user impact,\nand the smallest supported fix. Fix critical and high items first. Do not add\nARIA attributes, alt text, labels, or live regions when their meaning cannot be\nknown from the project; ask the user or report the missing context.\n\nFinish with a concise summary of fixed findings, remaining findings, and manual\nverification items. Use screenshots as evidence of the rendered state, not as\nproof of accessibility compliance.\n',
"mcp-startup-guidance":
- 'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output. Before editing a Webstudio project, do one small discovery step, then act. For delegated design-system or “use every component” tasks, the first MCP command is `workflow.next {"goal":"design-system-page"}`; report that returned checkpoint to the parent/user and stop until continued. For a simple authored/styled section, the intended path is literal: call `meta.index`, call `meta.get_more_tools` with `{"tools":["insert-fragment"]}`, read the target parent id with `list-pages`/`get-page-by-path`/`list-instances` only if needed, then call `insert-fragment`. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. Do not grep source files, dump full MCP resources, or write parser scripts before trying focused MCP calls. Good first calls are `meta.index` for orientation, `meta.guide` for a goal workflow, `workflow.next` for one bounded delegated phase, `meta.get_more_tools` for exact tool schemas, and `components.coverage-plan`, `components.coverage-insert-next`, `components.find`, or `components.get` for component work. Do not call every discovery tool up front. For delegated or non-streaming agents whose parent cannot see live stderr/stdout, treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report its command/result, and wait for the parent before the next MCP command. Do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands; they hide progress from the parent. Do not take a broad task such as creating a full design-system page as one execution unit. Instead call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint to the parent, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For design-system or “use every component” tasks, start with `workflow.next`, acknowledge its checkpoint only after parent/user continuation, then run compact `components.coverage-plan`, checkpoint, create the page, checkpoint, then call `components.coverage-insert-next` once per coverage checkpoint, and finish with the `presentation-pass` workflow phase. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world design-system examples instead of raw unstyled component dumps. Request component coverage details with `components.coverage-plan {"detail":"roots"}` or `components.coverage-plan {"detail":"parts"}` only when needed. `list-pages` does not accept `detail`; use `list-pages {}` or `get-page-by-path` for page lookup. Read overview resources such as `webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview` only when focused tools are insufficient. Do not dump or parse full resources such as `webstudio://project/tools` or `webstudio://project/components` unless the focused tools are insufficient. Run one-shot shortcut or explicit `webstudio mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. For experiments, pass `--dry-run` to local-capable mutations. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project. If a one-shot call returns checkpoint.required, the CLI persists `CHECKPOINT_REQUIRED` across later one-shot calls until you report the checkpoint, wait until continued, and call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially. Complete one bounded phase and return a checkpoint before continuing. Follow the guide: read ids and Builder breakpoints first, use focused component discovery for component ids, props, and content model composition, prefer semantic tools over `apply-patch`, use direct value tools for fixed text/props, use bindings only for dynamic expressions/resources/actions, quote fixed text for expression-backed fields such as page metadata and resource URLs, put page/resource update fields under `values`, do not edit generated files for normal content/design changes, and use `preview.start` plus screenshot/vision for visual work.\n',
+ 'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output. Before editing a Webstudio project, do one small discovery step, then act. For delegated design-system or “use every component” tasks, the first MCP command is `workflow.next {"goal":"design-system-page"}`; report that returned checkpoint to the parent/user and stop until continued. For a simple authored/styled section, the intended path is literal: call `meta.index`, call `meta.get_more_tools` with `{"tools":["insert-fragment"]}`, read the target parent id with `list-pages`/`get-page-by-path`/`list-instances` only if needed, then call `insert-fragment`. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. Do not grep source files, dump full MCP resources, or write parser scripts before trying focused MCP calls. Good first calls are `meta.index` for orientation, `meta.guide` for a goal workflow, `workflow.next` for one bounded delegated phase, `meta.get_more_tools` for exact tool schemas, and `components.coverage-plan`, `components.coverage-insert-next`, `components.find`, or `components.get` for component work. Do not call every discovery tool up front. For delegated or non-streaming agents whose parent cannot see live stderr/stdout, treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report its command/result, and wait for the parent before the next MCP command. Do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands; they hide progress from the parent. Do not take a broad task such as creating a full design-system page as one execution unit. Instead call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint to the parent, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For design-system or “use every component” tasks, start with `workflow.next`, acknowledge its checkpoint only after parent/user continuation, then run compact `components.coverage-plan`, checkpoint, create the page, checkpoint, then call `components.coverage-insert-next` once per coverage checkpoint, and finish with the `presentation-pass` workflow phase. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world design-system examples instead of raw unstyled component dumps. Request component coverage details with `components.coverage-plan {"detail":"roots"}` or `components.coverage-plan {"detail":"parts"}` only when needed. `list-pages` does not accept `detail`; use `list-pages {}` or `get-page-by-path` for page lookup. Read overview resources such as `webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview` only when focused tools are insufficient. Do not dump or parse full resources such as `webstudio://project/tools` or `webstudio://project/components` unless the focused tools are insufficient. Run one-shot shortcut or explicit `webstudio mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. For experiments, pass `--dry-run` to local-capable mutations. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project. If a one-shot call returns checkpoint.required, the CLI persists `CHECKPOINT_REQUIRED` across later one-shot calls until you report the checkpoint, wait until continued, and call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially. Complete one bounded phase and return a checkpoint before continuing. Follow the guide: read ids and Builder breakpoints first, use focused component discovery for component ids, props, and content model composition, prefer semantic tools over `apply-patch`, use direct value tools for fixed text/props, use bindings only for dynamic expressions/resources/actions, page metadata and fixed resource URLs accept plain strings, put page/resource update fields under `values`, do not edit generated files for normal content/design changes, and use `preview.start` plus screenshot/vision for visual work.\n',
} as const;
export type ProjectBuildDocName = keyof typeof projectBuildDocs;
diff --git a/packages/project-build/src/docs/accessibility-review.md b/packages/project-build/src/docs/accessibility-review.md
new file mode 100644
index 0000000000..150822d73c
--- /dev/null
+++ b/packages/project-build/src/docs/accessibility-review.md
@@ -0,0 +1,115 @@
+<!-- Adapted for Webstudio MCP from Community-Access/accessibility-agents, web-accessibility-wizard/SKILL.md (MIT): https://github.com/Community-Access/accessibility-agents/blob/main/codex-skills/web-accessibility-wizard/SKILL.md -->
+
+# Webstudio Accessibility Review
+
+Use this workflow when creating or reviewing a page, component, form, menu,
+dialog, or responsive layout. It is an LLM-assisted review, not proof of WCAG
+conformance. Do not claim that a page is accessible solely because this review
+has no findings.
+
+## Evidence First
+
+1. Read `meta.index` and use focused project tools. Do not inspect Webstudio
+ source code or generated files for normal project reviews.
+2. Run `audit` with `{"scopes":["accessibility"]}` before changing
+ anything. It detects deterministic metadata issues such as labels, landmark
+ structure, positive tabindex values, invalid static ARIA states, and unmuted
+ autoplay. Fix confirmed static findings first.
+3. For each changed route, use `preview.start` and capture screenshots with
+ `screenshot` at desktop, tablet, and mobile widths. Use `waitForSelector`
+ or `waitForTimeout` only when the page has an actual delayed ready state.
+4. Use `get-page-by-path`, `list-instances`, `inspect-instance`, and focused
+ prop/style reads to verify semantics and authored state that screenshots
+ cannot prove.
+5. Make only supported, evidence-based fixes with semantic MCP tools. Recheck
+ the affected route and the static accessibility search after every fix.
+
+## Review Areas
+
+Review these areas in priority order. Record the evidence for every finding.
+
+### 1. Names, Semantics, and Structure
+
+- Every image has purposeful alternative text or an explicitly empty alt when
+ decorative. Image-submit inputs need a non-empty alt label describing their
+ action.
+- For `missing-image-description` findings, inspect the rendered image in its
+ page context and call `set-image-descriptions` with either a concise generated
+ description or `decorative: true`. Re-run the audit after saving the decision.
+- Buttons, links, icon-only controls, and form controls have accessible names.
+- Prefer native HTML semantics over ARIA roles.
+- Non-native elements using `role="button"` or `role="link"` must be
+ keyboard-focusable.
+- Use one sensible page h1, ordered heading levels, meaningful link text, and
+ a main landmark.
+- Iframes have titles. Static HTML ids are unique, ARIA reference props point
+ to real ids, and static boolean/select/numeric ARIA values are valid.
+- Focusable controls must not be hidden from assistive technology with
+ `aria-hidden`.
+
+### 2. Keyboard and Focus
+
+- Interactive controls should be native or have a documented keyboard model.
+- Visible focus must not be removed without a visible replacement.
+- Hover-only information or controls need a keyboard-accessible equivalent.
+- Do not use positive tabindex values.
+- Mark keyboard behavior as **manual verification required** when the available
+ evidence cannot prove tab order, Escape handling, or focus restoration.
+
+### 3. Dialogs, Menus, and Other Overlays
+
+- Dialogs need an accessible name and a close action.
+- Opening an overlay should move focus into it, trap focus where appropriate,
+ and restore focus to its trigger on close.
+- Menus, popovers, disclosures, and tabs must expose their expanded/selected
+ state and remain usable without a pointer.
+- If the current MCP/browser tools cannot exercise the interaction, report it
+ as a manual verification item instead of guessing.
+
+### 4. Forms and Errors
+
+- Inputs have labels, required state, helpers, and errors associated with the
+ right control.
+- Invalid controls expose `aria-invalid` when applicable.
+- Error, loading, and success feedback is not conveyed only by color or a
+ transient visual toast.
+- Submit controls do not become unexplained dead ends when disabled.
+
+### 5. Visual, Responsive, Media, and Motion
+
+- At each target width, text remains readable, controls remain reachable, and
+ no content is clipped, overlapped, or dependent on hover alone.
+- Do not rely only on color, position, shape, or iconography to convey meaning.
+- Keep non-text contrast, text contrast, focus indicators, and small text as
+ visual review items unless measured evidence is available.
+- Videos with meaningful speech need captions; non-essential motion should
+ respect reduced-motion preferences. Do not autoplay sound.
+
+### 6. Dynamic Content and Data
+
+- Loading, empty, error, and success states have understandable visible text.
+- Important dynamic updates and validation feedback need an appropriate
+ announcement strategy.
+- Check repeated resource-driven content for unique labels, headings, ids, and
+ meaningful empty states.
+
+## Findings and Fixes
+
+Classify every item as one of:
+
+- **Confirmed:** directly shown by `audit`, project data, or a rendered
+ screenshot.
+- **Likely:** a credible issue inferred from rendered evidence; explain what
+ would confirm it.
+- **Manual verification required:** needs keyboard, screen-reader, contrast, or
+ interaction testing that the available tools cannot prove.
+
+For each item include: severity (`critical`, `high`, `medium`, or `low`), page
+path, affected element or instance id when known, evidence, short user impact,
+and the smallest supported fix. Fix critical and high items first. Do not add
+ARIA attributes, alt text, labels, or live regions when their meaning cannot be
+known from the project; ask the user or report the missing context.
+
+Finish with a concise summary of fixed findings, remaining findings, and manual
+verification items. Use screenshots as evidence of the rendered state, not as
+proof of accessibility compliance.
diff --git a/packages/project-build/src/docs/mcp-startup-guidance.md b/packages/project-build/src/docs/mcp-startup-guidance.md
index 92ed66cdd2..42f319e79d 100644
--- a/packages/project-build/src/docs/mcp-startup-guidance.md
+++ b/packages/project-build/src/docs/mcp-startup-guidance.md
@@ -1 +1 @@
-If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output. Before editing a Webstudio project, do one small discovery step, then act. For delegated design-system or “use every component” tasks, the first MCP command is `workflow.next {"goal":"design-system-page"}`; report that returned checkpoint to the parent/user and stop until continued. For a simple authored/styled section, the intended path is literal: call `meta.index`, call `meta.get_more_tools` with `{"tools":["insert-fragment"]}`, read the target parent id with `list-pages`/`get-page-by-path`/`list-instances` only if needed, then call `insert-fragment`. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. Do not grep source files, dump full MCP resources, or write parser scripts before trying focused MCP calls. Good first calls are `meta.index` for orientation, `meta.guide` for a goal workflow, `workflow.next` for one bounded delegated phase, `meta.get_more_tools` for exact tool schemas, and `components.coverage-plan`, `components.coverage-insert-next`, `components.find`, or `components.get` for component work. Do not call every discovery tool up front. For delegated or non-streaming agents whose parent cannot see live stderr/stdout, treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report its command/result, and wait for the parent before the next MCP command. Do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands; they hide progress from the parent. Do not take a broad task such as creating a full design-system page as one execution unit. Instead call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint to the parent, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For design-system or “use every component” tasks, start with `workflow.next`, acknowledge its checkpoint only after parent/user continuation, then run compact `components.coverage-plan`, checkpoint, create the page, checkpoint, then call `components.coverage-insert-next` once per coverage checkpoint, and finish with the `presentation-pass` workflow phase. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world design-system examples instead of raw unstyled component dumps. Request component coverage details with `components.coverage-plan {"detail":"roots"}` or `components.coverage-plan {"detail":"parts"}` only when needed. `list-pages` does not accept `detail`; use `list-pages {}` or `get-page-by-path` for page lookup. Read overview resources such as `webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview` only when focused tools are insufficient. Do not dump or parse full resources such as `webstudio://project/tools` or `webstudio://project/components` unless the focused tools are insufficient. Run one-shot shortcut or explicit `webstudio mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. For experiments, pass `--dry-run` to local-capable mutations. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project. If a one-shot call returns checkpoint.required, the CLI persists `CHECKPOINT_REQUIRED` across later one-shot calls until you report the checkpoint, wait until continued, and call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially. Complete one bounded phase and return a checkpoint before continuing. Follow the guide: read ids and Builder breakpoints first, use focused component discovery for component ids, props, and content model composition, prefer semantic tools over `apply-patch`, use direct value tools for fixed text/props, use bindings only for dynamic expressions/resources/actions, quote fixed text for expression-backed fields such as page metadata and resource URLs, put page/resource update fields under `values`, do not edit generated files for normal content/design changes, and use `preview.start` plus screenshot/vision for visual work.
+If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output. Before editing a Webstudio project, do one small discovery step, then act. For delegated design-system or “use every component” tasks, the first MCP command is `workflow.next {"goal":"design-system-page"}`; report that returned checkpoint to the parent/user and stop until continued. For a simple authored/styled section, the intended path is literal: call `meta.index`, call `meta.get_more_tools` with `{"tools":["insert-fragment"]}`, read the target parent id with `list-pages`/`get-page-by-path`/`list-instances` only if needed, then call `insert-fragment`. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. Do not grep source files, dump full MCP resources, or write parser scripts before trying focused MCP calls. Good first calls are `meta.index` for orientation, `meta.guide` for a goal workflow, `workflow.next` for one bounded delegated phase, `meta.get_more_tools` for exact tool schemas, and `components.coverage-plan`, `components.coverage-insert-next`, `components.find`, or `components.get` for component work. Do not call every discovery tool up front. For delegated or non-streaming agents whose parent cannot see live stderr/stdout, treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report its command/result, and wait for the parent before the next MCP command. Do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands; they hide progress from the parent. Do not take a broad task such as creating a full design-system page as one execution unit. Instead call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint to the parent, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For design-system or “use every component” tasks, start with `workflow.next`, acknowledge its checkpoint only after parent/user continuation, then run compact `components.coverage-plan`, checkpoint, create the page, checkpoint, then call `components.coverage-insert-next` once per coverage checkpoint, and finish with the `presentation-pass` workflow phase. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world design-system examples instead of raw unstyled component dumps. Request component coverage details with `components.coverage-plan {"detail":"roots"}` or `components.coverage-plan {"detail":"parts"}` only when needed. `list-pages` does not accept `detail`; use `list-pages {}` or `get-page-by-path` for page lookup. Read overview resources such as `webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview` only when focused tools are insufficient. Do not dump or parse full resources such as `webstudio://project/tools` or `webstudio://project/components` unless the focused tools are insufficient. Run one-shot shortcut or explicit `webstudio mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. For experiments, pass `--dry-run` to local-capable mutations. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project. If a one-shot call returns checkpoint.required, the CLI persists `CHECKPOINT_REQUIRED` across later one-shot calls until you report the checkpoint, wait until continued, and call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially. Complete one bounded phase and return a checkpoint before continuing. Follow the guide: read ids and Builder breakpoints first, use focused component discovery for component ids, props, and content model composition, prefer semantic tools over `apply-patch`, use direct value tools for fixed text/props, use bindings only for dynamic expressions/resources/actions, page metadata and fixed resource URLs accept plain strings, put page/resource update fields under `values`, do not edit generated files for normal content/design changes, and use `preview.start` plus screenshot/vision for visual work.
diff --git a/packages/project-build/src/index.ts b/packages/project-build/src/index.ts
index be565354c6..3bbf931553 100644
--- a/packages/project-build/src/index.ts
+++ b/packages/project-build/src/index.ts
@@ -5,4 +5,5 @@ export * from "./db/style-source-selections";
export * from "./db/styles";
export * from "./shared/pages-utils";
export * from "./shared/marketplace";
+export * from "./shared/project-settings";
export * from "./shared/graph-utils";
diff --git a/packages/project-build/src/mcp-rendered-audit.test.ts b/packages/project-build/src/mcp-rendered-audit.test.ts
new file mode 100644
index 0000000000..24655b1aa5
--- /dev/null
+++ b/packages/project-build/src/mcp-rendered-audit.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, test } from "vitest";
+import {
+ getRenderedAuditViewports,
+ getRenderedImageIssues,
+ getRenderedResourceIssues,
+} from "./mcp-rendered-audit";
+
+const layout = {
+ viewportWidth: 375,
+ viewportHeight: 812,
+ contentWidth: 375,
+ contentHeight: 1600,
+ horizontalOverflow: false,
+ images: [],
+ resources: [],
+};
+
+describe("rendered audit evidence", () => {
+ test("captures mobile, desktop, and both sides of breakpoint edges", () => {
+ expect(
+ getRenderedAuditViewports({
+ breakpoints: [
+ { minWidth: 768 },
+ { maxWidth: 991.5 },
+ { minWidth: Number.NaN },
+ ],
+ })
+ ).toEqual([
+ { width: 375, height: 812 },
+ { width: 767, height: 900 },
+ { width: 768, height: 900 },
+ { width: 992, height: 900 },
+ { width: 993, height: 900 },
+ { width: 1440, height: 900 },
+ ]);
+ });
+
+ test("classifies broken, eager below-fold, and oversized images once", () => {
+ expect(
+ getRenderedImageIssues({
+ ...layout,
+ images: [
+ {
+ loading: "eager",
+ complete: true,
+ naturalWidth: 0,
+ naturalHeight: 0,
+ renderedWidth: 100,
+ renderedHeight: 50,
+ top: 900,
+ },
+ {
+ loading: "eager",
+ complete: true,
+ naturalWidth: 100,
+ naturalHeight: 100,
+ renderedWidth: 100,
+ renderedHeight: 100,
+ top: 900,
+ },
+ {
+ loading: "lazy",
+ complete: true,
+ naturalWidth: 1000,
+ naturalHeight: 800,
+ renderedWidth: 200,
+ renderedHeight: 150,
+ top: 0,
+ },
+ ],
+ }).map(({ kind }) => kind)
+ ).toEqual(["broken-image", "eager-below-fold-image", "oversized-image"]);
+ });
+
+ test("reports blocking resources and legacy font formats independently", () => {
+ expect(
+ getRenderedResourceIssues({
+ ...layout,
+ resources: [
+ {
+ pathname: "/fonts/brand.woff",
+ initiatorType: "link",
+ transferSize: 10,
+ encodedBodySize: 8,
+ decodedBodySize: 12,
+ duration: 5,
+ renderBlockingStatus: "blocking",
+ },
+ ],
+ }).map(({ kind }) => kind)
+ ).toEqual(["render-blocking-resource", "legacy-font-format"]);
+ });
+});
diff --git a/packages/project-build/src/mcp-rendered-audit.ts b/packages/project-build/src/mcp-rendered-audit.ts
new file mode 100644
index 0000000000..083a938289
--- /dev/null
+++ b/packages/project-build/src/mcp-rendered-audit.ts
@@ -0,0 +1,305 @@
+import type { ProjectSessionEnvelope } from "./project-session";
+import type { RenderedAuditCheck, RenderedAuditFailure } from "./runtime/audit";
+import { isRecord } from "./shared/type-utils";
+import type {
+ ProjectSessionScreenshotInput,
+ ProjectSessionScreenshotResult,
+} from "./mcp";
+
+type Viewport = { width: number; height: number };
+
+type RenderedAuditInput = Record<string, unknown> & {
+ rendered: true;
+};
+
+type ExecuteRead = (
+ command: "list-pages" | "list-breakpoints",
+ input: unknown
+) => Promise<ProjectSessionEnvelope>;
+
+type StartPreview = (
+ input: { source: "session" },
+ progress: { report: (message: string) => void }
+) => Promise<unknown>;
+
+type CaptureScreenshot = (
+ input: ProjectSessionScreenshotInput
+) => Promise<ProjectSessionScreenshotResult>;
+
+export const getRenderedAuditViewports = (breakpoints: unknown): Viewport[] => {
+ const widths = new Set([375, 1440]);
+ if (isRecord(breakpoints) && Array.isArray(breakpoints.breakpoints)) {
+ for (const breakpoint of breakpoints.breakpoints) {
+ if (isRecord(breakpoint) === false) {
+ continue;
+ }
+ for (const [key, delta] of [
+ ["minWidth", -1],
+ ["minWidth", 0],
+ ["maxWidth", 0],
+ ["maxWidth", 1],
+ ] as const) {
+ const value = breakpoint[key];
+ if (typeof value === "number" && Number.isFinite(value)) {
+ widths.add(Math.max(1, Math.round(value) + delta));
+ }
+ }
+ }
+ }
+ return [...widths]
+ .sort((left, right) => left - right)
+ .map((width) => ({ width, height: width <= 480 ? 812 : 900 }));
+};
+
+type Layout = NonNullable<ProjectSessionScreenshotResult["layout"]> & {
+ images: NonNullable<
+ NonNullable<ProjectSessionScreenshotResult["layout"]>["images"]
+ >;
+ resources: NonNullable<
+ NonNullable<ProjectSessionScreenshotResult["layout"]>["resources"]
+ >;
+};
+
+export const getRenderedImageIssues = (
+ layout: Layout
+): RenderedAuditCheck["imageIssues"] =>
+ layout.images.flatMap((image) => {
+ let kind: RenderedAuditCheck["imageIssues"][number]["kind"] | undefined;
+ if (
+ image.complete &&
+ image.naturalWidth === 0 &&
+ image.renderedWidth > 0 &&
+ image.renderedHeight > 0
+ ) {
+ kind = "broken-image";
+ } else if (image.top >= layout.viewportHeight && image.loading !== "lazy") {
+ kind = "eager-below-fold-image";
+ } else if (
+ image.renderedWidth > 0 &&
+ image.renderedHeight > 0 &&
+ image.naturalWidth > image.renderedWidth * 2 &&
+ image.naturalHeight > image.renderedHeight * 2
+ ) {
+ kind = "oversized-image";
+ }
+ return kind === undefined ? [] : [{ kind, ...image }];
+ });
+
+export const getRenderedResourceIssues = (
+ layout: Layout
+): RenderedAuditCheck["resourceIssues"] =>
+ layout.resources.flatMap((resource) => {
+ const issues: RenderedAuditCheck["resourceIssues"] = [];
+ if (resource.renderBlockingStatus === "blocking") {
+ issues.push({ kind: "render-blocking-resource", ...resource });
+ }
+ if (/\.(?:ttf|otf|woff)$/i.test(resource.pathname)) {
+ issues.push({ kind: "legacy-font-format", ...resource });
+ }
+ return issues;
+ });
+
+const selectStaticPages = (pagesResult: unknown, input: RenderedAuditInput) =>
+ isRecord(pagesResult) && Array.isArray(pagesResult.pages)
+ ? pagesResult.pages.filter(
+ (
+ page
+ ): page is Record<string, unknown> & { id: string; path: string } =>
+ isRecord(page) &&
+ typeof page.id === "string" &&
+ typeof page.path === "string" &&
+ page.path.includes(":") === false &&
+ page.path.includes("*") === false &&
+ (typeof input.pageId !== "string" || page.id === input.pageId) &&
+ (typeof input.pagePath !== "string" || page.path === input.pagePath)
+ )
+ : [];
+
+const mergeRenderedAudit = ({
+ envelope,
+ input,
+ checks,
+ failures,
+ complete,
+}: {
+ envelope: ProjectSessionEnvelope;
+ input: RenderedAuditInput;
+ checks: RenderedAuditCheck[];
+ failures: RenderedAuditFailure[];
+ complete: boolean;
+}): ProjectSessionEnvelope => {
+ const result = envelope.result;
+ if (isRecord(result) === false) {
+ return envelope;
+ }
+ const renderedIssueCount = checks.reduce(
+ (count, check) => count + check.issues.length,
+ 0
+ );
+ const isVerbose = input.verbose === true;
+ const manualChecks =
+ isVerbose && Array.isArray(result.manualChecks)
+ ? result.manualChecks.filter(
+ (check) =>
+ complete === false ||
+ (isRecord(check) && check.checkId !== "responsive-visual-review")
+ )
+ : undefined;
+ return {
+ ...envelope,
+ result: {
+ ...result,
+ renderedCheckCount: checks.length,
+ renderedIssueCount,
+ renderedFailureCount: failures.length,
+ manualCheckCount:
+ complete === false
+ ? result.manualCheckCount
+ : Math.max(
+ 0,
+ typeof result.manualCheckCount === "number"
+ ? result.manualCheckCount - 1
+ : 0
+ ),
+ ...(isVerbose
+ ? {
+ renderedChecks: checks,
+ renderedFailures: failures,
+ manualChecks: manualChecks ?? [],
+ }
+ : {}),
+ },
+ };
+};
+
+export const augmentAuditWithRenderedChecks = async ({
+ envelope,
+ input,
+ executeRead,
+ startPreview,
+ captureScreenshot,
+ reportProgress,
+}: {
+ envelope: ProjectSessionEnvelope;
+ input: unknown;
+ executeRead: ExecuteRead;
+ startPreview?: StartPreview;
+ captureScreenshot?: CaptureScreenshot;
+ reportProgress?: (message: string) => void;
+}): Promise<ProjectSessionEnvelope> => {
+ if (
+ isRecord(input) === false ||
+ input.rendered !== true ||
+ startPreview === undefined ||
+ captureScreenshot === undefined ||
+ isRecord(envelope.result) === false
+ ) {
+ return envelope;
+ }
+ const renderedInput = input as RenderedAuditInput;
+ const result = envelope.result;
+ const performanceEnabled =
+ Array.isArray(result.scopes) && result.scopes.includes("performance");
+ const checks: RenderedAuditCheck[] = [];
+ const failures: RenderedAuditFailure[] = [];
+ const finish = (complete: boolean) =>
+ mergeRenderedAudit({
+ envelope,
+ input: renderedInput,
+ checks,
+ failures,
+ complete,
+ });
+
+ reportProgress?.("tool audit preparing rendered responsive checks");
+ let pagesEnvelope: ProjectSessionEnvelope;
+ let breakpointsEnvelope: ProjectSessionEnvelope;
+ try {
+ pagesEnvelope = await executeRead("list-pages", {});
+ breakpointsEnvelope = await executeRead("list-breakpoints", {});
+ await startPreview(
+ { source: "session" },
+ { report: (message) => reportProgress?.(message) }
+ );
+ } catch (error) {
+ failures.push({
+ message: `Rendered audit could not start: ${error instanceof Error ? error.message : String(error)}`,
+ });
+ return finish(false);
+ }
+
+ const pages = selectStaticPages(pagesEnvelope.result, renderedInput);
+ const viewports = getRenderedAuditViewports(breakpointsEnvelope.result);
+ if (pages.length === 0) {
+ failures.push({
+ message: "Rendered audit found no static page paths to capture.",
+ });
+ return finish(false);
+ }
+
+ for (const page of pages) {
+ for (const viewport of viewports) {
+ const pagePath = page.path || "/";
+ reportProgress?.(
+ `tool audit capturing ${pagePath} at ${viewport.width}px`
+ );
+ try {
+ const screenshot = await captureScreenshot({
+ path: pagePath,
+ source: "session",
+ viewport,
+ fullPage: true,
+ includeImageMetrics: performanceEnabled,
+ includeResourceMetrics: performanceEnabled,
+ browser: "auto",
+ });
+ if (screenshot.layout === undefined) {
+ failures.push({
+ pageId: page.id,
+ pagePath,
+ viewport,
+ message: "Screenshot did not return rendered layout metrics.",
+ });
+ continue;
+ }
+ const layout: Layout = {
+ ...screenshot.layout,
+ images: screenshot.layout.images ?? [],
+ resources: screenshot.layout.resources ?? [],
+ };
+ const imageIssues = performanceEnabled
+ ? getRenderedImageIssues(layout)
+ : [];
+ const resourceIssues = performanceEnabled
+ ? getRenderedResourceIssues(layout)
+ : [];
+ checks.push({
+ pageId: page.id,
+ pagePath,
+ viewport,
+ screenshotPath: screenshot.output,
+ layout,
+ issues: [
+ ...(layout.horizontalOverflow
+ ? (["horizontal-overflow"] as const)
+ : []),
+ ...imageIssues.map((issue) => issue.kind),
+ ...resourceIssues.map((issue) => issue.kind),
+ ],
+ imageIssues,
+ resourceIssues,
+ });
+ } catch (error) {
+ failures.push({
+ pageId: page.id,
+ pagePath,
+ viewport,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ }
+ return finish(
+ failures.length === 0 && checks.length === pages.length * viewports.length
+ );
+};
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index 1b97bb61c6..aed7685c46 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -4,6 +4,7 @@ import path from "node:path";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
+import { ListToolsResultSchema } from "@modelcontextprotocol/sdk/types.js";
import { describe, expect, test, vi } from "vitest";
import { z } from "zod";
import type { WsComponentMeta } from "@webstudio-is/sdk";
@@ -12,6 +13,7 @@ import { builderPatchTransactionSchema } from "./contracts/patch";
import { runtimeOperationContracts } from "./contracts/builder-runtime";
import { getInputSchemaMetadata } from "./contracts/input-schema";
import { pageExpressionFieldHint } from "./runtime/pages";
+import { imageDescriptionsSetInput } from "./runtime/assets";
import {
createProjectSessionMcpCore,
createProjectSessionMcpServer,
@@ -109,6 +111,75 @@ const publicMcpOperations: readonly PublicMcpOperation[] = [
inputSchema: getTestInputSchema(z.object({ path: z.string() })),
readNamespaces: ["pages"],
}),
+ publicOperation({
+ command: "audit",
+ id: "project.audit",
+ description: "Audit project quality",
+ inputSchema: getTestInputSchema(
+ z.object({
+ scopes: z
+ .array(
+ z.enum([
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ])
+ )
+ .optional(),
+ severities: z.array(z.enum(["error", "warning", "info"])).optional(),
+ pageId: z.string().optional(),
+ pagePath: z.string().optional(),
+ limit: z.number().int().min(1).max(200).optional(),
+ cursor: z.string().optional(),
+ verbose: z.boolean().optional(),
+ })
+ ),
+ outputSchema: getTestInputSchema(
+ z.discriminatedUnion("verbose", [
+ z.object({
+ contractVersion: z.literal(1),
+ projectVersion: z.number(),
+ verbose: z.literal(false),
+ findings: z.array(z.unknown()),
+ renderedCheckCount: z.number(),
+ renderedIssueCount: z.number(),
+ renderedFailureCount: z.number(),
+ }),
+ z.object({
+ contractVersion: z.literal(1),
+ projectVersion: z.number(),
+ verbose: z.literal(true),
+ findings: z.array(z.unknown()),
+ renderedCheckCount: z.number(),
+ renderedIssueCount: z.number(),
+ renderedFailureCount: z.number(),
+ renderedChecks: z.array(z.unknown()),
+ renderedFailures: z.array(z.unknown()),
+ }),
+ ])
+ ),
+ readNamespaces: [
+ "pages",
+ "instances",
+ "props",
+ "styles",
+ "styleSources",
+ "styleSourceSelections",
+ "resources",
+ "dataSources",
+ "assets",
+ "breakpoints",
+ ],
+ }),
+ publicOperation({
+ command: "list-breakpoints",
+ id: "breakpoints.list",
+ description: "List breakpoints",
+ readNamespaces: ["breakpoints"],
+ }),
publicOperation({
command: "whoami",
id: "auth.me",
@@ -288,6 +359,17 @@ const publicMcpOperations: readonly PublicMcpOperation[] = [
localCapable: false,
serverOnly: true,
}),
+ publicOperation({
+ command: "set-image-descriptions",
+ id: "assets.setImageDescriptions",
+ method: "mutation",
+ permit: "edit",
+ description: "Save agent-generated image descriptions",
+ inputSchema: getTestInputSchema(imageDescriptionsSetInput),
+ readNamespaces: ["assets"],
+ writeNamespaces: ["assets"],
+ invalidatesNamespaces: ["assets"],
+ }),
publicOperation({
command: "replace-asset",
id: "assets.replace",
@@ -480,6 +562,63 @@ describe("project session mcp adapter", () => {
"reset-session",
]);
expect(toolNames).toContain("insert-fragment");
+ const imageDescriptionsTool = tools.find(
+ (tool) => tool.name === "set-image-descriptions"
+ );
+ expect(imageDescriptionsTool).toMatchObject({
+ description: expect.stringContaining(
+ "agent-generated image descriptions"
+ ),
+ inputSchema: expect.objectContaining({
+ required: ["updates"],
+ }),
+ });
+ expect(JSON.stringify(imageDescriptionsTool?.inputSchema)).toContain(
+ "decorative"
+ );
+ expect(
+ getSchemaProperties(
+ tools.find((tool) => tool.name === "audit")?.inputSchema
+ )
+ ).not.toHaveProperty("rendered");
+ const visualTools = listProjectSessionMcpTools(publicMcpOperations, {
+ includeScreenshot: true,
+ includePreview: true,
+ });
+ expect(
+ getSchemaProperties(
+ visualTools.find((tool) => tool.name === "audit")?.inputSchema
+ )
+ ).toHaveProperty("rendered", expect.objectContaining({ type: "boolean" }));
+ expect(JSON.stringify(imageDescriptionsTool?.inputSchema)).toContain(
+ "rendered image in context"
+ );
+ const auditOutputSchema = tools.find(
+ (tool) => tool.name === "audit"
+ )?.outputSchema;
+ expect(auditOutputSchema).toEqual(
+ expect.objectContaining({
+ type: "object",
+ required: ["ok", "data", "meta"],
+ properties: expect.objectContaining({
+ ok: { type: "boolean", const: true },
+ data: expect.objectContaining({ oneOf: expect.any(Array) }),
+ meta: { type: "object", additionalProperties: true },
+ }),
+ })
+ );
+ expect(() =>
+ ListToolsResultSchema.parse({
+ tools: tools.map(
+ ({ name, description, inputSchema, outputSchema }) => ({
+ name,
+ description,
+ inputSchema,
+ ...(outputSchema === undefined ? {} : { outputSchema }),
+ })
+ ),
+ })
+ ).not.toThrow();
for (const command of hiddenMcpOperationCommands) {
expect(toolNames).not.toContain(command);
}
@@ -801,7 +940,7 @@ describe("project session mcp adapter", () => {
);
});
- test("lists MCP resources for project status, tools, and components", () => {
+ test("lists MCP resources for project status, tools, components, and accessibility review", () => {
expect(listProjectSessionMcpResources()).toEqual([
expect.objectContaining({ uri: "webstudio://project/status" }),
expect.objectContaining({ uri: "webstudio://project/tools-overview" }),
@@ -811,6 +950,10 @@ describe("project session mcp adapter", () => {
}),
expect.objectContaining({ uri: "webstudio://project/components" }),
expect.objectContaining({ uri: "webstudio://project/guide" }),
+ expect.objectContaining({
+ uri: "webstudio://project/accessibility-review",
+ mimeType: "text/markdown",
+ }),
]);
});
@@ -850,7 +993,490 @@ describe("project session mcp adapter", () => {
session: expect.objectContaining({
operationId: "pages.list",
source: "local",
+ namespaceCounts: {
+ read: 1,
+ write: 0,
+ invalidated: 0,
+ missing: 0,
+ },
+ diagnosticCount: 0,
+ }),
+ },
+ });
+ expect(result.structuredContent.meta.session).not.toHaveProperty(
+ "namespaces"
+ );
+ expect(result.structuredContent.meta.session).not.toHaveProperty(
+ "diagnostics"
+ );
+ });
+
+ test("exposes the audit input and structured result through MCP", async () => {
+ const auditResult = {
+ contractVersion: 1,
+ projectVersion: 7,
+ scopes: ["accessibility"],
+ pageFilter: null,
+ summary: {
+ total: 1,
+ bySeverity: { error: 1, warning: 0, info: 0 },
+ byScope: {
+ accessibility: 1,
+ security: 0,
+ seo: 0,
+ assets: 0,
+ styles: 0,
+ performance: 0,
+ },
+ },
+ verbose: false,
+ findings: [{ id: "accessibility/missing-alt/image" }],
+ skippedCheckCount: 0,
+ manualCheckCount: 3,
+ renderedCheckCount: 0,
+ renderedIssueCount: 0,
+ renderedFailureCount: 0,
+ nextCursor: null,
+ };
+ const executeOperation = createExecuteOperation(async () =>
+ createEnvelope({ operationId: "project.audit", result: auditResult })
+ );
+ const adapter = createProjectSessionMcpCore({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation,
+ });
+
+ const result = await adapter.callTool({
+ name: "audit",
+ input: {
+ scopes: ["accessibility"],
+ severities: ["error"],
+ limit: 10,
+ },
+ });
+
+ expect(executeOperation).toHaveBeenCalledWith({
+ command: "audit",
+ input: {
+ scopes: ["accessibility"],
+ severities: ["error"],
+ limit: 10,
+ },
+ dryRun: false,
+ });
+ expect(result.structuredContent).toEqual({
+ ok: true,
+ data: auditResult,
+ meta: {
+ session: expect.objectContaining({ operationId: "project.audit" }),
+ },
+ });
+ });
+
+ test("runs rendered responsive checks through the audit tool", async () => {
+ const executeOperation = createExecuteOperation(
+ async ({ command, input }) => {
+ if (command === "list-pages") {
+ return createEnvelope({
+ operationId: "pages.list",
+ result: {
+ pages: [
+ { id: "home", path: "/" },
+ { id: "dynamic", path: "/posts/:slug" },
+ ],
+ },
+ });
+ }
+ if (command === "list-breakpoints") {
+ return createEnvelope({
+ operationId: "breakpoints.list",
+ result: {
+ breakpoints: [
+ { id: "base", label: "Base" },
+ { id: "tablet", label: "Tablet", minWidth: 768 },
+ ],
+ },
+ });
+ }
+ const requestedScopes =
+ typeof input === "object" &&
+ input !== null &&
+ "scopes" in input &&
+ Array.isArray(input.scopes)
+ ? input.scopes
+ : [
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ];
+ return createEnvelope({
+ operationId: "project.audit",
+ result: {
+ contractVersion: 1,
+ projectVersion: 7,
+ scopes: requestedScopes,
+ pageFilter: null,
+ summary: {
+ total: 0,
+ bySeverity: { error: 0, warning: 0, info: 0 },
+ byScope: {
+ accessibility: 0,
+ security: 0,
+ seo: 0,
+ assets: 0,
+ styles: 0,
+ performance: 0,
+ },
+ },
+ verbose: true,
+ findings: [],
+ skippedCheckCount: 0,
+ skippedChecks: [],
+ manualCheckCount: 3,
+ manualChecks: [
+ { checkId: "responsive-visual-review" },
+ { checkId: "visual-contrast-review" },
+ { checkId: "visual-hierarchy-review" },
+ ],
+ renderedCheckCount: 0,
+ renderedIssueCount: 0,
+ renderedFailureCount: 0,
+ renderedChecks: [],
+ renderedFailures: [],
+ nextCursor: null,
+ },
+ });
+ }
+ );
+ const startPreview = vi.fn(async () => ({
+ url: "http://127.0.0.1:5173",
+ running: true,
+ }));
+ const captureScreenshot = vi.fn(async (input) => ({
+ output: `/tmp/${input.viewport.width}.png`,
+ browserPath: "/browser",
+ browser: "chromium" as const,
+ viewport: input.viewport,
+ fullPage: true,
+ elapsedMs: 1,
+ warnings: [],
+ layout: {
+ viewportWidth: input.viewport.width,
+ viewportHeight: input.viewport.height,
+ contentWidth:
+ input.viewport.width === 375
+ ? input.viewport.width + 20
+ : input.viewport.width,
+ contentHeight: 1200,
+ horizontalOverflow: input.viewport.width === 375,
+ images:
+ input.viewport.width === 375
+ ? [
+ {
+ instanceId: "broken",
+ loading: "eager",
+ complete: true,
+ naturalWidth: 0,
+ naturalHeight: 0,
+ renderedWidth: 200,
+ renderedHeight: 100,
+ top: 100,
+ },
+ {
+ instanceId: "below-fold",
+ loading: "eager",
+ complete: true,
+ naturalWidth: 800,
+ naturalHeight: 600,
+ renderedWidth: 400,
+ renderedHeight: 300,
+ top: 900,
+ },
+ {
+ instanceId: "oversized",
+ loading: "lazy",
+ complete: true,
+ naturalWidth: 2400,
+ naturalHeight: 1600,
+ renderedWidth: 600,
+ renderedHeight: 400,
+ top: 100,
+ },
+ ]
+ : [],
+ resources:
+ input.viewport.width === 375
+ ? [
+ {
+ pathname: "/styles.css",
+ initiatorType: "link",
+ transferSize: 12000,
+ encodedBodySize: 11000,
+ decodedBodySize: 40000,
+ duration: 25,
+ renderBlockingStatus: "blocking",
+ },
+ {
+ pathname: "/fonts/brand.ttf",
+ initiatorType: "css",
+ transferSize: 80000,
+ encodedBodySize: 79000,
+ decodedBodySize: 79000,
+ duration: 40,
+ },
+ ]
+ : [],
+ },
+ }));
+ const adapter = createProjectSessionMcpCore({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation,
+ startPreview,
+ getPreviewStatus: vi.fn(),
+ captureScreenshot,
+ });
+
+ const result = await adapter.callTool({
+ name: "audit",
+ input: { rendered: true, verbose: true },
+ });
+
+ expect(executeOperation).toHaveBeenCalledWith({
+ command: "audit",
+ input: { verbose: true },
+ dryRun: false,
+ });
+
+ expect(startPreview).toHaveBeenCalledTimes(1);
+ expect(captureScreenshot).toHaveBeenCalledTimes(4);
+ expect(captureScreenshot).toHaveBeenCalledWith(
+ expect.objectContaining({
+ path: "/",
+ viewport: { width: 375, height: 812 },
+ })
+ );
+ expect(result.structuredContent.data).toMatchObject({
+ renderedCheckCount: 4,
+ renderedIssueCount: 6,
+ renderedFailureCount: 0,
+ manualCheckCount: 2,
+ renderedChecks: [
+ expect.objectContaining({
+ pageId: "home",
+ viewport: { width: 375, height: 812 },
+ issues: [
+ "horizontal-overflow",
+ "broken-image",
+ "eager-below-fold-image",
+ "oversized-image",
+ "render-blocking-resource",
+ "legacy-font-format",
+ ],
+ resourceIssues: [
+ expect.objectContaining({
+ kind: "render-blocking-resource",
+ pathname: "/styles.css",
+ }),
+ expect.objectContaining({
+ kind: "legacy-font-format",
+ pathname: "/fonts/brand.ttf",
+ }),
+ ],
+ imageIssues: [
+ expect.objectContaining({
+ kind: "broken-image",
+ instanceId: "broken",
+ }),
+ expect.objectContaining({
+ kind: "eager-below-fold-image",
+ instanceId: "below-fold",
+ }),
+ expect.objectContaining({
+ kind: "oversized-image",
+ instanceId: "oversized",
+ }),
+ ],
}),
+ expect.any(Object),
+ expect.any(Object),
+ expect.any(Object),
+ ],
+ renderedFailures: [],
+ manualChecks: [
+ { checkId: "visual-contrast-review" },
+ { checkId: "visual-hierarchy-review" },
+ ],
+ });
+
+ captureScreenshot.mockClear();
+ const accessibilityResult = await adapter.callTool({
+ name: "audit",
+ input: {
+ scopes: ["accessibility"],
+ rendered: true,
+ verbose: true,
+ },
+ });
+
+ expect(captureScreenshot).toHaveBeenCalledTimes(4);
+ expect(captureScreenshot).toHaveBeenCalledWith(
+ expect.objectContaining({
+ includeImageMetrics: false,
+ includeResourceMetrics: false,
+ })
+ );
+ expect(accessibilityResult.structuredContent.data).toMatchObject({
+ scopes: ["accessibility"],
+ renderedCheckCount: 4,
+ renderedIssueCount: 1,
+ renderedChecks: [
+ expect.objectContaining({
+ issues: ["horizontal-overflow"],
+ imageIssues: [],
+ resourceIssues: [],
+ }),
+ expect.any(Object),
+ expect.any(Object),
+ expect.any(Object),
+ ],
+ });
+
+ await expect(
+ adapter.callTool({
+ name: "audit",
+ input: { rendered: true, cursor: "next" },
+ })
+ ).rejects.toThrow(/cannot be combined with cursor pagination/);
+ });
+
+ test("keeps audit successful when rendered preview cannot start", async () => {
+ const executeOperation = createExecuteOperation(async ({ command }) => {
+ if (command === "list-pages") {
+ return createEnvelope({
+ operationId: "pages.list",
+ result: { pages: [{ id: "home", path: "/" }] },
+ });
+ }
+ if (command === "list-breakpoints") {
+ return createEnvelope({
+ operationId: "breakpoints.list",
+ result: { breakpoints: [] },
+ });
+ }
+ return createEnvelope({
+ operationId: "project.audit",
+ result: {
+ contractVersion: 1,
+ projectVersion: 7,
+ scopes: [],
+ pageFilter: null,
+ summary: {
+ total: 0,
+ bySeverity: { error: 0, warning: 0, info: 0 },
+ byScope: {},
+ },
+ verbose: true,
+ findings: [],
+ skippedCheckCount: 0,
+ skippedChecks: [],
+ manualCheckCount: 3,
+ manualChecks: [{ checkId: "responsive-visual-review" }],
+ renderedCheckCount: 0,
+ renderedIssueCount: 0,
+ renderedFailureCount: 0,
+ renderedChecks: [],
+ renderedFailures: [],
+ nextCursor: null,
+ },
+ });
+ });
+ const adapter = createProjectSessionMcpCore({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation,
+ startPreview: vi.fn(async () => {
+ throw new Error("preview build failed");
+ }),
+ getPreviewStatus: vi.fn(),
+ captureScreenshot: vi.fn(),
+ });
+
+ const result = await adapter.callTool({
+ name: "audit",
+ input: { rendered: true, verbose: true },
+ });
+
+ expect(result.structuredContent.data).toMatchObject({
+ renderedCheckCount: 0,
+ renderedIssueCount: 0,
+ renderedFailureCount: 1,
+ renderedFailures: [
+ { message: "Rendered audit could not start: preview build failed" },
+ ],
+ manualCheckCount: 3,
+ manualChecks: [{ checkId: "responsive-visual-review" }],
+ });
+ });
+
+ test("does not advertise or silently accept rendered audit without visual capabilities", async () => {
+ const adapter = createProjectSessionMcpCore({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation: createExecuteOperation(),
+ });
+ const auditTool = adapter.listTools().find(({ name }) => name === "audit");
+
+ expect(auditTool?.inputSchema.properties).not.toHaveProperty("rendered");
+ await expect(
+ adapter.callTool({ name: "audit", input: { rendered: true } })
+ ).rejects.toThrow(/does not provide preview and screenshot capabilities/);
+ });
+
+ test("returns the computed transaction for dry-run mutations", async () => {
+ const transaction = {
+ id: "dry-run-transaction",
+ payload: [
+ {
+ namespace: "pages" as const,
+ patches: [
+ { op: "add" as const, path: ["pages", "draft"], value: {} },
+ ],
+ },
+ ],
+ };
+ const executeOperation = createExecuteOperation(async () =>
+ createEnvelope({
+ operationId: "folders.create",
+ source: "dry-run",
+ result: { folderId: "draft" },
+ transaction,
+ })
+ );
+ const adapter = createProjectSessionMcpCore({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation,
+ });
+
+ const result = await adapter.callTool({
+ name: "list-pages",
+ input: {},
+ dryRun: true,
+ });
+
+ expect(result.structuredContent).toMatchObject({
+ data: { folderId: "draft" },
+ meta: {
+ session: {
+ source: "dry-run",
+ committed: false,
+ transaction,
+ },
},
});
});
@@ -1348,6 +1974,56 @@ describe("project session mcp adapter", () => {
});
});
+ test("resolves discriminated input branches before parsing JSON-looking strings", async () => {
+ const operation = publicOperation({
+ command: "update-discriminated-value",
+ id: "test.updateDiscriminatedValue",
+ method: "mutation",
+ permit: "build",
+ description: "Update a discriminated value",
+ inputSchema: getTestInputSchema(
+ z.object({
+ updates: z.array(
+ z.discriminatedUnion("type", [
+ z.object({ type: z.literal("string"), value: z.string() }),
+ z.object({ type: z.literal("json"), value: z.unknown() }),
+ ])
+ ),
+ })
+ ),
+ writeNamespaces: ["props"],
+ invalidatesNamespaces: ["props"],
+ });
+ const executeOperation = createExecuteOperation();
+ const adapter = createProjectSessionMcpCore({
+ operations: [operation],
+ createProjectSession: createSessionFactory(),
+ executeOperation,
+ });
+ const json = '{"@context":"https://schema.org","@type":1}';
+
+ await adapter.callTool({
+ name: operation.command,
+ input: {
+ updates: [
+ { type: "string", value: json },
+ { type: "json", value: json },
+ ],
+ },
+ });
+
+ expect(executeOperation).toHaveBeenCalledWith({
+ command: operation.command,
+ input: {
+ updates: [
+ { type: "string", value: json },
+ { type: "json", value: JSON.parse(json) },
+ ],
+ },
+ dryRun: false,
+ });
+ });
+
test("parses stringified record values through additionalProperties schemas", async () => {
const { adapter, executeOperation } = createTestMcpCore({
operationId: "pages.update",
@@ -1811,6 +2487,31 @@ describe("project session mcp adapter", () => {
createEnvelope({
operationId: "project-session.status",
result: { loaded: true },
+ namespaces: {
+ read: ["pages"],
+ write: [],
+ invalidated: [],
+ missing: ["assets"],
+ },
+ diagnostics: [
+ {
+ level: "warning",
+ code: "STALE_ASSETS",
+ message: "Assets need refreshing.",
+ details: { namespace: "assets" },
+ },
+ ],
+ state: {
+ committed: false,
+ freshness: {
+ pages: {
+ status: "fresh",
+ version: 1,
+ source: "remote",
+ loadedAt: "2026-07-10T12:00:00.000Z",
+ },
+ },
+ },
})
),
refresh: vi.fn(async () =>
@@ -1843,15 +2544,41 @@ describe("project session mcp adapter", () => {
});
const status = await adapter.callTool({ name: "status" });
+ const verboseStatus = await adapter.callTool({
+ name: "status",
+ input: { verbose: true },
+ });
const refresh = await adapter.callTool({
name: "refresh",
input: { namespaces: ["pages"] },
});
- expect(session.initialize).toHaveBeenCalledTimes(2);
+ expect(session.initialize).toHaveBeenCalledTimes(3);
const reset = await adapter.callTool({ name: "reset-session" });
expect(status.structuredContent.data).toEqual({ loaded: true });
- expect(session.initialize).toHaveBeenCalledTimes(2);
+ expect(status.structuredContent.meta.session).not.toHaveProperty(
+ "namespaces"
+ );
+ expect(verboseStatus.structuredContent.meta.session).toMatchObject({
+ namespaces: {
+ read: ["pages"],
+ missing: ["assets"],
+ },
+ diagnostics: [
+ {
+ code: "STALE_ASSETS",
+ details: { namespace: "assets" },
+ },
+ ],
+ freshness: {
+ pages: {
+ status: "fresh",
+ source: "remote",
+ loadedAt: "2026-07-10T12:00:00.000Z",
+ },
+ },
+ });
+ expect(session.initialize).toHaveBeenCalledTimes(3);
expect(session.refresh).toHaveBeenCalledWith(["pages"]);
expect(refresh.structuredContent.meta.session).toEqual(
expect.objectContaining({ operationId: "project-session.refresh" })
@@ -2464,6 +3191,10 @@ describe("project session mcp adapter", () => {
name: "meta.get_more_tools",
input: { brief: "get component details" },
});
+ const jsonLdGuide = await adapter.callTool({
+ name: "meta.guide",
+ input: { brief: "Add JSON-LD structured data to the home page" },
+ });
const getComponentToolNames = (
getComponentDetails.structuredContent.data as {
tools: { name: string }[];
@@ -2485,6 +3216,19 @@ describe("project session mcp adapter", () => {
if (coverageToolNames.includes("components.coverage-status")) {
expect(coverageToolNames[0]).toBe("components.coverage-status");
}
+ expect(jsonLdGuide.structuredContent.data).toEqual(
+ expect.objectContaining({
+ workflow: expect.arrayContaining([
+ expect.stringContaining("do not use update-page custom metadata"),
+ expect.stringContaining("Insert JsonLd under HeadSlot"),
+ expect.stringContaining("Run audit"),
+ ]),
+ tools: expect.arrayContaining([
+ expect.objectContaining({ name: "components.get" }),
+ expect.objectContaining({ name: "audit" }),
+ ]),
+ })
+ );
});
test("rejects invalid focused discovery input with path-specific messages", async () => {
@@ -2703,6 +3447,10 @@ describe("project session mcp adapter", () => {
name: "components.get",
input: { component: "Button" },
});
+ const jsonLdDetails = await adapter.callTool({
+ name: "components.get",
+ input: { component: "JsonLd" },
+ });
const italicDetails = await adapter.callTool({
name: "components.get",
input: { component: "Italic" },
@@ -3167,6 +3915,20 @@ describe("project session mcp adapter", () => {
),
})
);
+ expect(jsonLdDetails.structuredContent.data).toEqual(
+ expect.objectContaining({
+ component: "JsonLd",
+ description: expect.stringContaining("JSON-LD structured data"),
+ jsonLdUsage: expect.stringMatching(/inside HeadSlot.*Schema\.org/),
+ usage: expect.stringContaining("update-props"),
+ props: expect.objectContaining({
+ code: expect.objectContaining({
+ control: "json-code",
+ type: "string",
+ }),
+ }),
+ })
+ );
expect(selectTemplateDetails.structuredContent.data).toEqual(
expect.objectContaining({
found: true,
@@ -3627,6 +4389,7 @@ describe("project session mcp adapter", () => {
expect(captureScreenshot).toHaveBeenCalledWith(
{
url: "https://example.com",
+ baseUrl: undefined,
path: undefined,
output: "current.png",
host: undefined,
@@ -3634,6 +4397,8 @@ describe("project session mcp adapter", () => {
source: undefined,
viewport: { width: 1440, height: 900 },
fullPage: true,
+ includeImageMetrics: false,
+ includeResourceMetrics: false,
browser: "auto",
browserPath: undefined,
waitUntil: "networkidle",
@@ -3945,11 +4710,25 @@ describe("project session mcp adapter", () => {
});
test("rejects invalid screenshot diff input", async () => {
+ const diffScreenshots = vi.fn(async () => ({
+ totalPixels: 0,
+ differentPixels: 0,
+ mismatchPercentage: 0,
+ summary: "Screenshot diff summary",
+ regions: [],
+ textAnalysis: {
+ status: "ok" as const,
+ provider: "tesseract" as const,
+ changes: [],
+ observedText: ["Pricing"],
+ },
+ warnings: [],
+ }));
const adapter = createProjectSessionMcpCore({
operations: publicMcpOperations,
createProjectSession: createSessionFactory(),
executeOperation: createExecuteOperation(),
- diffScreenshots: diffPngFiles,
+ diffScreenshots,
});
await expect(
@@ -3968,6 +4747,58 @@ describe("project session mcp adapter", () => {
},
})
).rejects.toThrow("screenshot.diff threshold must be between 0 and 1.");
+ await adapter.callTool({
+ name: "screenshot.diff",
+ input: {
+ baselinePath: "baseline.png",
+ currentPath: "current.png",
+ expectedText: ["Pricing"],
+ expectedVisual: { maxMismatchPercentage: 2, maxChangedRegions: 3 },
+ },
+ });
+ expect(diffScreenshots).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ expectedText: ["Pricing"],
+ expectedVisual: { maxMismatchPercentage: 2, maxChangedRegions: 3 },
+ })
+ );
+ await expect(
+ adapter.callTool({
+ name: "screenshot.diff",
+ input: {
+ baselinePath: "baseline.png",
+ currentPath: "current.png",
+ expectedText: [],
+ },
+ })
+ ).rejects.toThrow(
+ "screenshot.diff expectedText must be a non-empty array of non-empty strings."
+ );
+ await expect(
+ adapter.callTool({
+ name: "screenshot.diff",
+ input: {
+ baselinePath: "baseline.png",
+ currentPath: "current.png",
+ expectedVisual: { minChangedRegions: 2, maxChangedRegions: 1 },
+ },
+ })
+ ).rejects.toThrow("screenshot.diff expectedVisual must include valid");
+ await expect(
+ adapter.callTool({
+ name: "screenshot.diff",
+ input: {
+ baselinePath: "baseline.png",
+ currentPath: "current.png",
+ expectedVisual: {
+ dominantColorChange: {
+ channel: "purple",
+ direction: "increase",
+ },
+ },
+ },
+ })
+ ).rejects.toThrow("screenshot.diff expectedVisual must include valid");
});
test("installs OCR only after explicit confirmation", async () => {
@@ -4271,6 +5102,9 @@ describe("project session mcp adapter", () => {
const guide = await adapter.readResource({
uri: "webstudio://project/guide",
});
+ const accessibilityReview = await adapter.readResource({
+ uri: "webstudio://project/accessibility-review",
+ });
const componentsOverview = await adapter.readResource({
uri: "webstudio://project/components-overview",
});
@@ -4326,6 +5160,15 @@ describe("project session mcp adapter", () => {
]),
})
);
+ expect(accessibilityReview.contents[0]).toEqual(
+ expect.objectContaining({
+ mimeType: "text/markdown",
+ text: expect.stringContaining("# Webstudio Accessibility Review"),
+ })
+ );
+ expect(accessibilityReview.contents[0]?.text).toContain(
+ "Community-Access/accessibility-agents"
+ );
const componentOverviewData = JSON.parse(
componentsOverview.contents[0]?.text ?? "{}"
);
@@ -4843,6 +5686,64 @@ describe("project session mcp adapter", () => {
}
});
+ test("returns expected input examples for SDK zod tool errors", async () => {
+ const inputSchema = z.object({
+ email: z.email(),
+ description: z.string().min(10),
+ });
+ const parseResult = inputSchema.safeParse({
+ email: "invalid",
+ description: "short",
+ });
+ if (parseResult.success) {
+ throw new Error("Expected invalid test input");
+ }
+ const server = await createProjectSessionMcpServer({
+ operations: [
+ ...publicMcpOperations,
+ {
+ ...publicMcpOperations[0]!,
+ command: "constrained-input",
+ inputSchema: getTestInputSchema(inputSchema),
+ },
+ ],
+ createProjectSession: createSessionFactory(),
+ executeOperation: createExecuteOperation(async () => {
+ throw parseResult.error;
+ }),
+ });
+ const { client, close } = await createConnectedClient(server);
+
+ try {
+ const result = await client.callTool({
+ name: "constrained-input",
+ arguments: { email: "invalid", description: "short" },
+ });
+ expect(result).toEqual(
+ expect.objectContaining({
+ isError: true,
+ structuredContent: {
+ ok: false,
+ error: {
+ message: expect.stringContaining('"email":"[email protected]"'),
+ code: "MCP_TOOL_FAILED",
+ },
+ meta: {},
+ },
+ })
+ );
+ expect(result.structuredContent).toEqual(
+ expect.objectContaining({
+ error: expect.objectContaining({
+ message: expect.stringContaining('"description":"stringxxxx"'),
+ }),
+ })
+ );
+ } finally {
+ await close();
+ }
+ });
+
test("blocks long-lived MCP tool chains until required checkpoint is acknowledged", async () => {
const server = await createProjectSessionMcpServer({
operations: publicMcpOperations,
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index 7f27101734..97e37c44ba 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -13,8 +13,13 @@ import type { BuilderApiCapability } from "./contracts/permissions";
import path from "node:path";
import {
projectSessionBusyMessage,
+ serializeProjectSessionDebug,
+ serializeProjectSessionMeta,
type ProjectSessionEnvelope,
} from "./project-session";
+import type { ScreenshotVisualExpectation } from "./visual/screenshot-diff";
+import { isPlainRecord, isRecord } from "./shared/type-utils";
+import { augmentAuditWithRenderedChecks } from "./mcp-rendered-audit";
import {
defaultScreenshotTimeout,
defaultScreenshotWaitForTimeout,
@@ -57,6 +62,7 @@ import {
} from "./runtime/component-catalog";
import { parseWebstudioJsxFragment } from "./runtime/jsx";
import { webstudioJsxFragmentInputDescription } from "./runtime/jsx/bindings";
+import { z } from "zod";
type PublicMcpOperationMethod = "query" | "mutation";
type PublicMcpOperationPermit = BuilderApiCapability;
@@ -68,6 +74,7 @@ export type PublicMcpOperation<Command extends string = string> = {
permit: PublicMcpOperationPermit;
description: string;
inputSchema: InputJsonSchema;
+ outputSchema?: InputJsonSchema;
requiredOptions?: readonly string[];
examples?: readonly string[];
localCapable: boolean;
@@ -112,6 +119,8 @@ export type ProjectSessionScreenshotInput = {
height: number;
};
fullPage?: boolean;
+ includeImageMetrics?: boolean;
+ includeResourceMetrics?: boolean;
browser: ScreenshotBrowser;
browserPath?: string;
waitUntil?: ScreenshotWaitUntil;
@@ -131,6 +140,32 @@ export type ProjectSessionScreenshotResult = {
fullPage: boolean;
elapsedMs: number;
warnings: readonly string[];
+ layout?: {
+ viewportWidth: number;
+ viewportHeight: number;
+ contentWidth: number;
+ contentHeight: number;
+ horizontalOverflow: boolean;
+ images?: Array<{
+ instanceId?: string;
+ loading: string;
+ complete: boolean;
+ naturalWidth: number;
+ naturalHeight: number;
+ renderedWidth: number;
+ renderedHeight: number;
+ top: number;
+ }>;
+ resources?: Array<{
+ pathname: string;
+ initiatorType: string;
+ transferSize: number;
+ encodedBodySize: number;
+ decodedBodySize: number;
+ duration: number;
+ renderBlockingStatus?: string;
+ }>;
+ };
};
type McpToolProgress = {
@@ -148,6 +183,8 @@ export type ProjectSessionScreenshotDiffInput = {
outputDir: string;
threshold?: number;
ignoreTopNormalizedY?: number;
+ expectedText?: readonly string[];
+ expectedVisual?: ScreenshotVisualExpectation;
};
type DiffScreenshots = (
@@ -207,12 +244,6 @@ export type ProjectSessionMcpGuidance = {
getVisionWorkflowSummary: (options: { includeDiff: boolean }) => string;
};
-const isRecord = (value: unknown): value is Record<string, unknown> =>
- typeof value === "object" && value !== null;
-
-const isPlainRecord = (value: unknown): value is Record<string, unknown> =>
- isRecord(value) && Array.isArray(value) === false;
-
const isScreenshotBrowser = (value: unknown): value is ScreenshotBrowser =>
typeof value === "string" &&
screenshotBrowserChoices.includes(value as ScreenshotBrowser);
@@ -220,18 +251,6 @@ const isScreenshotBrowser = (value: unknown): value is ScreenshotBrowser =>
const getRequestParams = (request: unknown) =>
isRecord(request) && isRecord(request.params) ? request.params : {};
-const getProjectSessionMeta = (envelope: ProjectSessionEnvelope) => ({
- operationId: envelope.operationId,
- projectId: envelope.projectId,
- buildId: envelope.buildId,
- version: envelope.version,
- source: envelope.source,
- committed: envelope.state.committed,
- compatibility: envelope.state.compatibility,
- namespaces: envelope.namespaces,
- diagnostics: envelope.diagnostics,
-});
-
type ProjectSessionMcpInputSchema = InputJsonSchema & {
type: "object";
additionalProperties: boolean | InputJsonSchema;
@@ -545,27 +564,58 @@ const parseJsonStringForSchema = (
return value;
};
+const resolveDiscriminatedInputSchema = (
+ schema: InputJsonSchema | undefined,
+ value: unknown
+) => {
+ if (schema === undefined || isPlainRecord(value) === false) {
+ return schema;
+ }
+ const branches = [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])];
+ for (const branch of branches) {
+ const branchSchema = toInputJsonSchemaObject(branch);
+ const properties = getInputJsonSchemaProperties(branchSchema);
+ const discriminatorEntries = Object.entries(properties ?? {}).filter(
+ ([, propertySchema]) => {
+ const property = toInputJsonSchemaObject(propertySchema);
+ return property !== undefined && "const" in property;
+ }
+ );
+ if (
+ discriminatorEntries.length > 0 &&
+ discriminatorEntries.every(([field, propertySchema]) => {
+ const property = toInputJsonSchemaObject(propertySchema);
+ return property?.const === value[field];
+ })
+ ) {
+ return branchSchema;
+ }
+ }
+ return schema;
+};
+
const parseStringifiedJsonInputFields = (
input: unknown,
schema: InputJsonSchema | undefined
): unknown => {
const parsedInput = parseJsonStringForSchema(input, schema);
+ const resolvedSchema = resolveDiscriminatedInputSchema(schema, parsedInput);
if (Array.isArray(parsedInput)) {
- const prefixItems = Array.isArray(schema?.prefixItems)
- ? schema.prefixItems
+ const prefixItems = Array.isArray(resolvedSchema?.prefixItems)
+ ? resolvedSchema.prefixItems
: undefined;
return parsedInput.map((item, index) =>
parseStringifiedJsonInputFields(
item,
- toInputJsonSchemaObject(prefixItems?.[index] ?? schema?.items)
+ toInputJsonSchemaObject(prefixItems?.[index] ?? resolvedSchema?.items)
)
);
}
if (isPlainRecord(parsedInput) === false) {
return parsedInput;
}
- const properties = getInputJsonSchemaProperties(schema);
- const additionalProperties = schema?.additionalProperties;
+ const properties = getInputJsonSchemaProperties(resolvedSchema);
+ const additionalProperties = resolvedSchema?.additionalProperties;
if (properties === undefined && additionalProperties === undefined) {
return parsedInput;
}
@@ -765,6 +815,18 @@ const screenshotInputSchema = {
description:
"Capture the full page height after layout instead of only the viewport. Use this for long pages and design-system audits.",
},
+ includeImageMetrics: {
+ type: "boolean",
+ default: false,
+ description:
+ "Include per-image loading state and natural/rendered dimensions. Rendered audit enables this automatically; omit for compact ordinary screenshots.",
+ },
+ includeResourceMetrics: {
+ type: "boolean",
+ default: false,
+ description:
+ "Include sanitized Resource Timing transfer and render-blocking metadata. Rendered audit enables this automatically; omit for compact ordinary screenshots.",
+ },
browser: {
type: "string",
enum: screenshotBrowserChoices,
@@ -819,6 +881,40 @@ const screenshotInputSchema = {
required: ["viewport"],
} as const satisfies ProjectSessionMcpInputSchema;
+const statusInputSchema = {
+ ...emptyInputSchema,
+ properties: {
+ verbose: {
+ type: "boolean",
+ description:
+ "Include full namespace arrays, freshness, compatibility details, and diagnostics. Omit for the compact default response.",
+ },
+ },
+} as const satisfies ProjectSessionMcpInputSchema;
+
+const renderedAuditInputProperty = {
+ type: "boolean",
+ description:
+ "Run a rendered responsive pass through this long-lived MCP session. Cannot be combined with cursor pagination.",
+} as const;
+
+const getMcpOperationInputSchema = (
+ operation: PublicMcpOperation,
+ options: { includeRenderedAudit: boolean }
+) => {
+ const schema = getOperationInputSchema(operation);
+ if (operation.command !== "audit" || options.includeRenderedAudit === false) {
+ return schema;
+ }
+ return {
+ ...schema,
+ properties: {
+ ...schema.properties,
+ rendered: renderedAuditInputProperty,
+ },
+ } satisfies InputJsonSchema;
+};
+
const screenshotDiffInputSchema = {
...emptyInputSchema,
description:
@@ -848,6 +944,57 @@ const screenshotDiffInputSchema = {
description:
"Ignore the top fraction of the image, useful for browser chrome or status bars.",
},
+ expectedText: {
+ type: "array",
+ items: { type: "string" },
+ description:
+ "Text that OCR must find in the current screenshot. Returns pass/fail assertions plus found and missing text. Requires Tesseract OCR.",
+ },
+ expectedVisual: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ maxMismatchPercentage: {
+ type: "number",
+ minimum: 0,
+ maximum: 100,
+ description: "Fail when changed pixels exceed this percentage.",
+ },
+ minChangedRegions: {
+ type: "integer",
+ minimum: 0,
+ description: "Fail when fewer changed regions are detected.",
+ },
+ maxChangedRegions: {
+ type: "integer",
+ minimum: 0,
+ description: "Fail when more changed regions are detected.",
+ },
+ dominantColorChange: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ channel: {
+ type: "string",
+ enum: ["red", "green", "blue", "luminance"],
+ },
+ direction: {
+ type: "string",
+ enum: ["increase", "decrease"],
+ },
+ minMagnitude: {
+ type: "number",
+ minimum: 0,
+ },
+ },
+ required: ["channel", "direction"],
+ description:
+ "Expected overall dominant color or brightness direction across changed pixels.",
+ },
+ },
+ description:
+ "Quantitative visual assertions derived from pixel-diff evidence.",
+ },
},
required: ["baselinePath", "currentPath"],
} as const satisfies ProjectSessionMcpInputSchema;
@@ -921,6 +1068,7 @@ export type ProjectSessionMcpTool = {
name: string;
description: string;
inputSchema: ProjectSessionMcpInputSchema;
+ outputSchema?: InputJsonSchema;
mcpExamples?: readonly unknown[];
annotations: {
command: string;
@@ -1007,6 +1155,7 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
"preview.start": [{ host: "127.0.0.1", port: 5173, source: "session" }],
"preview.status": [{}],
"preview.stop": [{}],
+ status: [{}, { verbose: true }],
"list-pages": [{ includeFolders: true }],
"get-page-by-path": [{ path: "/pricing" }],
"list-instances": [{ pagePath: "/", maxDepth: 3 }],
@@ -1016,6 +1165,16 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
include: ["props", "styles", "children"],
},
],
+ "search-project": [
+ { query: "pricing" },
+ { query: "api.example.com", scopes: ["resources"] },
+ ],
+ audit: [
+ {},
+ { scopes: ["accessibility", "seo"] },
+ { pagePath: "/pricing", severities: ["error", "warning"] },
+ { scopes: ["accessibility"], verbose: true },
+ ],
"insert-component": [
{
parentInstanceId: "parent-id",
@@ -1058,13 +1217,31 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
mode: "expression",
},
],
+ "replace-text": [
+ {
+ find: "Start free",
+ replace: "Get started",
+ match: "exact",
+ pagePath: "/pricing",
+ limit: 20,
+ },
+ ],
+ "replace-prop-text": [
+ {
+ find: "old.example.com",
+ replace: "www.example.com",
+ match: "substring",
+ names: ["href", "code"],
+ limit: 20,
+ },
+ ],
"update-page": [
{
pageId: "page-id",
values: {
- title: '"Pricing"',
+ title: "Pricing",
meta: {
- description: '"Pricing plans"',
+ description: "Pricing plans",
},
},
},
@@ -1136,7 +1313,7 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
resource: {
name: "Posts",
method: "get",
- url: '"https://api.example.com/posts"',
+ url: "https://api.example.com/posts",
headers: [],
},
},
@@ -1144,9 +1321,10 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
resource: {
name: "Filtered Posts",
method: "get",
- url: '"https://api.example.com/posts"',
+ url: "https://api.example.com/posts",
searchParams: [
{ name: "tag", value: "filters.tag" },
+ { name: "source", value: { type: "literal", value: "website" } },
{ name: "page", value: "String(filters.page ?? 1)" },
],
headers: [{ name: "Authorization", value: '"Bearer " + auth.token' }],
@@ -1159,8 +1337,13 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
name: "Post GraphQL",
control: "graphql",
method: "post",
- url: '"https://api.example.com/graphql"',
- headers: [{ name: "Content-Type", value: '"application/json"' }],
+ 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: "body-id",
@@ -1171,7 +1354,7 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
name: "Current Date",
control: "system",
method: "get",
- url: '"/$resources/current-date"',
+ url: "/$resources/current-date",
headers: [],
},
scopeInstanceId: "body-id",
@@ -1181,7 +1364,32 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
"update-resource": [
{
resourceId: "resource-id",
- values: { url: '"https://api.example.com/posts"' },
+ values: { url: "https://api.example.com/posts" },
+ },
+ ],
+ "update-asset": [
+ {
+ assetId: "asset-id",
+ values: { description: "Team collaborating around a whiteboard" },
+ },
+ ],
+ "set-image-descriptions": [
+ {
+ updates: [
+ {
+ assetId: "hero-asset-id",
+ description: "Team collaborating around a whiteboard",
+ },
+ { assetId: "background-texture-id", decorative: true },
+ ],
+ },
+ ],
+ "replace-resource-text": [
+ {
+ find: "api.old.example.com",
+ replace: "api.example.com",
+ fields: ["url"],
+ limit: 20,
},
],
"update-styles": [
@@ -1253,6 +1461,16 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
outputDir: "visual-diff",
threshold: 0.1,
ignoreTopNormalizedY: 0,
+ expectedText: ["Pricing", "Start free"],
+ expectedVisual: {
+ maxMismatchPercentage: 2,
+ maxChangedRegions: 3,
+ dominantColorChange: {
+ channel: "luminance",
+ direction: "increase",
+ minMagnitude: 10,
+ },
+ },
},
],
"vision.install-ocr": [{ confirm: true }],
@@ -1602,8 +1820,9 @@ const sessionTools: readonly ProjectSessionMcpTool[] = [
}),
createProjectSessionMcpTool({
name: "status",
- description: "Read the current local ProjectSession status and freshness.",
- inputSchema: emptyInputSchema,
+ description:
+ "Read the current local ProjectSession status. Pass verbose true only when debugging namespace, compatibility, freshness, or diagnostic details.",
+ inputSchema: statusInputSchema,
annotations: {
command: "status",
operationId: "project-session.status",
@@ -1667,7 +1886,7 @@ const sessionTools: readonly ProjectSessionMcpTool[] = [
const screenshotTool = createProjectSessionMcpTool({
name: "screenshot",
description:
- "Capture a PNG screenshot so a vision-capable AI can inspect what was actually built, compare it with the intent, and iterate.",
+ "Capture a PNG screenshot plus rendered viewport/content dimensions and horizontal-overflow evidence so an AI can inspect what was actually built, compare it with the intent, and iterate.",
inputSchema: screenshotInputSchema,
mcpExamples: getMcpExamples("screenshot"),
annotations: {
@@ -1808,7 +2027,9 @@ type ProjectSessionMcpStructuredContent = {
ok: true;
data: unknown;
meta: {
- session?: ReturnType<typeof getProjectSessionMeta>;
+ session?:
+ | ReturnType<typeof serializeProjectSessionMeta>
+ | ReturnType<typeof serializeProjectSessionDebug>;
};
};
@@ -1832,7 +2053,7 @@ export type ProjectSessionMcpResource = {
uri: string;
name: string;
description: string;
- mimeType: "application/json";
+ mimeType: "application/json" | "text/markdown";
};
type SdkTool = {
@@ -1851,6 +2072,17 @@ type SdkTool = {
export const hiddenMcpOperationCommands = new Set<string>();
+const getMcpOutputSchema = (dataSchema: InputJsonSchema): InputJsonSchema => ({
+ type: "object",
+ properties: {
+ ok: { type: "boolean", const: true },
+ data: dataSchema,
+ meta: { type: "object", additionalProperties: true },
+ },
+ required: ["ok", "data", "meta"],
+ additionalProperties: false,
+});
+
export const listProjectSessionMcpTools = (
operations: readonly PublicMcpOperation[],
options: {
@@ -1875,7 +2107,14 @@ export const listProjectSessionMcpTools = (
inputSchema:
operation.command === "insert-fragment"
? insertFragmentMcpInputSchema
- : getOperationInputSchema(operation),
+ : getMcpOperationInputSchema(operation, {
+ includeRenderedAudit:
+ options.includeScreenshot === true &&
+ options.includePreview === true,
+ }),
+ ...(operation.outputSchema === undefined
+ ? {}
+ : { outputSchema: getMcpOutputSchema(operation.outputSchema) }),
mcpExamples: getMcpExamples(operation.command),
annotations: {
command: operation.command,
@@ -2025,6 +2264,8 @@ const capabilityAreas = [
"delete-instance",
"list-texts",
"update-text",
+ "replace-text",
+ "replace-prop-text",
"update-props",
"delete-props",
"bind-props",
@@ -2066,16 +2307,20 @@ const capabilityAreas = [
"list-resources",
"create-resource",
"update-resource",
+ "replace-resource-text",
"delete-resource",
],
},
{
area: "assets",
- goal: "Upload, replace, delete, list, and find usage of assets.",
+ goal: "Manage uploaded and system fonts, plus upload, replace, delete, list, and find usage of assets.",
tools: [
"list-assets",
+ "list-fonts",
"upload-asset",
"upload-assets",
+ "update-asset",
+ "set-image-descriptions",
"find-asset-usage",
"replace-asset",
"delete-asset",
@@ -2760,7 +3005,7 @@ const filterCapabilities = (tools: readonly ProjectSessionMcpTool[]) => {
const startupGuidance = readProjectBuildDoc("mcp-startup-guidance").trim();
const valuesVsBindingsRule =
- 'Use direct value tools for fixed text/props. Use bindings only for dynamic expressions, resources, actions, or existing scoped runtime context such as system. Parameters are internal scoped runtime values, not a public create/update/delete surface. Expression-backed fixed strings such as page metadata and resource URLs must be quoted JavaScript string literal expressions, for example "\\"Pricing\\"". Page and resource updates put changed fields under values.';
+ "Use direct value tools for fixed text/props. Use bindings only for dynamic expressions, resources, actions, or existing scoped runtime context such as system. Parameters are internal scoped runtime values, not a public create/update/delete surface. Page metadata and fixed resource URLs accept plain strings; use JavaScript expression code only when values are computed. Page and resource updates put changed fields under values.";
const getComponentStateUsage = (
states:
@@ -3418,7 +3663,7 @@ const getComponentCoverageStatus = async ({
missingParts: missing
.filter((entry) => entry.standaloneInsertable === false)
.map(toCoverageEntry),
- session: getProjectSessionMeta(envelope),
+ session: serializeProjectSessionMeta(envelope),
};
};
@@ -3556,7 +3801,7 @@ const getComponentCoverageInsertNext = async ({
nextMissingRoots: after.missingRoots.slice(0, 12),
remainingMissingRootCount: after.missingRoots.length,
},
- session: getProjectSessionMeta(insert),
+ session: serializeProjectSessionMeta(insert),
};
};
@@ -3682,6 +3927,10 @@ const getComponentDetails = (component: string) => {
const meta = componentMetas.get(component);
const stateUsage = getComponentStateUsage(meta?.states);
const animationUsage = getAnimationComponentGuidance(component);
+ const jsonLdUsage =
+ component === "JsonLd"
+ ? 'Prefer placing JsonLd inside HeadSlot. Insert it with insert-component using the HeadSlot instance as parentInstanceId and component "JsonLd". Set its code prop with update-props using type "string" and a compact JSON object or array string. Fixed values with structurally invalid JSON-LD are rejected. Run audit with the seo scope after editing to find unknown, superseded, unsupported, or incompatible Schema.org terms; vocabulary findings are warnings because custom vocabularies remain valid.'
+ : undefined;
if (entry === undefined || meta === undefined) {
return {
found: false,
@@ -3700,6 +3949,7 @@ const getComponentDetails = (component: string) => {
states: meta.states ?? [],
stateUsage,
animationUsage,
+ jsonLdUsage,
indexWithinAncestor: meta.indexWithinAncestor,
usage: [
entry.standaloneInsertable
@@ -3707,6 +3957,7 @@ const getComponentDetails = (component: string) => {
: "Do not insert this component standalone. It is a child/part component and must be created by inserting a containing root/template component.",
stateUsage,
animationUsage,
+ jsonLdUsage,
]
.filter(Boolean)
.join(" "),
@@ -3756,6 +4007,8 @@ const getMetaIndex = (
'Use components.list({"source":"all"}) for shadcn-compatible registry items, templates.list({}) for templates, components.summary for a compact catalog, components.coverage-plan for design-system/all-component tasks, components.coverage-insert-next({"pagePath":"/design-system","parentInstanceId":"root-id"}) for one checkpoint-safe coverage insertion, components.coverage-status({"pagePath":"/design-system"}) to verify progress, components.search({"brief":"radix select"}) to search, and components.get({"component":"@webstudio-is/sdk-components-react-radix:Select"}) or templates.get({"component":"@webstudio-is/sdk-components-react-radix:Select"}) for one item. Do not dump or parse webstudio://project/components unless those focused tools are insufficient.',
guide:
'Use meta.guide({"brief":"Create a design system page using every component"}) for a goal-specific workflow.',
+ accessibility:
+ "For an accessibility review, read webstudio://project/accessibility-review, run audit with scopes [accessibility], then verify changed routes with preview and screenshots.",
workflow:
'Use workflow.next({"goal":"design-system-page"}) for one bounded phase when delegated/non-streaming agents must return progress instead of silently running a broad task.',
details:
@@ -3786,7 +4039,19 @@ const getMetaGuide = (
tools: readonly ProjectSessionMcpTool[],
guidance: ProjectSessionMcpGuidance | undefined
) => {
- const matches = getMatchingTools(brief, tools).slice(0, 12);
+ const isJsonLdGoal = /json\s*-?\s*ld|structured\s+data/i.test(brief);
+ const matches = isJsonLdGoal
+ ? getExactTools(
+ [
+ "components.get",
+ "list-instances",
+ "insert-component",
+ "update-props",
+ "audit",
+ ],
+ tools
+ )
+ : getMatchingTools(brief, tools).slice(0, 12);
const canVerifyVisually =
tools.some((tool) => tool.name === "preview.start") &&
tools.some((tool) => tool.name === "screenshot");
@@ -3798,6 +4063,14 @@ const getMetaGuide = (
delegatedAgentRule:
"Do not spend the whole phase on discovery. If you are delegated/non-streaming and the parent asks for status within 30 seconds, run exactly one shortcut command such as webstudio meta.index or one explicit webstudio mcp single-op-call command, report its command/result, and wait before the next MCP command.",
workflow: [
+ ...(isJsonLdGoal
+ ? [
+ 'Call components.get with {"component":"JsonLd"}; do not use update-page custom metadata for JSON-LD.',
+ "Find the page HeadSlot instance with list-instances.",
+ 'Insert JsonLd under HeadSlot with insert-component, then set code with update-props using type "string" and a compact JSON object or array string.',
+ 'Run audit with {"scopes":["seo"],"pagePath":"<path>"} and fix any JSON-LD finding.',
+ ]
+ : []),
"Use the fewest discovery calls needed for the immediate action.",
"Call permissions or status only when the task depends on capabilities or local session freshness.",
matches.some((tool) => tool.annotations.localCapable)
@@ -3901,7 +4174,11 @@ const designSystemWorkflowPhases: Record<
"Use ws.element tags or components confirmed by components.get; do not use deprecated $.Box, $.Heading, $.Paragraph, or $.Button.",
"Return immediately after one dry-run result.",
],
- expectedReturn: ["dry-run diagnostics", "whether the JSX is valid"],
+ expectedReturn: [
+ "dry-run diagnostics",
+ "computed transaction",
+ "whether the JSX is valid",
+ ],
nextPhase: "commit-section",
},
"commit-section": {
@@ -4064,6 +4341,9 @@ const toSdkTool = (tool: ProjectSessionMcpTool): SdkTool => ({
name: tool.name,
description: tool.description,
inputSchema: tool.inputSchema,
+ ...(tool.outputSchema === undefined
+ ? {}
+ : { outputSchema: tool.outputSchema }),
annotations: {
readOnlyHint: isReadOnlyTool(tool),
destructiveHint: isDestructiveTool(tool),
@@ -4117,16 +4397,27 @@ export const listProjectSessionMcpResources =
"Concise model-facing guide for discovering and choosing Webstudio MCP tools.",
mimeType: "application/json",
},
+ {
+ uri: "webstudio://project/accessibility-review",
+ name: "Webstudio accessibility review",
+ description:
+ "Model-facing workflow for evidence-based accessibility reviews using Webstudio MCP tools and screenshots.",
+ mimeType: "text/markdown",
+ },
];
const toCallResult = (
- envelope: Parameters<typeof getProjectSessionMeta>[0]
+ envelope: Parameters<typeof serializeProjectSessionMeta>[0],
+ options: { verboseSession?: boolean } = {}
): ProjectSessionMcpToolResult => {
const structuredContent = {
ok: true as const,
data: envelope.result,
meta: {
- session: getProjectSessionMeta(envelope),
+ session:
+ options.verboseSession === true
+ ? serializeProjectSessionDebug(envelope)
+ : serializeProjectSessionMeta(envelope),
},
};
return {
@@ -4141,11 +4432,11 @@ const toCallResult = (
};
const toResourceContent = (
- envelope: Parameters<typeof getProjectSessionMeta>[0]
+ envelope: Parameters<typeof serializeProjectSessionMeta>[0]
) => ({
data: envelope.result,
meta: {
- session: getProjectSessionMeta(envelope),
+ session: serializeProjectSessionMeta(envelope),
},
});
@@ -4287,6 +4578,8 @@ const getScreenshotInput = (input: unknown): ProjectSessionScreenshotInput => {
source,
viewport: { width, height },
fullPage: input.fullPage === true,
+ includeImageMetrics: input.includeImageMetrics === true,
+ includeResourceMetrics: input.includeResourceMetrics === true,
browser,
browserPath:
typeof input.browserPath === "string" ? input.browserPath : undefined,
@@ -4297,6 +4590,68 @@ const getScreenshotInput = (input: unknown): ProjectSessionScreenshotInput => {
};
};
+const isValidScreenshotDiffVisualExpectation = (
+ value: unknown
+): value is ScreenshotVisualExpectation => {
+ if (isRecord(value) === false || Object.keys(value).length === 0) {
+ return false;
+ }
+ const numericFieldValid = (
+ key: "maxMismatchPercentage" | "minChangedRegions" | "maxChangedRegions"
+ ) => {
+ const field = value[key];
+ if (field === undefined) {
+ return true;
+ }
+ if (typeof field !== "number" || Number.isFinite(field) === false) {
+ return false;
+ }
+ if (key === "maxMismatchPercentage") {
+ return field >= 0 && field <= 100;
+ }
+ return Number.isInteger(field) && field >= 0;
+ };
+ if (
+ numericFieldValid("maxMismatchPercentage") === false ||
+ numericFieldValid("minChangedRegions") === false ||
+ numericFieldValid("maxChangedRegions") === false
+ ) {
+ return false;
+ }
+ if (
+ typeof value.minChangedRegions === "number" &&
+ typeof value.maxChangedRegions === "number" &&
+ value.minChangedRegions > value.maxChangedRegions
+ ) {
+ return false;
+ }
+ const dominantColorChange = value.dominantColorChange;
+ if (dominantColorChange !== undefined) {
+ if (
+ isRecord(dominantColorChange) === false ||
+ (dominantColorChange.channel !== "red" &&
+ dominantColorChange.channel !== "green" &&
+ dominantColorChange.channel !== "blue" &&
+ dominantColorChange.channel !== "luminance") ||
+ (dominantColorChange.direction !== "increase" &&
+ dominantColorChange.direction !== "decrease") ||
+ (dominantColorChange.minMagnitude !== undefined &&
+ (typeof dominantColorChange.minMagnitude !== "number" ||
+ Number.isFinite(dominantColorChange.minMagnitude) === false ||
+ dominantColorChange.minMagnitude < 0))
+ ) {
+ return false;
+ }
+ }
+ return Object.keys(value).every(
+ (key) =>
+ key === "maxMismatchPercentage" ||
+ key === "minChangedRegions" ||
+ key === "maxChangedRegions" ||
+ key === "dominantColorChange"
+ );
+};
+
const getScreenshotDiffInput = (
input: unknown
): ProjectSessionScreenshotDiffInput => {
@@ -4336,6 +4691,28 @@ const getScreenshotDiffInput = (
"screenshot.diff ignoreTopNormalizedY must be between 0 and 1."
);
}
+ const expectedText = input.expectedText;
+ if (
+ expectedText !== undefined &&
+ (Array.isArray(expectedText) === false ||
+ expectedText.length === 0 ||
+ expectedText.some(
+ (value) => typeof value !== "string" || value.trim().length === 0
+ ))
+ ) {
+ throw new Error(
+ "screenshot.diff expectedText must be a non-empty array of non-empty strings."
+ );
+ }
+ const expectedVisual = input.expectedVisual;
+ if (
+ expectedVisual !== undefined &&
+ isValidScreenshotDiffVisualExpectation(expectedVisual) === false
+ ) {
+ throw new Error(
+ "screenshot.diff expectedVisual must include valid maxMismatchPercentage (0-100), minChangedRegions, or maxChangedRegions values."
+ );
+ }
return {
baselinePath,
currentPath,
@@ -4345,6 +4722,8 @@ const getScreenshotDiffInput = (
: path.dirname(currentPath),
threshold,
ignoreTopNormalizedY,
+ expectedText,
+ expectedVisual,
};
};
@@ -4456,6 +4835,16 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
session ??= createProjectSession();
return session;
};
+ const executeRead = async (command: string, input: unknown) => {
+ if (operationByCommand.has(command as Command) === false) {
+ throw new Error(`Rendered audit requires the ${command} operation.`);
+ }
+ return await executeOperation({
+ command: command as Command,
+ input,
+ dryRun: false,
+ });
+ };
return {
listTools,
listResources: listProjectSessionMcpResources,
@@ -4515,6 +4904,17 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
],
};
}
+ if (uri === "webstudio://project/accessibility-review") {
+ return {
+ contents: [
+ {
+ uri,
+ mimeType: "text/markdown",
+ text: readProjectBuildDoc("accessibility-review"),
+ },
+ ],
+ };
+ }
if (uri === "webstudio://project/status") {
const session = getSession();
return {
@@ -4652,7 +5052,9 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
}
if (name === "status") {
const session = getSession();
- return toCallResult(await session.initialize());
+ return toCallResult(await session.initialize(), {
+ verboseSession: isRecord(input) && input.verbose === true,
+ });
}
if (name === "refresh") {
const session = getSession();
@@ -4711,13 +5113,56 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
if (operation === undefined) {
throw new Error(`Unknown MCP tool "${name}".`);
}
- const operationInput = getNormalizedOperationInput(operation, input);
+ const isAuditInput = name === "audit" && isRecord(input);
+ if (
+ isAuditInput &&
+ input.rendered !== undefined &&
+ typeof input.rendered !== "boolean"
+ ) {
+ throw new Error("audit input.rendered must be a boolean.");
+ }
+ const isRenderedAudit = isAuditInput && input.rendered === true;
+ if (
+ isRenderedAudit &&
+ (startPreview === undefined || captureScreenshot === undefined)
+ ) {
+ throw new Error(
+ "Rendered audit is unavailable because this MCP host does not provide preview and screenshot capabilities."
+ );
+ }
+ if (isRenderedAudit && typeof input.cursor === "string") {
+ throw new Error(
+ "Rendered audit cannot be combined with cursor pagination. Run the rendered pass once without cursor."
+ );
+ }
+ const operationInput = getNormalizedOperationInput(
+ operation,
+ isAuditInput
+ ? Object.fromEntries(
+ Object.entries(input).filter(([key]) => key !== "rendered")
+ )
+ : input
+ );
const envelope = await executeOperation({
command: name as Command,
input: operationInput,
dryRun,
});
- return toCallResult(envelope);
+ return toCallResult(
+ name === "audit"
+ ? await augmentAuditWithRenderedChecks({
+ envelope,
+ input:
+ isRenderedAudit && isRecord(operationInput)
+ ? { ...operationInput, rendered: true }
+ : operationInput,
+ executeRead,
+ startPreview,
+ captureScreenshot,
+ reportProgress: reportToolProgress,
+ })
+ : envelope
+ );
},
};
};
@@ -4744,17 +5189,127 @@ type ProjectSessionMcpErrorResult = {
};
};
+const getJsonSchemaExample = (
+ schema: InputJsonSchema | undefined,
+ depth = 0
+): unknown => {
+ if (
+ schema === undefined ||
+ typeof schema !== "object" ||
+ schema === null ||
+ depth > 4
+ ) {
+ return {};
+ }
+ if ("default" in schema && schema.default !== undefined) {
+ return schema.default;
+ }
+ if (
+ "examples" in schema &&
+ Array.isArray(schema.examples) &&
+ schema.examples.length > 0
+ ) {
+ return schema.examples[0];
+ }
+ if ("const" in schema) {
+ return schema.const;
+ }
+ if ("enum" in schema && Array.isArray(schema.enum)) {
+ return schema.enum[0];
+ }
+ if ("anyOf" in schema && Array.isArray(schema.anyOf)) {
+ return getJsonSchemaExample(schema.anyOf[0] as InputJsonSchema, depth + 1);
+ }
+ if ("oneOf" in schema && Array.isArray(schema.oneOf)) {
+ return getJsonSchemaExample(schema.oneOf[0] as InputJsonSchema, depth + 1);
+ }
+ if ("allOf" in schema && Array.isArray(schema.allOf)) {
+ const examples = schema.allOf.map((item) =>
+ getJsonSchemaExample(item as InputJsonSchema, depth + 1)
+ );
+ return examples.every(
+ (example) =>
+ typeof example === "object" &&
+ example !== null &&
+ Array.isArray(example) === false
+ )
+ ? Object.assign({}, ...examples)
+ : examples[0];
+ }
+ if (schema.type === "object") {
+ const properties = getInputJsonSchemaProperties(schema) ?? {};
+ const required = new Set(schema.required ?? []);
+ const entries = Object.entries(properties).filter(([name]) =>
+ required.has(name)
+ );
+ return Object.fromEntries(
+ entries.map(([name, property]) => [
+ name,
+ getJsonSchemaExample(property as InputJsonSchema, depth + 1),
+ ])
+ );
+ }
+ if (schema.type === "array") {
+ const minItems = schema.minItems ?? 0;
+ return Array.from({ length: minItems }, () =>
+ getJsonSchemaExample(schema.items as InputJsonSchema, depth + 1)
+ );
+ }
+ if (schema.type === "number" || schema.type === "integer") {
+ if (typeof schema.exclusiveMinimum === "number") {
+ return schema.exclusiveMinimum + 1;
+ }
+ return schema.minimum ?? 0;
+ }
+ if (schema.type === "boolean") {
+ return true;
+ }
+ if (schema.type === "string") {
+ const formatExamples: Record<string, string> = {
+ email: "[email protected]",
+ uri: "https://example.com",
+ url: "https://example.com",
+ uuid: "00000000-0000-4000-8000-000000000000",
+ date: "2026-01-01",
+ "date-time": "2026-01-01T00:00:00.000Z",
+ };
+ const base =
+ typeof schema.format === "string"
+ ? (formatExamples[schema.format] ?? "string")
+ : "string";
+ return base.padEnd(schema.minLength ?? 0, "x");
+ }
+ return {};
+};
+
+const getZodErrorMessage = (
+ error: z.ZodError,
+ inputSchema: InputJsonSchema | undefined
+) => {
+ const issues = error.issues
+ .map((issue) => {
+ const path = issue.path.join(".");
+ return path === "" ? issue.message : `${path}: ${issue.message}`;
+ })
+ .join(", ");
+ const example = getJsonSchemaExample(inputSchema);
+ return `${issues}. Expected input shape example: ${JSON.stringify(example)}`;
+};
+
const toToolErrorResult = (
error: unknown,
- getErrorCode: McpErrorCodeResolver | undefined
+ getErrorCode: McpErrorCodeResolver | undefined,
+ inputSchema?: InputJsonSchema
): ProjectSessionMcpErrorResult => {
const code = getErrorCode?.(error) ?? "MCP_TOOL_FAILED";
const message =
code === "PROJECT_SESSION_BUSY"
? projectSessionBusyMessage
- : error instanceof Error
- ? error.message
- : String(error);
+ : error instanceof z.ZodError
+ ? getZodErrorMessage(error, inputSchema)
+ : error instanceof Error
+ ? error.message
+ : String(error);
const structuredContent = {
ok: false as const,
error: {
@@ -4918,7 +5473,11 @@ export const createProjectSessionMcpServer = async <
error instanceof Error ? error.message : String(error)
}`
);
- return toToolErrorResult(error, getErrorCode);
+ return toToolErrorResult(
+ error,
+ getErrorCode,
+ core.listTools().find((tool) => tool.name === name)?.inputSchema
+ );
} finally {
if (heartbeat !== undefined) {
clearInterval(heartbeat);
diff --git a/packages/project-build/src/project-session.test.ts b/packages/project-build/src/project-session.test.ts
index 7c764bb513..a30e88757f 100644
--- a/packages/project-build/src/project-session.test.ts
+++ b/packages/project-build/src/project-session.test.ts
@@ -8,6 +8,7 @@ import {
hasProjectSessionPermit,
projectSessionBusyMessage,
redactProjectSessionValue,
+ serializeProjectSessionMeta,
} from "./project-session";
import { runtimeOperationContracts } from "./contracts/builder-runtime";
import type {
@@ -175,7 +176,7 @@ describe("project session", () => {
expect(result.source).toBe("local");
expect(result.state.committed).toBe(false);
- expect(result.namespaces.read).toEqual(["pages"]);
+ expect(result.namespaces.read).toEqual(["pages", "projectSettings"]);
expect(transport.loadedNamespaces).toEqual([]);
});
@@ -204,7 +205,7 @@ describe("project session", () => {
const result = await session.read("pages.list", { projectId: "project-1" });
expect(result.source).toBe("local");
- expect(transport.loadedNamespaces).toEqual([["pages"]]);
+ expect(transport.loadedNamespaces).toEqual([["pages", "projectSettings"]]);
expect(storage.saved).toHaveLength(1);
});
@@ -291,6 +292,17 @@ describe("project session", () => {
expect(result.source).toBe("dry-run");
expect(result.state.committed).toBe(false);
expect(result.transaction?.payload).toHaveLength(1);
+ expect(serializeProjectSessionMeta(result)).toMatchObject({
+ diagnosticCount: 1,
+ transaction: result.transaction,
+ diagnostics: [
+ {
+ level: "info",
+ code: "DRY_RUN",
+ message: "Mutation was planned locally and was not committed.",
+ },
+ ],
+ });
expect(transport.commits).toEqual([]);
expect(storage.saved).toHaveLength(0);
});
@@ -306,7 +318,7 @@ describe("project session", () => {
values: { name: "New Home" },
});
- expect(result.source).toBe("remote");
+ expect(result.source).toBe("local");
expect(result.state.committed).toBe(true);
expect(result.version).toBe(2);
expect(transport.commits).toHaveLength(1);
@@ -315,6 +327,21 @@ describe("project session", () => {
expect(
storage.saved.at(-1)?.state.pages?.pages.get("page-home")?.name
).toBe("New Home");
+ expect(storage.saved.at(-1)?.freshness.pages).toMatchObject({
+ status: "invalidated",
+ version: 2,
+ source: "local",
+ loadedAt: expect.any(String),
+ invalidatedBy: "pages.update",
+ });
+ expect(serializeProjectSessionMeta(result)).toMatchObject({
+ source: "local",
+ committed: true,
+ });
+ expect(storage.saved.at(-1)?.freshness.instances).toEqual({
+ status: "fresh",
+ version: 1,
+ });
});
test("runs generated-record create mutations on the server", async () => {
@@ -364,7 +391,7 @@ describe("project session", () => {
dataSourceId: variableId,
});
- expect(result.source).toBe("remote");
+ expect(result.source).toBe("local");
expect(result.state.committed).toBe(true);
expect(transport.commits).toHaveLength(1);
expect(transport.serverOperations).toEqual([]);
@@ -388,6 +415,40 @@ describe("project session", () => {
);
});
+ test("distinguishes locally written namespaces from additional invalidations", async () => {
+ const state = createBuilderStateFromSnapshot(build);
+ state.resources?.set("resource", {
+ id: "resource",
+ name: "Users",
+ method: "get",
+ url: '"https://example.com/users"',
+ headers: [],
+ });
+ const storage = createStorage(createPersistedSnapshot({ state }));
+ const transport = createTransport();
+ const session = createSession({ storage, transport });
+
+ await session.initialize();
+ const result = await session.mutate("resources.update", {
+ resourceId: "resource",
+ values: { name: "Customers" },
+ });
+
+ expect(result.source).toBe("local");
+ expect(result.state.committed).toBe(true);
+ expect(storage.saved.at(-1)?.freshness.resources).toMatchObject({
+ status: "invalidated",
+ version: 2,
+ source: "local",
+ invalidatedBy: "resources.update",
+ });
+ expect(storage.saved.at(-1)?.freshness.pages).toMatchObject({
+ status: "invalidated",
+ version: 1,
+ invalidatedBy: "resources.update",
+ });
+ });
+
test("refreshes required namespaces and returns conflict diagnostic", async () => {
const storage = createStorage(createPersistedSnapshot());
const transport = createTransport();
diff --git a/packages/project-build/src/project-session.ts b/packages/project-build/src/project-session.ts
index 22093a9218..73fb4dc4cd 100644
--- a/packages/project-build/src/project-session.ts
+++ b/packages/project-build/src/project-session.ts
@@ -25,6 +25,7 @@ import {
markBuilderStateNamespacesInvalidated,
markBuilderStateNamespacesStale,
type BuilderStateFreshness,
+ type BuilderStateNamespaceSource,
} from "./state/freshness";
import { applyBuilderPatchTransactions } from "./state/patch";
@@ -131,6 +132,7 @@ export type ProjectSessionEnvelope<Result = unknown> = {
projectId: string;
buildId?: string;
version?: number;
+ /** Where the returned state was materialized, independently of commit state. */
source: ProjectSessionSource;
result: Result;
state: {
@@ -148,6 +150,57 @@ export type ProjectSessionEnvelope<Result = unknown> = {
transaction?: BuilderPatchTransaction;
};
+const getNamespaceCounts = (envelope: ProjectSessionEnvelope) =>
+ Object.fromEntries(
+ Object.entries(envelope.namespaces).map(([name, values]) => [
+ name,
+ values.length,
+ ])
+ ) as Record<keyof ProjectSessionEnvelope["namespaces"], number>;
+
+export const serializeProjectSessionMeta = (
+ envelope: ProjectSessionEnvelope
+) => {
+ const diagnostics = envelope.diagnostics.map(({ level, code, message }) => ({
+ level,
+ code,
+ message,
+ }));
+ const diagnosticErrorCount = diagnostics.filter(
+ (diagnostic) => diagnostic.level === "error"
+ ).length;
+ return {
+ operationId: envelope.operationId,
+ projectId: envelope.projectId,
+ ...(envelope.buildId === undefined ? {} : { buildId: envelope.buildId }),
+ ...(envelope.version === undefined ? {} : { version: envelope.version }),
+ source: envelope.source,
+ committed: envelope.state.committed,
+ namespaceCounts: getNamespaceCounts(envelope),
+ diagnosticCount: diagnostics.length,
+ ...(diagnosticErrorCount === 0 ? {} : { diagnosticErrorCount }),
+ ...(diagnostics.length === 0 ? {} : { diagnostics }),
+ ...(envelope.state.compatibility === undefined
+ ? {}
+ : {
+ compatibilityVersion: envelope.state.compatibility.sessionVersion,
+ }),
+ ...(envelope.source !== "dry-run" || envelope.transaction === undefined
+ ? {}
+ : { transaction: envelope.transaction }),
+ };
+};
+
+export const serializeProjectSessionDebug = (
+ envelope: ProjectSessionEnvelope
+) => ({
+ ...serializeProjectSessionMeta(envelope),
+ namespaces: envelope.namespaces,
+ freshness: envelope.state.freshness,
+ compatibility: envelope.state.compatibility,
+ diagnostics: envelope.diagnostics,
+});
+
export type ProjectSessionMutationOptions = {
dryRun?: boolean;
permit?: BuilderApiCapability;
@@ -262,25 +315,37 @@ const getNamespacesNeedingRemote = (
const createFreshness = (
state: BuilderState,
- version: number
-): BuilderStateFreshness => createBuilderStateFreshness({ state, version });
+ version: number,
+ loadedAt: string,
+ source: BuilderStateNamespaceSource = "remote"
+): BuilderStateFreshness =>
+ createBuilderStateFreshness({
+ state,
+ version,
+ source,
+ loadedAt,
+ });
const mergeFreshness = ({
current,
state,
namespaces,
version,
+ loadedAt,
+ source = "remote",
}: {
current: BuilderStateFreshness | undefined;
state: BuilderState;
namespaces: readonly BuilderNamespace[];
version: number;
+ loadedAt: string;
+ source?: BuilderStateNamespaceSource;
}): BuilderStateFreshness => {
const next =
current === undefined
? createBuilderStateFreshness({ state })
: { ...current };
- const fresh = createFreshness(state, version);
+ const fresh = createFreshness(state, version, loadedAt, source);
for (const namespace of namespaces) {
next[namespace] = fresh[namespace];
}
@@ -315,6 +380,7 @@ const mergeSnapshot = ({
state,
namespaces,
version: remote.version,
+ loadedAt: new Date().toISOString(),
}),
compatibilityVersion,
compatibility,
@@ -531,7 +597,10 @@ export class ProjectSession {
id: operationId,
state: snapshot.state,
input,
- context: this.#options.runtimeContext,
+ context: {
+ ...this.#options.runtimeContext,
+ projectVersion: snapshot.version,
+ },
});
return this.createEnvelope({
source: "local",
@@ -812,7 +881,10 @@ export class ProjectSession {
id: operationId,
state: snapshot.state,
input,
- context: this.#options.runtimeContext,
+ context: {
+ ...this.#options.runtimeContext,
+ projectVersion: snapshot.version,
+ },
});
if (mutation.noop) {
return this.createEnvelope({
@@ -865,20 +937,30 @@ export class ProjectSession {
const applied = applyBuilderPatchTransactions(snapshot.state, [
transaction,
]);
+ const loadedAt = new Date().toISOString();
+ const updatedNamespaces = [
+ ...new Set(mutation.payload.map((change) => change.namespace)),
+ ];
const committedSnapshot: ProjectSessionSnapshot = {
...snapshot,
version: commit.version,
state: applied.state,
- freshness: createBuilderStateFreshness({
- state: applied.state,
- version: commit.version,
- invalidatedNamespaces: mutation.invalidatesNamespaces,
- invalidatedBy: operationId,
- }),
+ freshness: markBuilderStateNamespacesInvalidated(
+ mergeFreshness({
+ current: snapshot.freshness,
+ state: applied.state,
+ namespaces: updatedNamespaces,
+ version: commit.version,
+ loadedAt,
+ source: "local",
+ }),
+ mutation.invalidatesNamespaces,
+ operationId
+ ),
};
await this.saveSnapshot(committedSnapshot);
return this.createEnvelope({
- source: "remote",
+ source: "local",
result: mutation.result,
committed: true,
contract: {
diff --git a/packages/project-build/src/runtime/accessibility-analysis.test.ts b/packages/project-build/src/runtime/accessibility-analysis.test.ts
new file mode 100644
index 0000000000..243d2deb78
--- /dev/null
+++ b/packages/project-build/src/runtime/accessibility-analysis.test.ts
@@ -0,0 +1,85 @@
+import { expect, test } from "vitest";
+import type { Instance } from "@webstudio-is/sdk";
+import {
+ getAccessibleContentState,
+ hasAccessibleName,
+ isDynamicPropType,
+} from "./accessibility-analysis";
+
+const instances = new Map<string, Instance>([
+ [
+ "button",
+ {
+ type: "instance",
+ id: "button",
+ component: "Button",
+ children: [{ type: "id", value: "label" }],
+ },
+ ],
+ [
+ "label",
+ {
+ type: "instance",
+ id: "label",
+ component: "Text",
+ children: [{ type: "expression", value: "label" }],
+ },
+ ],
+ [
+ "image-link",
+ {
+ type: "instance",
+ id: "image-link",
+ component: "Link",
+ children: [{ type: "id", value: "image" }],
+ },
+ ],
+ [
+ "image",
+ {
+ type: "instance",
+ id: "image",
+ component: "Image",
+ children: [],
+ },
+ ],
+]);
+
+test("classifies every runtime-backed prop type as dynamic", () => {
+ expect(["expression", "parameter", "resource"].every(isDynamicPropType)).toBe(
+ true
+ );
+ expect(isDynamicPropType("string")).toBe(false);
+});
+
+test("distinguishes dynamic accessible content from static text", () => {
+ expect(getAccessibleContentState("button", instances)).toEqual({
+ hasStatic: false,
+ hasDynamic: true,
+ });
+});
+
+test("accepts dynamic accessible props without requiring a static value", () => {
+ expect(
+ hasAccessibleName({
+ instanceId: "button",
+ instances,
+ propsByInstance: new Map([
+ ["button", new Map([["aria-label", undefined]])],
+ ]),
+ propTypesByInstance: new Map([
+ ["button", new Map([["aria-label", "resource"]])],
+ ]),
+ })
+ ).toBe(true);
+});
+
+test("uses a nested image alt as the parent link accessible name", () => {
+ expect(
+ hasAccessibleName({
+ instanceId: "image-link",
+ instances,
+ propsByInstance: new Map([["image", new Map([["alt", "Portrait"]])]]),
+ })
+ ).toBe(true);
+});
diff --git a/packages/project-build/src/runtime/accessibility-analysis.ts b/packages/project-build/src/runtime/accessibility-analysis.ts
new file mode 100644
index 0000000000..27f733cd80
--- /dev/null
+++ b/packages/project-build/src/runtime/accessibility-analysis.ts
@@ -0,0 +1,106 @@
+import type { BuilderState } from "../state/builder-state";
+
+export const dynamicPropTypes = new Set([
+ "expression",
+ "parameter",
+ "resource",
+]);
+
+export const isDynamicPropType = (type: string | undefined) =>
+ type !== undefined && dynamicPropTypes.has(type);
+
+export type AccessibleContentState = {
+ hasStatic: boolean;
+ hasDynamic: boolean;
+};
+
+export const getAccessibleContentState = (
+ instanceId: string,
+ instances: NonNullable<BuilderState["instances"]>,
+ visited = new Set<string>()
+): AccessibleContentState => {
+ if (visited.has(instanceId)) {
+ return { hasStatic: false, hasDynamic: false };
+ }
+ visited.add(instanceId);
+ const instance = instances.get(instanceId);
+ if (instance === undefined) {
+ return { hasStatic: false, hasDynamic: false };
+ }
+ let hasStatic = false;
+ let hasDynamic = false;
+ for (const child of instance.children) {
+ if (child.type === "text") {
+ hasStatic ||= child.value.trim().length > 0;
+ continue;
+ }
+ if (child.type === "expression") {
+ hasDynamic = true;
+ continue;
+ }
+ const nested = getAccessibleContentState(child.value, instances, visited);
+ hasStatic ||= nested.hasStatic;
+ hasDynamic ||= nested.hasDynamic;
+ }
+ return { hasStatic, hasDynamic };
+};
+
+const hasNonEmptyValue = (value: unknown) =>
+ value !== undefined && (typeof value !== "string" || value.trim() !== "");
+
+export const hasAccessibleName = ({
+ instanceId,
+ instances,
+ propsByInstance,
+ propTypesByInstance,
+ visited = new Set<string>(),
+}: {
+ instanceId: string;
+ instances: NonNullable<BuilderState["instances"]>;
+ propsByInstance: ReadonlyMap<string, ReadonlyMap<string, unknown>>;
+ propTypesByInstance?: ReadonlyMap<string, ReadonlyMap<string, string>>;
+ visited?: Set<string>;
+}): boolean => {
+ if (visited.has(instanceId)) {
+ return false;
+ }
+ visited.add(instanceId);
+ const props = propsByInstance.get(instanceId);
+ const propTypes = propTypesByInstance?.get(instanceId);
+ const names = ["aria-label", "aria-labelledby", "title"];
+ if (
+ names.some(
+ (name) =>
+ isDynamicPropType(propTypes?.get(name)) ||
+ hasNonEmptyValue(props?.get(name))
+ )
+ ) {
+ return true;
+ }
+ const instance = instances.get(instanceId);
+ if (
+ instance !== undefined &&
+ (instance.component === "Image" || instance.tag === "img") &&
+ (isDynamicPropType(propTypes?.get("alt")) ||
+ hasNonEmptyValue(props?.get("alt")))
+ ) {
+ return true;
+ }
+ return (
+ instance?.children.some((child) => {
+ if (child.type === "text") {
+ return child.value.trim().length > 0;
+ }
+ if (child.type === "expression") {
+ return true;
+ }
+ return hasAccessibleName({
+ instanceId: child.value,
+ instances,
+ propsByInstance,
+ propTypesByInstance,
+ visited,
+ });
+ }) ?? false
+ );
+};
diff --git a/packages/project-build/src/runtime/assets.test.ts b/packages/project-build/src/runtime/assets.test.ts
index ec0cff7cc9..7959026483 100644
--- a/packages/project-build/src/runtime/assets.test.ts
+++ b/packages/project-build/src/runtime/assets.test.ts
@@ -25,6 +25,7 @@ import {
findAssetUsage,
getAssetInfoFallback,
getBrowserAssetFormat,
+ imageDescriptionsSetInput,
listAssets,
formatAssetName,
parseAssetName,
@@ -32,6 +33,7 @@ import {
replaceAsset,
replaceAssetInStyleValueMutable,
replaceAssetMutable,
+ setImageDescriptions,
updateAsset,
} from "./assets";
@@ -88,6 +90,7 @@ const pages: Pages = {
const state = {
pages,
+ projectSettings: { meta: pages.meta ?? {}, compiler: pages.compiler ?? {} },
assets: new Map([
["asset", imageAsset("asset", "asset.png")],
["next", imageAsset("next", "next.png")],
@@ -247,7 +250,7 @@ describe("asset runtime operations", () => {
test("lists assets with usage counts", () => {
expect(listAssets(state, { sort: "usage" })).toMatchObject({
items: [
- { id: "asset", usageCount: 1 },
+ { id: "asset", description: null, usageCount: 1 },
{ id: "next", usageCount: 0 },
{ id: "unused", usageCount: 0 },
],
@@ -255,6 +258,21 @@ describe("asset runtime operations", () => {
});
});
+ test("lists asset descriptions used as image alt text", () => {
+ const asset = imageAsset("described");
+ asset.description = "Team collaborating around a whiteboard";
+ expect(
+ listAssets({ ...state, assets: new Map([[asset.id, asset]]) })
+ ).toMatchObject({
+ items: [
+ {
+ id: "described",
+ description: "Team collaborating around a whiteboard",
+ },
+ ],
+ });
+ });
+
test("paginates assets and rejects invalid cursors", () => {
expect(listAssets(state, { cursor: "1", limit: 1 })).toMatchObject({
items: [{ id: "next" }],
@@ -378,7 +396,16 @@ describe("asset-info", () => {
const styles: Styles = new Map();
const assets = new Map<Asset["id"], Asset>();
- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });
+ const usages = calculateUsagesByAssetId({
+ pages,
+ projectSettings: {
+ meta: { faviconAssetId: "favicon-asset" },
+ compiler: {},
+ },
+ props,
+ styles,
+ assets,
+ });
expect(usages.get("favicon-asset")).toEqual([{ type: "favicon" }]);
});
@@ -552,7 +579,16 @@ describe("asset-info", () => {
]);
const assets = new Map<Asset["id"], Asset>();
- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });
+ const usages = calculateUsagesByAssetId({
+ pages,
+ projectSettings: {
+ meta: { faviconAssetId: "asset-1" },
+ compiler: {},
+ },
+ props,
+ styles,
+ assets,
+ });
expect(usages.get("asset-1")).toHaveLength(4);
expect(usages.get("asset-1")).toEqual([
@@ -886,6 +922,24 @@ describe("updateAsset", () => {
]);
});
+ test("does not invalidate assets when values are unchanged", () => {
+ const asset = {
+ ...imageAsset("asset-1"),
+ filename: "Hero",
+ description: "Product hero",
+ };
+ const result = updateAsset(
+ { assets: new Map([[asset.id, asset]]) },
+ {
+ assetId: asset.id,
+ values: { filename: "Hero", description: "Product hero" },
+ }
+ );
+
+ expect(result.payload).toEqual([]);
+ expect(result.invalidatesNamespaces).toEqual([]);
+ });
+
test("rejects invalid filename", () => {
expect(() =>
updateAsset(
@@ -918,6 +972,144 @@ describe("updateAsset", () => {
});
});
+describe("setImageDescriptions", () => {
+ test("strips the internally injected project id", () => {
+ expect(
+ imageDescriptionsSetInput.parse({
+ projectId: "project",
+ updates: [{ assetId: "hero", description: "Dashboard overview" }],
+ })
+ ).toEqual({
+ updates: [{ assetId: "hero", description: "Dashboard overview" }],
+ });
+ });
+
+ test("stores generated descriptions and explicit decorative markers", () => {
+ const result = setImageDescriptions(
+ {
+ assets: new Map([
+ ["hero", imageAsset("hero")],
+ ["texture", imageAsset("texture")],
+ ]),
+ },
+ {
+ updates: [
+ { assetId: "hero", description: "Product dashboard overview" },
+ { assetId: "texture", decorative: true },
+ ],
+ }
+ );
+
+ expect(result.result).toEqual({
+ updated: [
+ { assetId: "hero", decorative: false },
+ { assetId: "texture", decorative: true },
+ ],
+ });
+ expect(result.payload).toEqual([
+ {
+ namespace: "assets",
+ patches: [
+ {
+ op: "replace",
+ path: ["hero", "description"],
+ value: "Product dashboard overview",
+ },
+ {
+ op: "replace",
+ path: ["texture", "description"],
+ value: "",
+ },
+ ],
+ },
+ ]);
+ });
+
+ test("reports and invalidates only descriptions that changed", () => {
+ const result = setImageDescriptions(
+ {
+ assets: new Map([
+ [
+ "unchanged",
+ { ...imageAsset("unchanged"), description: "Already described" },
+ ],
+ ["changed", imageAsset("changed")],
+ ]),
+ },
+ {
+ updates: [
+ { assetId: "unchanged", description: "Already described" },
+ { assetId: "changed", description: "New description" },
+ ],
+ }
+ );
+
+ expect(result.result).toEqual({
+ updated: [{ assetId: "changed", decorative: false }],
+ });
+ expect(result.payload).toEqual([
+ {
+ namespace: "assets",
+ patches: [
+ {
+ op: "replace",
+ path: ["changed", "description"],
+ value: "New description",
+ },
+ ],
+ },
+ ]);
+ expect(result.invalidatesNamespaces).toEqual(["assets"]);
+ });
+
+ test("returns a complete no-op when every description is unchanged", () => {
+ const result = setImageDescriptions(
+ {
+ assets: new Map([
+ ["hero", { ...imageAsset("hero"), description: "Hero image" }],
+ ]),
+ },
+ { updates: [{ assetId: "hero", description: "Hero image" }] }
+ );
+
+ expect(result.result).toEqual({ updated: [] });
+ expect(result.payload).toEqual([]);
+ expect(result.invalidatesNamespaces).toEqual([]);
+ });
+
+ test("rejects duplicate, empty, missing, and non-image updates", () => {
+ expect(() =>
+ imageDescriptionsSetInput.parse({
+ updates: [
+ { assetId: "hero", description: "Hero" },
+ { assetId: "hero", decorative: true },
+ ],
+ })
+ ).toThrow();
+ expect(() =>
+ imageDescriptionsSetInput.parse({
+ updates: [{ assetId: "hero", description: "" }],
+ })
+ ).toThrow();
+ expect(() =>
+ setImageDescriptions(
+ { assets: new Map([["hero", imageAsset("hero")]]) },
+ { updates: [{ assetId: "missing", description: "Missing" }] }
+ )
+ ).toThrow('Image asset "missing" not found');
+ expect(() =>
+ setImageDescriptions(
+ {
+ assets: new Map([
+ ["font", { ...imageAsset("font"), type: "font" } as Asset],
+ ]),
+ },
+ { updates: [{ assetId: "font", description: "Font" }] }
+ )
+ ).toThrow('Asset "font" is not an image');
+ });
+});
+
test("creates asset usage list from project, pages, props, styles, and resources", () => {
const asset = createAsset("asset-1");
const fontAsset: Asset = {
@@ -928,8 +1120,11 @@ test("creates asset usage list from project, pages, props, styles, and resources
meta: { family: "Inter", style: "normal", weight: 400 },
};
const build = {
- pages: {
+ projectSettings: {
meta: { faviconAssetId: asset.id },
+ compiler: {},
+ },
+ pages: {
homePage: { id: "page-1" },
pages: new Map([
[
@@ -1176,7 +1371,10 @@ describe("replaceAssetInStyleValue", () => {
test("replaces asset references in pages props and styles", () => {
const pages = createDefaultPages({ rootInstanceId: "root" });
- pages.meta = { faviconAssetId: "old-id" };
+ const projectSettings = {
+ meta: { faviconAssetId: "old-id" },
+ compiler: {},
+ };
const homePage = pages.pages.get(pages.homePageId);
if (homePage === undefined) {
throw new Error("Expected home page");
@@ -1202,12 +1400,13 @@ describe("replaceAssetInStyleValue", () => {
replaceAssetMutable({
pages,
+ projectSettings,
props: [prop],
styles: [style],
replacement: { fromAssetId: "old-id", toAssetId: "new-id" },
});
- expect(pages.meta.faviconAssetId).toBe("new-id");
+ expect(projectSettings.meta.faviconAssetId).toBe("new-id");
expect(homePage.meta.socialImageAssetId).toBe("new-id");
expect(homePage.marketplace.thumbnailAssetId).toBe("new-id");
expect(prop.value).toBe("new-id");
@@ -1219,7 +1418,10 @@ describe("replaceAssetInStyleValue", () => {
test("creates asset replacement payload", () => {
const pages = createDefaultPages({ rootInstanceId: "root" });
- pages.meta = { faviconAssetId: "old-id" };
+ const projectSettings = {
+ meta: { faviconAssetId: "old-id" },
+ compiler: {},
+ };
const homePage = pages.pages.get(pages.homePageId);
if (homePage === undefined) {
throw new Error("Expected home page");
@@ -1230,6 +1432,7 @@ describe("replaceAssetInStyleValue", () => {
createAssetReplacementPayload({
build: {
pages,
+ projectSettings,
props: [
{
id: "prop",
@@ -1262,13 +1465,18 @@ describe("replaceAssetInStyleValue", () => {
})
).toEqual([
{
- namespace: "pages",
+ namespace: "projectSettings",
patches: [
{
op: "replace",
path: ["meta", "faviconAssetId"],
value: "new-id",
},
+ ],
+ },
+ {
+ namespace: "pages",
+ patches: [
{
op: "replace",
path: ["pages", pages.homePageId, "meta", "socialImageAssetId"],
@@ -1324,6 +1532,7 @@ describe("replaceAssetInStyleValue", () => {
createAssetReplacementPayload({
build: {
pages,
+ projectSettings: { meta: {}, compiler: {} },
props: [],
styles: [],
} as never,
@@ -1359,6 +1568,7 @@ describe("replaceAssetInStyleValue", () => {
createAssetReplacementPayload({
build: {
pages,
+ projectSettings: { meta: {}, compiler: {} },
props: [],
styles: [],
} as never,
diff --git a/packages/project-build/src/runtime/assets.ts b/packages/project-build/src/runtime/assets.ts
index f5b73e5b3f..0d9e9041e5 100644
--- a/packages/project-build/src/runtime/assets.ts
+++ b/packages/project-build/src/runtime/assets.ts
@@ -21,6 +21,7 @@ import {
import type { BuilderPatchChange } from "../contracts/patch";
import type { BuilderState } from "../state/builder-state";
import type { CompactBuild } from "../types";
+import type { ProjectSettings } from "../shared/project-settings";
import { throwBuilderRuntimeError } from "./errors";
import { createRuntimeMutation } from "./mutation";
import {
@@ -64,6 +65,55 @@ export const assetUpdateInput = z.object({
}),
});
+const imageDescriptionUpdate = z.union([
+ z
+ .object({
+ assetId: z.string(),
+ description: z
+ .string()
+ .trim()
+ .min(1)
+ .describe(
+ "Concise alt description generated after inspecting the rendered image in context."
+ ),
+ decorative: z.literal(false).optional(),
+ })
+ .strict(),
+ z
+ .object({
+ assetId: z.string(),
+ decorative: z
+ .literal(true)
+ .describe(
+ "Mark the image decorative and intentionally store an empty alt description."
+ ),
+ })
+ .strict(),
+]);
+
+export const imageDescriptionsSetInput = z
+ .object({
+ updates: z
+ .array(imageDescriptionUpdate)
+ .min(1)
+ .describe(
+ "Descriptions or decorative decisions for image assets reported by the accessibility audit."
+ ),
+ })
+ .superRefine(({ updates }, context) => {
+ const assetIds = new Set<string>();
+ updates.forEach(({ assetId }, index) => {
+ if (assetIds.has(assetId)) {
+ context.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["updates", index, "assetId"],
+ message: "Each image asset may be updated only once.",
+ });
+ }
+ assetIds.add(assetId);
+ });
+ });
+
export const assetAddInput = z.object({
asset: assetSchema,
});
@@ -149,19 +199,21 @@ export const replaceAssetInStyleValueMutable = (
export const replaceAssetMutable = ({
pages,
+ projectSettings,
props,
styles,
replacement,
}: {
pages?: Pages;
+ projectSettings?: ProjectSettings;
props: Iterable<Prop>;
styles: Iterable<StyleDecl>;
replacement: AssetStyleValueReplacement;
}) => {
+ if (projectSettings?.meta.faviconAssetId === replacement.fromAssetId) {
+ projectSettings.meta.faviconAssetId = replacement.toAssetId;
+ }
if (pages !== undefined) {
- if (pages.meta?.faviconAssetId === replacement.fromAssetId) {
- pages.meta.faviconAssetId = replacement.toAssetId;
- }
for (const page of getAllPages(pages)) {
if (page.meta.socialImageAssetId === replacement.fromAssetId) {
page.meta.socialImageAssetId = replacement.toAssetId;
@@ -183,11 +235,13 @@ export const replaceAssetMutable = ({
export const calculateUsagesByAssetId = ({
pages,
+ projectSettings,
props,
styles,
assets,
}: {
pages: Pages | undefined;
+ projectSettings?: ProjectSettings;
props: Props;
styles: Styles;
assets: Map<Asset["id"], Asset>;
@@ -206,8 +260,9 @@ export const calculateUsagesByAssetId = ({
}
}
- if (pages?.meta?.faviconAssetId) {
- addUsage(pages.meta.faviconAssetId, { type: "favicon" });
+ const faviconAssetId = projectSettings?.meta.faviconAssetId;
+ if (faviconAssetId) {
+ addUsage(faviconAssetId, { type: "favicon" });
}
if (pages) {
for (const page of getAllPages(pages)) {
@@ -260,7 +315,7 @@ export const calculateUsagesByAssetId = ({
type AssetReferenceBuild = Pick<
CompactBuild,
- "pages" | "props" | "styles" | "resources" | "dataSources"
+ "pages" | "projectSettings" | "props" | "styles" | "resources" | "dataSources"
>;
const getRequiredAssets = (state: Pick<BuilderState, "assets">) => {
@@ -276,11 +331,17 @@ const getRequiredAssets = (state: Pick<BuilderState, "assets">) => {
const getRequiredAssetReferenceBuild = (
state: Pick<
BuilderState,
- "pages" | "props" | "styles" | "resources" | "dataSources"
+ | "pages"
+ | "projectSettings"
+ | "props"
+ | "styles"
+ | "resources"
+ | "dataSources"
>
): AssetReferenceBuild => {
if (
state.pages === undefined ||
+ state.projectSettings === undefined ||
state.props === undefined ||
state.styles === undefined ||
state.resources === undefined ||
@@ -293,6 +354,7 @@ const getRequiredAssetReferenceBuild = (
}
return {
pages: state.pages,
+ projectSettings: state.projectSettings,
props: Array.from(state.props.values()),
styles: Array.from(state.styles.values()),
resources: Array.from(state.resources.values()),
@@ -305,11 +367,12 @@ export const createAssetReplacementPayload = ({
fromAsset,
toAsset,
}: {
- build: Pick<CompactBuild, "pages" | "props" | "styles">;
+ build: Pick<CompactBuild, "pages" | "projectSettings" | "props" | "styles">;
fromAsset: Asset;
toAsset: Asset;
}) => {
const pages = structuredClone(build.pages);
+ const projectSettings = structuredClone(build.projectSettings);
const props = new Map(
build.props.map((item) => [item.id, structuredClone(item)])
);
@@ -319,6 +382,7 @@ export const createAssetReplacementPayload = ({
replaceAssetMutable({
pages,
+ projectSettings,
props: props.values(),
styles: styles.values(),
replacement: {
@@ -331,11 +395,13 @@ export const createAssetReplacementPayload = ({
});
const pagePatches = [];
- if (build.pages.meta?.faviconAssetId !== pages.meta?.faviconAssetId) {
- pagePatches.push({
+ const projectSettingsPatches: BuilderPatchChange["patches"] = [];
+ const previousFaviconAssetId = build.projectSettings.meta.faviconAssetId;
+ if (previousFaviconAssetId !== projectSettings.meta.faviconAssetId) {
+ projectSettingsPatches.push({
op: "replace" as const,
path: ["meta", "faviconAssetId"],
- value: pages.meta?.faviconAssetId,
+ value: projectSettings.meta.faviconAssetId,
});
}
for (const page of getAllPages(build.pages)) {
@@ -391,6 +457,12 @@ export const createAssetReplacementPayload = ({
}
const payload = [];
+ if (projectSettingsPatches.length > 0) {
+ payload.push({
+ namespace: "projectSettings" as const,
+ patches: projectSettingsPatches,
+ });
+ }
if (pagePatches.length > 0) {
payload.push({ namespace: "pages" as const, patches: pagePatches });
}
@@ -484,6 +556,15 @@ export const addAsset = (
});
};
+const createAssetDescriptionPatch = (
+ asset: Asset,
+ description: string | null
+): BuilderPatchChange["patches"][number] => ({
+ op: asset.description === undefined ? "add" : "replace",
+ path: [asset.id, "description"],
+ value: description,
+});
+
export const updateAsset = (
state: Pick<BuilderState, "assets">,
input: z.infer<typeof assetUpdateInput>
@@ -519,17 +600,52 @@ export const updateAsset = (
input.values.description !== undefined &&
asset.description !== input.values.description
) {
- patches.push({
- op: asset.description === undefined ? "add" : "replace",
- path: [asset.id, "description"],
- value: input.values.description,
- });
+ patches.push(createAssetDescriptionPatch(asset, input.values.description));
}
return createRuntimeMutation({
- payload: [{ namespace: "assets", patches }],
+ payload: patches.length === 0 ? [] : [{ namespace: "assets", patches }],
result: { assetId: asset.id },
- invalidatesNamespaces: ["assets"],
+ invalidatesNamespaces: patches.length === 0 ? [] : ["assets"],
+ });
+};
+
+export const setImageDescriptions = (
+ state: Pick<BuilderState, "assets">,
+ input: z.infer<typeof imageDescriptionsSetInput>
+) => {
+ const assets = getRequiredAssets(state);
+ const patches: BuilderPatchChange["patches"] = [];
+ const updated = [];
+
+ for (const update of input.updates) {
+ const asset = findAsset(assets.values(), update.assetId);
+ if (asset === undefined) {
+ return throwBuilderRuntimeError(
+ "NOT_FOUND",
+ `Image asset "${update.assetId}" not found`
+ );
+ }
+ if (asset.type !== "image") {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ `Asset "${asset.id}" is not an image`
+ );
+ }
+ const description = update.decorative === true ? "" : update.description;
+ if (asset.description !== description) {
+ patches.push(createAssetDescriptionPatch(asset, description));
+ updated.push({
+ assetId: asset.id,
+ decorative: update.decorative === true,
+ });
+ }
+ }
+
+ return createRuntimeMutation({
+ payload: patches.length === 0 ? [] : [{ namespace: "assets", patches }],
+ result: { updated },
+ invalidatesNamespaces: patches.length === 0 ? [] : ["assets"],
});
};
@@ -587,6 +703,7 @@ const countApiOnlyAssetUsage = (build: AssetReferenceBuild, assetId: string) =>
const getAssetUsageCounts = (build: AssetReferenceBuild, assets: Asset[]) => {
const usageMap = calculateUsagesByAssetId({
pages: build.pages,
+ projectSettings: build.projectSettings,
props: new Map(build.props.map((item) => [item.id, item])),
styles: new Map(build.styles.map((item) => [getStyleDeclKey(item), item])),
assets: new Map(assets.map((asset) => [asset.id, asset])),
@@ -605,6 +722,7 @@ const getAssetUsageCounts = (build: AssetReferenceBuild, assets: Asset[]) => {
const serializeAssetSummary = (asset: Asset) => ({
id: asset.id,
name: asset.name,
+ description: asset.description,
type: asset.type,
size: asset.size,
contentType: asset.format,
@@ -692,6 +810,7 @@ export const createAssetUsageList = ({
);
const usageMap = calculateUsagesByAssetId({
pages: build.pages,
+ projectSettings: build.projectSettings,
props,
styles,
assets: new Map(assets.map((item) => [item.id, item])),
@@ -756,7 +875,13 @@ export const createAssetDeletePayload = (
export const listAssets = (
state: Pick<
BuilderState,
- "assets" | "pages" | "props" | "styles" | "resources" | "dataSources"
+ | "assets"
+ | "pages"
+ | "projectSettings"
+ | "props"
+ | "styles"
+ | "resources"
+ | "dataSources"
>,
input: {
type?: "image" | "font";
@@ -839,14 +964,26 @@ export const replaceAsset = (
toAsset,
}),
result: { fromAssetId: fromAsset.id, toAssetId: toAsset.id },
- invalidatesNamespaces: ["pages", "props", "styles", "assets"],
+ invalidatesNamespaces: [
+ "pages",
+ "projectSettings",
+ "props",
+ "styles",
+ "assets",
+ ],
});
};
export const deleteAssets = (
state: Pick<
BuilderState,
- "assets" | "pages" | "props" | "styles" | "resources" | "dataSources"
+ | "assets"
+ | "pages"
+ | "projectSettings"
+ | "props"
+ | "styles"
+ | "resources"
+ | "dataSources"
>,
input: z.infer<typeof assetDeleteInput>
) => {
diff --git a/packages/project-build/src/runtime/audit.test.ts b/packages/project-build/src/runtime/audit.test.ts
new file mode 100644
index 0000000000..a4d5b71cce
--- /dev/null
+++ b/packages/project-build/src/runtime/audit.test.ts
@@ -0,0 +1,2450 @@
+import { describe, expect, test } from "vitest";
+import {
+ type Instance,
+ type Page,
+ type Prop,
+ type StyleDecl,
+} from "@webstudio-is/sdk";
+import { executeBuilderRuntimeOperation } from "./registry";
+import { setImageDescriptions } from "./assets";
+import { analyzeProject, searchProject } from "./search";
+import { audit, auditRuleId, auditRules, normalizeAuditFinding } from "./audit";
+import type { BuilderState } from "../state/builder-state";
+import { applyBuilderPatchTransactions } from "../state/patch";
+import {
+ context,
+ expectRuntimeValidationError,
+ state,
+} from "./runtime.test-fixtures";
+
+describe("project audit and analysis", () => {
+ test("requires every emitted audit rule to be registered", () => {
+ expect(Object.keys(auditRules).sort()).toEqual(
+ [...auditRuleId.options].sort()
+ );
+ for (const [ruleId, metadata] of Object.entries(auditRules)) {
+ expect(ruleId).not.toBe("");
+ expect(metadata.explanation).not.toBe("");
+ expect(metadata.remediation).not.toBe("");
+ expect(metadata.documentationUrl).toMatch(/^https:\/\//);
+ expect(
+ normalizeAuditFinding({
+ kind: metadata.scope,
+ issue: ruleId,
+ message: "Detected issue",
+ instanceId: `${ruleId}-instance`,
+ })
+ ).toMatchObject({
+ scope: metadata.scope,
+ ruleId,
+ severity: metadata.severity,
+ message: "Detected issue",
+ explanation: metadata.explanation,
+ remediation: metadata.remediation,
+ documentationUrl: metadata.documentationUrl,
+ });
+ }
+ expect(
+ normalizeAuditFinding({
+ kind: "accessibility",
+ issue: "missing-aria-reference",
+ message: "Missing reference",
+ instanceId: "button",
+ name: "aria-labelledby",
+ })
+ ).toMatchObject({
+ scope: "accessibility",
+ ruleId: "missing-aria-reference",
+ severity: "error",
+ });
+ expect(() =>
+ normalizeAuditFinding({
+ kind: "accessibility",
+ issue: "unregistered-rule",
+ message: "Unknown issue",
+ })
+ ).toThrow(/Unregistered audit rule/);
+
+ const firstDuplicateTitle = normalizeAuditFinding({
+ kind: "seo",
+ issue: "duplicate-page-title",
+ message: "Duplicate title",
+ pageIds: ["home", "pricing"],
+ pagePaths: ["/", "/pricing"],
+ });
+ const secondDuplicateTitle = normalizeAuditFinding({
+ kind: "seo",
+ issue: "duplicate-page-title",
+ message: "Duplicate title",
+ pageIds: ["about", "contact"],
+ pagePaths: ["/about", "/contact"],
+ });
+ const firstMissingReference = normalizeAuditFinding({
+ kind: "accessibility",
+ issue: "missing-aria-reference",
+ message: "Missing reference",
+ instanceId: "button",
+ name: "aria-labelledby",
+ id: "first-label",
+ });
+ const secondMissingReference = normalizeAuditFinding({
+ kind: "accessibility",
+ issue: "missing-aria-reference",
+ message: "Missing reference",
+ instanceId: "button",
+ name: "aria-labelledby",
+ id: "second-label",
+ });
+ expect(firstDuplicateTitle.id).not.toBe(secondDuplicateTitle.id);
+ expect(firstMissingReference.id).not.toBe(secondMissingReference.id);
+ });
+
+ test("returns normalized project audit findings", () => {
+ const result = audit(
+ state,
+ {
+ scopes: ["assets", "styles"],
+ severities: ["info"],
+ limit: 1,
+ verbose: true,
+ },
+ { projectVersion: 7 }
+ );
+
+ expect(result.summary.total).toBeGreaterThan(1);
+ expect(result.summary.selectedTotal).toBe(result.summary.total);
+ expect(result.summary.bySeverity.info).toBe(result.summary.total);
+ expect(result.findings).toHaveLength(1);
+ expect(result.contractVersion).toBe(1);
+ expect(result.projectVersion).toBe(7);
+ expect(result.nextCursor).not.toBeNull();
+ expect(result.findings[0]).toMatchObject({
+ scope: expect.stringMatching(/assets|styles/),
+ severity: "info",
+ ruleId: expect.any(String),
+ explanation: expect.any(String),
+ remediation: expect.any(String),
+ location: expect.any(Object),
+ evidence: expect.any(Object),
+ });
+ expect(result.findings[0].id).toContain(result.findings[0].ruleId);
+
+ const nextResult = audit(
+ state,
+ {
+ scopes: ["assets", "styles"],
+ severities: ["info"],
+ limit: 1,
+ cursor: result.nextCursor ?? undefined,
+ verbose: true,
+ },
+ { projectVersion: 7 }
+ );
+ expect(nextResult.findings[0].id).not.toBe(result.findings[0].id);
+ expect(() =>
+ audit(
+ state,
+ {
+ scopes: ["assets", "styles"],
+ cursor: result.nextCursor ?? undefined,
+ },
+ { projectVersion: 8 }
+ )
+ ).toThrow(/cursor is stale/i);
+ expect(() =>
+ audit(
+ state,
+ {
+ scopes: ["assets"],
+ cursor: result.nextCursor ?? undefined,
+ },
+ { projectVersion: 7 }
+ )
+ ).toThrow(/cursor does not match/i);
+ });
+
+ test("runs all audit scopes deterministically without mutating state", () => {
+ const before = structuredClone(state);
+
+ const first = audit(state, { verbose: true }, { projectVersion: 11 });
+ const second = audit(state, { verbose: true }, { projectVersion: 11 });
+
+ expect(first.scopes).toEqual([
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+ ]);
+ expect(first).toEqual(second);
+ expect(new Set(first.findings.map(({ id }) => id)).size).toBe(
+ first.findings.length
+ );
+ expect(first.manualChecks.map(({ checkId }) => checkId)).toEqual([
+ "responsive-visual-review",
+ "visual-contrast-review",
+ "visual-hierarchy-review",
+ ]);
+ expect(state).toEqual(before);
+ });
+
+ test("returns compact findings by default and expands them with verbose", () => {
+ const compact = audit(
+ state,
+ { scopes: ["assets"], limit: 1 },
+ { projectVersion: 1 }
+ );
+ const verbose = audit(
+ state,
+ { scopes: ["assets"], limit: 1, verbose: true },
+ { projectVersion: 1 }
+ );
+
+ expect(compact).toMatchObject({
+ contractVersion: 1,
+ verbose: false,
+ skippedCheckCount: expect.any(Number),
+ manualCheckCount: 0,
+ renderedCheckCount: 0,
+ renderedIssueCount: 0,
+ renderedFailureCount: 0,
+ });
+ expect(compact).not.toHaveProperty("skippedChecks");
+ expect(compact).not.toHaveProperty("manualChecks");
+ expect(compact.findings[0]).not.toHaveProperty("explanation");
+ expect(compact.findings[0]).not.toHaveProperty("remediation");
+ expect(compact.findings[0]).not.toHaveProperty("evidence");
+
+ expect(verbose).toMatchObject({
+ contractVersion: 1,
+ verbose: true,
+ skippedCheckCount: compact.skippedCheckCount,
+ manualCheckCount: compact.manualCheckCount,
+ renderedCheckCount: 0,
+ renderedIssueCount: 0,
+ renderedFailureCount: 0,
+ findings: [
+ expect.objectContaining({
+ id: compact.findings[0].id,
+ explanation: expect.any(String),
+ remediation: expect.any(String),
+ evidence: expect.any(Object),
+ documentationUrl: expect.stringMatching(/^https:\/\//),
+ }),
+ ],
+ skippedChecks: expect.any(Array),
+ manualChecks: expect.any(Array),
+ renderedChecks: [],
+ renderedFailures: [],
+ });
+ });
+
+ test("validates mutually exclusive audit page selectors", () => {
+ expectRuntimeValidationError("project.audit", {
+ pageId: "home",
+ pagePath: "/",
+ });
+ expectRuntimeValidationError("project.audit", { scopes: [] });
+ expectRuntimeValidationError("project.audit", { severities: [] });
+ expectRuntimeValidationError("project.audit", { limit: 0 });
+ expect(() =>
+ audit(state, { cursor: "invalid" }, { projectVersion: 1 })
+ ).toThrow(/Invalid audit cursor/);
+ });
+
+ test("rejects unknown audit input fields at the runtime boundary", () => {
+ expect(() =>
+ executeBuilderRuntimeOperation({
+ id: "project.audit",
+ state,
+ input: { unknown: true },
+ context: { projectVersion: 1, createId: () => "unused" },
+ })
+ ).toThrow(/Unrecognized key/);
+ });
+
+ test("filters audit scopes and severities independently", () => {
+ const seo = audit(state, { scopes: ["seo"] }, { projectVersion: 1 });
+ expect(seo.findings.every((finding) => finding.scope === "seo")).toBe(true);
+ expect(seo.manualCheckCount).toBe(0);
+
+ const performance = audit(
+ state,
+ { scopes: ["performance"], verbose: true },
+ { projectVersion: 1 }
+ );
+ expect(performance.manualChecks).toEqual([
+ expect.objectContaining({ checkId: "responsive-visual-review" }),
+ ]);
+
+ const errors = audit(
+ state,
+ { severities: ["error"] },
+ { projectVersion: 1 }
+ );
+ expect(
+ errors.findings.every((finding) => finding.severity === "error")
+ ).toBe(true);
+ expect(errors.summary.total).toBeGreaterThanOrEqual(errors.findings.length);
+ expect(errors.summary.selectedTotal).toBe(errors.findings.length);
+ });
+
+ test("reports dynamic audit values as skipped checks", () => {
+ const props = new Map<string, Prop>(state.props);
+ props.set("dynamic-alt", {
+ id: "dynamic-alt",
+ instanceId: "image",
+ name: "alt",
+ type: "expression",
+ value: "product.alt",
+ });
+ const instances = new Map<string, Instance>(state.instances);
+ instances.set("image", {
+ type: "instance",
+ id: "image",
+ component: "Image",
+ tag: "img",
+ children: [],
+ });
+ instances.set("body", {
+ ...instances.get("body")!,
+ children: [
+ ...instances.get("body")!.children,
+ { type: "id", value: "image" },
+ ],
+ });
+
+ const result = audit(
+ { ...state, instances, props },
+ { scopes: ["accessibility"], pageId: "home", verbose: true },
+ { projectVersion: 1 }
+ );
+
+ expect(result.findings).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ ruleId: "missing-alt",
+ location: expect.objectContaining({ instanceId: "image" }),
+ }),
+ ])
+ );
+ expect(result.skippedChecks).toContainEqual({
+ scope: "accessibility",
+ checkId: "dynamic-accessibility-prop",
+ reason: "dynamic-value",
+ message: "alt is expression-backed and cannot be audited statically.",
+ location: { instanceId: "image", propName: "alt" },
+ });
+ });
+
+ test("reports resource, parameter, and text expression audit values as skipped", () => {
+ const instances = new Map<string, Instance>(state.instances);
+ instances.set("resource-image", {
+ type: "instance",
+ id: "resource-image",
+ component: "Image",
+ tag: "img",
+ children: [],
+ });
+ instances.set("parameter-iframe", {
+ type: "instance",
+ id: "parameter-iframe",
+ component: "HtmlEmbed",
+ tag: "iframe",
+ children: [],
+ });
+ instances.set("dynamic-button", {
+ type: "instance",
+ id: "dynamic-button",
+ component: "Button",
+ tag: "button",
+ children: [{ type: "expression", value: "buttonLabel" }],
+ });
+ instances.set("body", {
+ ...instances.get("body")!,
+ children: [
+ ...instances.get("body")!.children,
+ { type: "id", value: "resource-image" },
+ { type: "id", value: "parameter-iframe" },
+ { type: "id", value: "dynamic-button" },
+ ],
+ });
+ const props = new Map<string, Prop>(state.props);
+ props.set("resource-alt", {
+ id: "resource-alt",
+ instanceId: "resource-image",
+ name: "alt",
+ type: "resource",
+ value: "resource-id",
+ });
+ props.set("parameter-title", {
+ id: "parameter-title",
+ instanceId: "parameter-iframe",
+ name: "title",
+ type: "parameter",
+ value: "parameter-id",
+ });
+
+ const result = audit(
+ { ...state, instances, props },
+ { scopes: ["accessibility"], pageId: "home", verbose: true },
+ { projectVersion: 1 }
+ );
+
+ expect(result.findings).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ ruleId: "missing-alt",
+ location: expect.objectContaining({ instanceId: "resource-image" }),
+ }),
+ expect.objectContaining({
+ ruleId: "missing-iframe-title",
+ location: expect.objectContaining({
+ instanceId: "parameter-iframe",
+ }),
+ }),
+ expect.objectContaining({
+ ruleId: "missing-accessible-name",
+ location: expect.objectContaining({ instanceId: "dynamic-button" }),
+ }),
+ ])
+ );
+ expect(result.skippedChecks).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ checkId: "dynamic-accessibility-prop",
+ message: "alt is resource-backed and cannot be audited statically.",
+ location: { instanceId: "resource-image", propName: "alt" },
+ }),
+ expect.objectContaining({
+ checkId: "dynamic-accessibility-prop",
+ message:
+ "title is parameter-backed and cannot be audited statically.",
+ location: { instanceId: "parameter-iframe", propName: "title" },
+ }),
+ expect.objectContaining({
+ checkId: "dynamic-accessible-name",
+ location: { instanceId: "dynamic-button" },
+ }),
+ ])
+ );
+ });
+
+ test("keeps asset and style audits project-wide with a page filter", () => {
+ const result = audit(
+ state,
+ { scopes: ["assets", "styles"], pageId: "home" },
+ { projectVersion: 1 }
+ );
+
+ expect(result.pageFilter).toEqual({
+ pageId: "home",
+ pagePath: "",
+ projectWideScopes: ["assets", "styles"],
+ });
+ expect(result.findings).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ scope: "assets" }),
+ expect.objectContaining({ scope: "styles" }),
+ ])
+ );
+ });
+
+ test("searches project content and audits basic accessibility issues", () => {
+ const searchState = {
+ ...state,
+ instances: new Map<
+ string,
+ NonNullable<BuilderState["instances"]> extends Map<
+ string,
+ infer Instance
+ >
+ ? Instance
+ : never
+ >([
+ ...state.instances,
+ [
+ "image",
+ {
+ type: "instance" as const,
+ id: "image",
+ component: "Image",
+ tag: "img",
+ label: "Image",
+ children: [],
+ },
+ ],
+ [
+ "iframe",
+ {
+ type: "instance" as const,
+ id: "iframe",
+ component: "HtmlEmbed",
+ tag: "iframe",
+ children: [],
+ },
+ ],
+ [
+ "button",
+ {
+ type: "instance" as const,
+ id: "button",
+ component: "Button",
+ tag: "button",
+ children: [],
+ },
+ ],
+ [
+ "named-button",
+ {
+ type: "instance" as const,
+ id: "named-button",
+ component: "Button",
+ tag: "button",
+ children: [{ type: "text", value: "Continue" }],
+ },
+ ],
+ [
+ "link",
+ {
+ type: "instance" as const,
+ id: "link",
+ component: "Link",
+ tag: "a",
+ children: [],
+ },
+ ],
+ [
+ "role-button",
+ {
+ type: "instance" as const,
+ id: "role-button",
+ component: "Element",
+ tag: "div",
+ children: [],
+ },
+ ],
+ [
+ "image-link",
+ {
+ type: "instance" as const,
+ id: "image-link",
+ component: "Link",
+ tag: "a",
+ children: [{ type: "id", value: "linked-image" }],
+ },
+ ],
+ [
+ "linked-image",
+ {
+ type: "instance" as const,
+ id: "linked-image",
+ component: "Image",
+ tag: "img",
+ children: [],
+ },
+ ],
+ [
+ "unlabeled-input",
+ {
+ type: "instance" as const,
+ id: "unlabeled-input",
+ component: "Input",
+ tag: "input",
+ children: [],
+ },
+ ],
+ [
+ "email-label",
+ {
+ type: "instance" as const,
+ id: "email-label",
+ component: "Label",
+ tag: "label",
+ children: [{ type: "text", value: "Email address" }],
+ },
+ ],
+ [
+ "orphan-label",
+ {
+ type: "instance" as const,
+ id: "orphan-label",
+ component: "Label",
+ tag: "label",
+ children: [{ type: "text", value: "Orphaned label" }],
+ },
+ ],
+ [
+ "labeled-input",
+ {
+ type: "instance" as const,
+ id: "labeled-input",
+ component: "Input",
+ tag: "input",
+ children: [],
+ },
+ ],
+ [
+ "nested-label",
+ {
+ type: "instance" as const,
+ id: "nested-label",
+ component: "Label",
+ tag: "label",
+ children: [
+ { type: "text", value: "Accept terms" },
+ { type: "id", value: "nested-input" },
+ ],
+ },
+ ],
+ [
+ "nested-input",
+ {
+ type: "instance" as const,
+ id: "nested-input",
+ component: "Input",
+ tag: "input",
+ children: [],
+ },
+ ],
+ [
+ "hidden-input",
+ {
+ type: "instance" as const,
+ id: "hidden-input",
+ component: "Input",
+ tag: "input",
+ children: [],
+ },
+ ],
+ [
+ "skipped-heading",
+ {
+ type: "instance" as const,
+ id: "skipped-heading",
+ component: "Text",
+ tag: "h4",
+ children: [{ type: "text", value: "Skipped level" }],
+ },
+ ],
+ [
+ "body",
+ {
+ ...state.instances.get("body")!,
+ children: [
+ { type: "id", value: "heading" },
+ { type: "id", value: "skipped-heading" },
+ { type: "id", value: "role-button" },
+ ],
+ },
+ ],
+ [
+ "heading",
+ {
+ ...state.instances.get("heading")!,
+ tag: "h2",
+ },
+ ],
+ ]),
+ props: new Map([
+ ...state.props,
+ [
+ "embed",
+ {
+ id: "embed",
+ instanceId: "heading",
+ name: "code",
+ type: "string" as const,
+ value: '<iframe src="https://video.example.com/embed"></iframe>',
+ },
+ ],
+ [
+ "linked-image-alt",
+ {
+ id: "linked-image-alt",
+ instanceId: "linked-image",
+ name: "alt",
+ type: "string" as const,
+ value: "Product preview",
+ },
+ ],
+ [
+ "empty-button-label",
+ {
+ id: "empty-button-label",
+ instanceId: "button",
+ name: "aria-label",
+ type: "string" as const,
+ value: "",
+ },
+ ],
+ [
+ "role-button-role",
+ {
+ id: "role-button-role",
+ instanceId: "role-button",
+ name: "role",
+ type: "string" as const,
+ value: "button",
+ },
+ ],
+ [
+ "role-button-controls",
+ {
+ id: "role-button-controls",
+ instanceId: "role-button",
+ name: "aria-controls",
+ type: "string" as const,
+ value: "missing-panel",
+ },
+ ],
+ [
+ "empty-iframe-title",
+ {
+ id: "empty-iframe-title",
+ instanceId: "iframe",
+ name: "title",
+ type: "string" as const,
+ value: "",
+ },
+ ],
+ [
+ "labeled-input-id",
+ {
+ id: "labeled-input-id",
+ instanceId: "labeled-input",
+ name: "id",
+ type: "string" as const,
+ value: "email",
+ },
+ ],
+ [
+ "email-label-for",
+ {
+ id: "email-label-for",
+ instanceId: "email-label",
+ name: "for",
+ type: "string" as const,
+ value: "email",
+ },
+ ],
+ [
+ "orphan-label-for",
+ {
+ id: "orphan-label-for",
+ instanceId: "orphan-label",
+ name: "for",
+ type: "string" as const,
+ value: "missing-input",
+ },
+ ],
+ [
+ "hidden-input-type",
+ {
+ id: "hidden-input-type",
+ instanceId: "hidden-input",
+ name: "type",
+ type: "string" as const,
+ value: "hidden",
+ },
+ ],
+ ]),
+ } satisfies BuilderState;
+
+ expect(
+ searchProject(searchState, { query: "video.example.com" })
+ ).toMatchObject({
+ total: 1,
+ matches: [
+ {
+ kind: "prop",
+ propId: "embed",
+ instanceId: "heading",
+ name: "code",
+ },
+ ],
+ });
+ expect(
+ analyzeProject(searchState, { query: "posts", scopes: ["resources"] })
+ ).toMatchObject({
+ matches: [
+ {
+ kind: "resource",
+ resourceId: "resource",
+ url: '"/posts"',
+ },
+ ],
+ });
+ const propsWithAssetReference = new Map<string, Prop>(searchState.props);
+ propsWithAssetReference.set("asset-reference", {
+ id: "asset-reference",
+ instanceId: "heading",
+ name: "src",
+ type: "asset",
+ value: "asset",
+ });
+ expect(
+ executeBuilderRuntimeOperation({
+ id: "project.search",
+ state: { ...searchState, props: propsWithAssetReference },
+ input: { query: "next", scopes: ["assets"] },
+ context,
+ })
+ ).toMatchObject({
+ total: 1,
+ matches: [
+ {
+ kind: "asset",
+ assetId: "next",
+ },
+ ],
+ });
+ const styleSourcesWithUnusedToken = new Map(searchState.styleSources);
+ styleSourcesWithUnusedToken.set("unused-token", {
+ type: "token",
+ id: "unused-token",
+ name: "Unused token",
+ });
+ expect(
+ executeBuilderRuntimeOperation({
+ id: "project.search",
+ state: { ...searchState, styleSources: styleSourcesWithUnusedToken },
+ input: { query: "unused-token", scopes: ["styles"] },
+ context,
+ })
+ ).toMatchObject({
+ total: 1,
+ matches: [
+ {
+ kind: "design-token",
+ designTokenId: "unused-token",
+ usageCount: 0,
+ },
+ ],
+ });
+ expectRuntimeValidationError("project.search", {});
+ expectRuntimeValidationError("project.search", {
+ query: "button",
+ scopes: ["accessibility"],
+ });
+ expectRuntimeValidationError("project.search", {
+ query: "button",
+ pagePat: "/pricing",
+ });
+ expect(
+ analyzeProject(searchState, { query: "BRAND", scopes: ["styles"] })
+ ).toMatchObject({
+ total: 1,
+ matches: [
+ {
+ kind: "design-token",
+ designTokenId: "token",
+ name: "Brand",
+ },
+ ],
+ });
+ const styleSourcesWithDuplicateToken = new Map(searchState.styleSources);
+ styleSourcesWithDuplicateToken.set("duplicate-token", {
+ type: "token",
+ id: "duplicate-token",
+ name: "Brand alias",
+ });
+ const stylesWithDuplicateToken = new Map(searchState.styles);
+ stylesWithDuplicateToken.set("duplicate-token:base::color", {
+ styleSourceId: "duplicate-token",
+ breakpointId: "base",
+ state: undefined,
+ property: "color",
+ value: { type: "keyword", value: "blue" },
+ });
+ const tokenAudit = analyzeProject(
+ {
+ ...searchState,
+ styleSources: styleSourcesWithDuplicateToken,
+ styles: stylesWithDuplicateToken,
+ },
+ { scopes: ["styles"] }
+ );
+ expect(tokenAudit.matches).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ kind: "design-token",
+ issue: "duplicate-design-token-declarations",
+ designTokenIds: ["token", "duplicate-token"],
+ names: ["Brand", "Brand alias"],
+ }),
+ ])
+ );
+ expect(analyzeProject(searchState, { scopes: ["styles"] }).matches).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ kind: "breakpoint",
+ issue: "unused-breakpoint",
+ breakpointId: "desktop",
+ label: "Desktop",
+ }),
+ ])
+ );
+ const stylesWithUnusedCssVariable = new Map<string, StyleDecl>(
+ searchState.styles
+ );
+ stylesWithUnusedCssVariable.set("local:base::--unused-color", {
+ styleSourceId: "local",
+ breakpointId: "base",
+ state: undefined,
+ property: "--unused-color",
+ value: { type: "keyword", value: "blue" },
+ });
+ const cssVariableAudit = analyzeProject(
+ { ...searchState, styles: stylesWithUnusedCssVariable },
+ { scopes: ["styles"] }
+ );
+ expect(cssVariableAudit.matches).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ kind: "css-variable",
+ issue: "unused-css-variable",
+ name: "--unused-color",
+ scope: "heading",
+ usageCount: 0,
+ }),
+ ])
+ );
+ expect(cssVariableAudit.matches).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ kind: "css-variable",
+ issue: "unused-css-variable",
+ name: "--brand-color",
+ }),
+ ])
+ );
+ const styleSourcesWithUnusedLocal = new Map(searchState.styleSources);
+ styleSourcesWithUnusedLocal.set("unused-local", {
+ type: "local",
+ id: "unused-local",
+ });
+ const stylesWithUnusedLocal = new Map<string, StyleDecl>(
+ searchState.styles
+ );
+ stylesWithUnusedLocal.set("unused-local:base::color", {
+ styleSourceId: "unused-local",
+ breakpointId: "base",
+ state: undefined,
+ property: "color",
+ value: { type: "keyword", value: "blue" },
+ });
+ const localStyleAudit = analyzeProject(
+ {
+ ...searchState,
+ styleSources: styleSourcesWithUnusedLocal,
+ styles: stylesWithUnusedLocal,
+ },
+ { scopes: ["styles"] }
+ );
+ expect(localStyleAudit.matches).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ kind: "style-source",
+ issue: "unused-local-style-source",
+ styleSourceId: "unused-local",
+ declarationCount: 1,
+ }),
+ ])
+ );
+ expect(localStyleAudit.matches).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "unused-local-style-source",
+ styleSourceId: "local",
+ }),
+ ])
+ );
+ const stylesWithDesktopDeclaration = new Map(searchState.styles);
+ stylesWithDesktopDeclaration.set("local:desktop::color", {
+ styleSourceId: "local",
+ breakpointId: "desktop",
+ state: undefined,
+ property: "color",
+ value: { type: "keyword", value: "blue" },
+ });
+ expect(
+ analyzeProject(
+ { ...searchState, styles: stylesWithDesktopDeclaration },
+ { scopes: ["styles"] }
+ ).matches
+ ).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ kind: "breakpoint",
+ issue: "unused-breakpoint",
+ breakpointId: "desktop",
+ }),
+ ])
+ );
+ expect(
+ analyzeProject(searchState, { scopes: ["accessibility"] })
+ ).toMatchObject({
+ matches: [
+ {
+ kind: "accessibility",
+ issue: "missing-alt",
+ instanceId: "image",
+ },
+ {
+ kind: "accessibility",
+ issue: "missing-iframe-title",
+ instanceId: "iframe",
+ },
+ {
+ kind: "accessibility",
+ issue: "missing-accessible-name",
+ instanceId: "button",
+ },
+ {
+ kind: "accessibility",
+ issue: "missing-accessible-name",
+ instanceId: "link",
+ },
+ {
+ kind: "accessibility",
+ issue: "missing-accessible-name",
+ instanceId: "role-button",
+ },
+ {
+ kind: "accessibility",
+ issue: "role-interactive-not-focusable",
+ instanceId: "role-button",
+ role: "button",
+ },
+ {
+ kind: "accessibility",
+ issue: "missing-form-label",
+ instanceId: "unlabeled-input",
+ },
+ {
+ kind: "accessibility",
+ issue: "invalid-label-reference",
+ instanceId: "orphan-label",
+ htmlFor: "missing-input",
+ },
+ {
+ kind: "accessibility",
+ issue: "missing-page-heading",
+ pageId: "home",
+ },
+ {
+ kind: "accessibility",
+ issue: "skipped-heading-level",
+ pageId: "home",
+ instanceId: "skipped-heading",
+ fromLevel: 2,
+ toLevel: 4,
+ },
+ {
+ kind: "accessibility",
+ issue: "missing-main-landmark",
+ pageId: "home",
+ },
+ {
+ kind: "accessibility",
+ issue: "missing-aria-reference",
+ instanceId: "role-button",
+ name: "aria-controls",
+ id: "missing-panel",
+ },
+ ],
+ });
+ expect(
+ analyzeProject(searchState, { scopes: ["accessibility"] }).matches
+ ).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "missing-accessible-name",
+ instanceId: "image-link",
+ }),
+ expect.objectContaining({
+ issue: "missing-form-label",
+ instanceId: "labeled-input",
+ }),
+ expect.objectContaining({
+ issue: "missing-form-label",
+ instanceId: "nested-input",
+ }),
+ expect.objectContaining({
+ issue: "missing-form-label",
+ instanceId: "hidden-input",
+ }),
+ ])
+ );
+
+ const instancesWithDuplicateMain = new Map<string, Instance>(
+ searchState.instances
+ );
+ instancesWithDuplicateMain.set("main-one", {
+ type: "instance",
+ id: "main-one",
+ component: "Element",
+ tag: "main",
+ children: [],
+ });
+ instancesWithDuplicateMain.set("main-two", {
+ type: "instance",
+ id: "main-two",
+ component: "Element",
+ tag: "main",
+ children: [],
+ });
+ instancesWithDuplicateMain.set("body", {
+ ...instancesWithDuplicateMain.get("body")!,
+ children: [
+ ...instancesWithDuplicateMain.get("body")!.children,
+ { type: "id", value: "main-one" },
+ { type: "id", value: "main-two" },
+ ],
+ });
+ expect(
+ analyzeProject(
+ { ...searchState, instances: instancesWithDuplicateMain },
+ { scopes: ["accessibility"], pageId: "home" }
+ ).matches
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "multiple-main-landmarks",
+ instanceIds: ["main-one", "main-two"],
+ }),
+ ])
+ );
+ });
+
+ test("does not associate form labels across page roots", () => {
+ const instances = new Map<string, Instance>(state.instances);
+ instances.set("body", {
+ ...instances.get("body")!,
+ children: [{ type: "id", value: "home-input" }],
+ });
+ instances.set("post-body", {
+ type: "instance",
+ id: "post-body",
+ component: "Body",
+ tag: "body",
+ children: [{ type: "id", value: "post-label" }],
+ });
+ instances.set("home-input", {
+ type: "instance",
+ id: "home-input",
+ component: "Input",
+ tag: "input",
+ children: [],
+ });
+ instances.set("post-label", {
+ type: "instance",
+ id: "post-label",
+ component: "Label",
+ tag: "label",
+ children: [{ type: "text", value: "Email" }],
+ });
+ const props = new Map(state.props);
+ props.set("home-input-id", {
+ id: "home-input-id",
+ instanceId: "home-input",
+ name: "id",
+ type: "string",
+ value: "email",
+ });
+ props.set("post-label-for", {
+ id: "post-label-for",
+ instanceId: "post-label",
+ name: "for",
+ type: "string",
+ value: "email",
+ });
+ const project = { ...state, instances, props } satisfies BuilderState;
+
+ expect(
+ analyzeProject(project, {
+ scopes: ["accessibility"],
+ pageId: "home",
+ }).matches
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "missing-form-label",
+ instanceId: "home-input",
+ }),
+ ])
+ );
+ expect(
+ analyzeProject(project, {
+ scopes: ["accessibility"],
+ pageId: "post",
+ }).matches
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "invalid-label-reference",
+ instanceId: "post-label",
+ }),
+ ])
+ );
+ });
+
+ test("audits deterministic keyboard, ARIA state, and autoplay media issues", () => {
+ const instances = new Map<string, Instance>(state.instances);
+ instances.set("positive-tabindex", {
+ type: "instance",
+ id: "positive-tabindex",
+ component: "Element",
+ tag: "div",
+ children: [],
+ });
+ instances.set("dynamic-tabindex", {
+ type: "instance",
+ id: "dynamic-tabindex",
+ component: "Element",
+ tag: "div",
+ children: [],
+ });
+ instances.set("invalid-aria-state", {
+ type: "instance",
+ id: "invalid-aria-state",
+ component: "Element",
+ tag: "div",
+ children: [],
+ });
+ instances.set("checkbox-role", {
+ type: "instance",
+ id: "checkbox-role",
+ component: "Element",
+ tag: "div",
+ children: [],
+ });
+ instances.set("invalid-role", {
+ type: "instance",
+ id: "invalid-role",
+ component: "Element",
+ tag: "div",
+ children: [],
+ });
+ instances.set("hidden-button", {
+ type: "instance",
+ id: "hidden-button",
+ component: "Button",
+ tag: "button",
+ children: [{ type: "text", value: "Continue" }],
+ });
+ instances.set("invalid-aria-current", {
+ type: "instance",
+ id: "invalid-aria-current",
+ component: "Link",
+ tag: "a",
+ children: [{ type: "text", value: "Current page" }],
+ });
+ instances.set("invalid-aria-number", {
+ type: "instance",
+ id: "invalid-aria-number",
+ component: "Element",
+ tag: "div",
+ children: [],
+ });
+ instances.set("dynamic-aria-number", {
+ type: "instance",
+ id: "dynamic-aria-number",
+ component: "Element",
+ tag: "div",
+ children: [],
+ });
+ instances.set("valid-aria-number", {
+ type: "instance",
+ id: "valid-aria-number",
+ component: "Element",
+ tag: "div",
+ children: [],
+ });
+ instances.set("autoplay-video", {
+ type: "instance",
+ id: "autoplay-video",
+ component: "Video",
+ tag: "video",
+ children: [],
+ });
+ instances.set("muted-autoplay-video", {
+ type: "instance",
+ id: "muted-autoplay-video",
+ component: "Video",
+ tag: "video",
+ children: [],
+ });
+ instances.set("body", {
+ ...instances.get("body")!,
+ children: [
+ ...instances.get("body")!.children,
+ { type: "id", value: "positive-tabindex" },
+ { type: "id", value: "dynamic-tabindex" },
+ { type: "id", value: "invalid-aria-state" },
+ { type: "id", value: "checkbox-role" },
+ { type: "id", value: "invalid-role" },
+ { type: "id", value: "hidden-button" },
+ { type: "id", value: "invalid-aria-current" },
+ { type: "id", value: "invalid-aria-number" },
+ { type: "id", value: "dynamic-aria-number" },
+ { type: "id", value: "valid-aria-number" },
+ { type: "id", value: "autoplay-video" },
+ { type: "id", value: "muted-autoplay-video" },
+ ],
+ });
+ const props = new Map<string, Prop>(state.props);
+ props.set("positive-tabindex-value", {
+ id: "positive-tabindex-value",
+ instanceId: "positive-tabindex",
+ name: "tabindex",
+ type: "number",
+ value: 1,
+ });
+ props.set("dynamic-tabindex-value", {
+ id: "dynamic-tabindex-value",
+ instanceId: "dynamic-tabindex",
+ name: "tabindex",
+ type: "expression",
+ value: "tabIndex",
+ });
+ props.set("invalid-aria-expanded", {
+ id: "invalid-aria-expanded",
+ instanceId: "invalid-aria-state",
+ name: "aria-expanded",
+ type: "string",
+ value: "sometimes",
+ });
+ props.set("checkbox-role", {
+ id: "checkbox-role",
+ instanceId: "checkbox-role",
+ name: "role",
+ type: "string",
+ value: "checkbox",
+ });
+ props.set("checkbox-role-pressed", {
+ id: "checkbox-role-pressed",
+ instanceId: "checkbox-role",
+ name: "aria-pressed",
+ type: "string",
+ value: "true",
+ });
+ props.set("invalid-role-value", {
+ id: "invalid-role-value",
+ instanceId: "invalid-role",
+ name: "role",
+ type: "string",
+ value: "not-a-real-role",
+ });
+ props.set("autoplay-video-value", {
+ id: "autoplay-video-value",
+ instanceId: "autoplay-video",
+ name: "autoplay",
+ type: "boolean",
+ value: true,
+ });
+ props.set("hidden-button-aria-hidden", {
+ id: "hidden-button-aria-hidden",
+ instanceId: "hidden-button",
+ name: "aria-hidden",
+ type: "boolean",
+ value: true,
+ });
+ props.set("invalid-aria-current-value", {
+ id: "invalid-aria-current-value",
+ instanceId: "invalid-aria-current",
+ name: "aria-current",
+ type: "string",
+ value: "today",
+ });
+ props.set("invalid-aria-number-value", {
+ id: "invalid-aria-number-value",
+ instanceId: "invalid-aria-number",
+ name: "aria-valuenow",
+ type: "string",
+ value: "unknown",
+ });
+ props.set("dynamic-aria-number-value", {
+ id: "dynamic-aria-number-value",
+ instanceId: "dynamic-aria-number",
+ name: "aria-valuenow",
+ type: "expression",
+ value: "progress.value",
+ });
+ props.set("valid-aria-number-value", {
+ id: "valid-aria-number-value",
+ instanceId: "valid-aria-number",
+ name: "aria-valuenow",
+ type: "string",
+ value: "1.5e2",
+ });
+ props.set("muted-autoplay-video-value", {
+ id: "muted-autoplay-video-value",
+ instanceId: "muted-autoplay-video",
+ name: "autoplay",
+ type: "boolean",
+ value: true,
+ });
+ props.set("muted-autoplay-video-muted", {
+ id: "muted-autoplay-video-muted",
+ instanceId: "muted-autoplay-video",
+ name: "muted",
+ type: "boolean",
+ value: true,
+ });
+
+ const matches = analyzeProject(
+ { ...state, instances, props },
+ { scopes: ["accessibility"], pageId: "home" }
+ ).matches;
+ expect(matches).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "positive-tabindex",
+ instanceId: "positive-tabindex",
+ tabindex: 1,
+ }),
+ expect.objectContaining({
+ issue: "invalid-aria-state",
+ instanceId: "invalid-aria-state",
+ name: "aria-expanded",
+ value: "sometimes",
+ }),
+ expect.objectContaining({
+ issue: "unsupported-aria-role-property",
+ instanceId: "checkbox-role",
+ role: "checkbox",
+ name: "aria-pressed",
+ }),
+ expect.objectContaining({
+ issue: "missing-required-aria-role-property",
+ instanceId: "checkbox-role",
+ role: "checkbox",
+ name: "aria-checked",
+ }),
+ expect.objectContaining({
+ issue: "invalid-aria-role",
+ instanceId: "invalid-role",
+ role: "not-a-real-role",
+ }),
+ expect.objectContaining({
+ issue: "autoplay-media-with-sound",
+ instanceId: "autoplay-video",
+ }),
+ expect.objectContaining({
+ issue: "aria-hidden-focusable",
+ instanceId: "hidden-button",
+ }),
+ expect.objectContaining({
+ issue: "invalid-aria-state",
+ instanceId: "invalid-aria-current",
+ name: "aria-current",
+ value: "today",
+ }),
+ expect.objectContaining({
+ issue: "invalid-aria-number",
+ instanceId: "invalid-aria-number",
+ name: "aria-valuenow",
+ value: "unknown",
+ }),
+ ])
+ );
+ expect(matches).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ instanceId: "dynamic-tabindex" }),
+ expect.objectContaining({ instanceId: "dynamic-aria-number" }),
+ expect.objectContaining({ instanceId: "valid-aria-number" }),
+ expect.objectContaining({ instanceId: "muted-autoplay-video" }),
+ ])
+ );
+ });
+
+ test("audits image submit inputs without an alt label", () => {
+ const instances = new Map<string, Instance>(state.instances);
+ instances.set("image-submit", {
+ type: "instance",
+ id: "image-submit",
+ component: "Input",
+ tag: "input",
+ children: [],
+ });
+ instances.set("labelled-image-submit", {
+ type: "instance",
+ id: "labelled-image-submit",
+ component: "Input",
+ tag: "input",
+ children: [],
+ });
+ instances.set("body", {
+ ...instances.get("body")!,
+ children: [
+ ...instances.get("body")!.children,
+ { type: "id", value: "image-submit" },
+ { type: "id", value: "labelled-image-submit" },
+ ],
+ });
+ const props = new Map<string, Prop>(state.props);
+ props.set("image-submit-type", {
+ id: "image-submit-type",
+ instanceId: "image-submit",
+ name: "type",
+ type: "string",
+ value: "image",
+ });
+ props.set("labelled-image-submit-type", {
+ id: "labelled-image-submit-type",
+ instanceId: "labelled-image-submit",
+ name: "type",
+ type: "string",
+ value: "image",
+ });
+ props.set("labelled-image-submit-alt", {
+ id: "labelled-image-submit-alt",
+ instanceId: "labelled-image-submit",
+ name: "alt",
+ type: "string",
+ value: "Search",
+ });
+
+ const matches = analyzeProject(
+ { ...state, instances, props },
+ { scopes: ["accessibility"], pageId: "home" }
+ ).matches;
+ expect(matches).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "missing-image-input-alt",
+ instanceId: "image-submit",
+ }),
+ ])
+ );
+ expect(matches).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "missing-image-input-alt",
+ instanceId: "labelled-image-submit",
+ }),
+ ])
+ );
+ });
+
+ test("audits missing asset descriptions and accepts decorative images", () => {
+ const instances = new Map<string, Instance>(state.instances);
+ instances.set("asset-image", {
+ type: "instance",
+ id: "asset-image",
+ component: "Image",
+ tag: "img",
+ children: [],
+ });
+ instances.set("decorative-image", {
+ type: "instance",
+ id: "decorative-image",
+ component: "Image",
+ tag: "img",
+ children: [],
+ });
+ instances.set("dynamic-image", {
+ type: "instance",
+ id: "dynamic-image",
+ component: "Image",
+ tag: "img",
+ children: [],
+ });
+ instances.set("body", {
+ ...instances.get("body")!,
+ children: [
+ ...instances.get("body")!.children,
+ { type: "id", value: "asset-image" },
+ { type: "id", value: "decorative-image" },
+ { type: "id", value: "dynamic-image" },
+ ],
+ });
+ const props = new Map<string, Prop>(state.props);
+ props.set("asset-image-alt", {
+ id: "asset-image-alt",
+ instanceId: "asset-image",
+ name: "alt",
+ type: "asset",
+ value: "asset",
+ });
+ props.set("decorative-image-alt", {
+ id: "decorative-image-alt",
+ instanceId: "decorative-image",
+ name: "alt",
+ type: "string",
+ value: "",
+ });
+ props.set("dynamic-image-alt", {
+ id: "dynamic-image-alt",
+ instanceId: "dynamic-image",
+ name: "alt",
+ type: "expression",
+ value: "imageAlt",
+ });
+ const project = { ...state, instances, props } satisfies BuilderState;
+
+ expect(
+ audit(
+ project,
+ { scopes: ["accessibility"], pageId: "home", verbose: true },
+ { projectVersion: 1 }
+ ).findings
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ ruleId: "missing-image-description",
+ severity: "warning",
+ location: expect.objectContaining({
+ instanceId: "asset-image",
+ assetId: "asset",
+ }),
+ }),
+ ])
+ );
+ expect(
+ analyzeProject(project, {
+ scopes: ["accessibility"],
+ pageId: "home",
+ }).matches
+ ).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "missing-image-description",
+ instanceId: "decorative-image",
+ }),
+ expect.objectContaining({
+ issue: "missing-image-description",
+ instanceId: "dynamic-image",
+ }),
+ ])
+ );
+
+ const mutation = setImageDescriptions(project, {
+ updates: [
+ {
+ assetId: "asset",
+ description: "Team collaborating around a whiteboard",
+ },
+ ],
+ });
+ const { state: updatedProject } = applyBuilderPatchTransactions(project, [
+ { id: "describe-image", payload: mutation.payload },
+ ]);
+ expect(
+ analyzeProject(updatedProject, {
+ scopes: ["accessibility"],
+ pageId: "home",
+ }).matches
+ ).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "missing-image-description",
+ instanceId: "asset-image",
+ }),
+ ])
+ );
+
+ const decorativeMutation = setImageDescriptions(project, {
+ updates: [{ assetId: "asset", decorative: true }],
+ });
+ const { state: decorativeProject } = applyBuilderPatchTransactions(
+ project,
+ [{ id: "mark-image-decorative", payload: decorativeMutation.payload }]
+ );
+ expect(decorativeProject.assets?.get("asset")?.description).toBe("");
+ expect(
+ analyzeProject(decorativeProject, {
+ scopes: ["accessibility"],
+ pageId: "home",
+ }).matches
+ ).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "missing-image-description",
+ instanceId: "asset-image",
+ }),
+ ])
+ );
+ });
+
+ test("audits pages missing SEO descriptions", () => {
+ expect(analyzeProject(state, { scopes: ["seo"] })).toMatchObject({
+ total: 1,
+ matches: [
+ {
+ kind: "seo",
+ issue: "missing-page-description",
+ pageId: "home",
+ pagePath: "",
+ },
+ ],
+ });
+ expect(
+ analyzeProject(state, { scopes: ["seo"], pagePath: "/blog/post" })
+ ).toMatchObject({ total: 0, matches: [] });
+
+ const pages = new Map<string, Page>(state.pages.pages);
+ pages.set("post", {
+ ...pages.get("post")!,
+ meta: {
+ ...pages.get("post")!.meta,
+ socialImageAssetId: "missing-asset",
+ },
+ });
+ const stateWithMissingSocialImage = {
+ ...state,
+ pages: { ...state.pages, pages },
+ } satisfies BuilderState;
+ expect(
+ analyzeProject(stateWithMissingSocialImage, {
+ scopes: ["seo"],
+ pageId: "post",
+ })
+ ).toMatchObject({
+ total: 1,
+ matches: [
+ {
+ kind: "seo",
+ issue: "missing-social-image-asset",
+ pageId: "post",
+ assetId: "missing-asset",
+ },
+ ],
+ });
+
+ pages.set("post", {
+ ...pages.get("post")!,
+ meta: {
+ ...pages.get("post")!.meta,
+ description: JSON.stringify(" "),
+ socialImageAssetId: undefined,
+ },
+ });
+ expect(
+ analyzeProject(
+ { ...state, pages: { ...state.pages, pages } },
+ { scopes: ["seo"], pageId: "post" }
+ )
+ ).toMatchObject({
+ total: 1,
+ matches: [
+ {
+ kind: "seo",
+ issue: "empty-page-description",
+ pageId: "post",
+ },
+ ],
+ });
+
+ pages.set("post", {
+ ...pages.get("post")!,
+ title: JSON.stringify(" "),
+ meta: {
+ ...pages.get("post")!.meta,
+ description: JSON.stringify("Post description"),
+ },
+ });
+ expect(
+ analyzeProject(
+ { ...state, pages: { ...state.pages, pages } },
+ { scopes: ["seo"], pageId: "post" }
+ )
+ ).toMatchObject({
+ total: 1,
+ matches: [
+ {
+ kind: "seo",
+ issue: "empty-page-title",
+ pageId: "post",
+ },
+ ],
+ });
+
+ pages.set("post", {
+ ...pages.get("post")!,
+ title: JSON.stringify("Post"),
+ meta: {
+ ...pages.get("post")!.meta,
+ language: JSON.stringify("not a locale"),
+ },
+ });
+ expect(
+ analyzeProject(
+ { ...state, pages: { ...state.pages, pages } },
+ { scopes: ["seo"], pageId: "post" }
+ )
+ ).toMatchObject({
+ total: 1,
+ matches: [
+ {
+ kind: "seo",
+ issue: "invalid-page-language",
+ pageId: "post",
+ language: "not a locale",
+ },
+ ],
+ });
+ });
+
+ test("audits static and dynamic JSON-LD", () => {
+ const instances = new Map<string, Instance>(state.instances);
+ instances.set("json-ld", {
+ type: "instance",
+ id: "json-ld",
+ component: "JsonLd",
+ children: [],
+ });
+ instances.set("body", {
+ ...instances.get("body")!,
+ children: [
+ ...instances.get("body")!.children,
+ { type: "id", value: "json-ld" },
+ ],
+ });
+ const props = new Map<string, Prop>(state.props);
+ props.set("json-ld-code", {
+ id: "json-ld-code",
+ instanceId: "json-ld",
+ name: "code",
+ type: "string",
+ value: "not json",
+ });
+ const project = { ...state, instances, props } satisfies BuilderState;
+
+ expect(
+ audit(
+ project,
+ { scopes: ["seo"], pagePath: "/", verbose: true },
+ { projectVersion: 1 }
+ ).findings
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ ruleId: "invalid-json-ld",
+ severity: "error",
+ location: expect.objectContaining({
+ instanceId: "json-ld",
+ propName: "code",
+ }),
+ }),
+ ])
+ );
+
+ props.set("json-ld-code", {
+ id: "json-ld-code",
+ instanceId: "json-ld",
+ name: "code",
+ type: "string",
+ value:
+ '{"@context":"https://schema.org","@type":"UnknownBusiness","madeUpProperty":true}',
+ });
+ expect(
+ audit(
+ project,
+ { scopes: ["seo"], pageId: "home", verbose: true },
+ { projectVersion: 1 }
+ ).findings
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ ruleId: "unknown-schema-org-type",
+ severity: "warning",
+ location: expect.objectContaining({
+ instanceId: "json-ld",
+ jsonLdPath: '$["@type"]',
+ }),
+ }),
+ expect.objectContaining({
+ ruleId: "unknown-schema-org-property",
+ severity: "warning",
+ location: expect.objectContaining({
+ instanceId: "json-ld",
+ jsonLdPath: "$.madeUpProperty",
+ }),
+ }),
+ ])
+ );
+
+ props.set("json-ld-code", {
+ id: "json-ld-code",
+ instanceId: "json-ld",
+ name: "code",
+ type: "string",
+ value: '{"@type":"Organization"}',
+ });
+ expect(
+ audit(project, { scopes: ["seo"], pageId: "home" }, { projectVersion: 1 })
+ .findings
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ ruleId: "missing-json-ld-context",
+ severity: "warning",
+ }),
+ ])
+ );
+
+ props.set("json-ld-code", {
+ id: "json-ld-code",
+ instanceId: "json-ld",
+ name: "code",
+ type: "expression",
+ value: "structuredData",
+ });
+ const dynamic = audit(
+ project,
+ { scopes: ["seo"], pageId: "home", verbose: true },
+ { projectVersion: 1 }
+ );
+ expect(dynamic.findings).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ ruleId: expect.stringMatching(/json-ld/),
+ }),
+ ])
+ );
+ expect(dynamic.skippedChecks).toContainEqual(
+ expect.objectContaining({
+ scope: "seo",
+ checkId: "dynamic-json-ld",
+ location: { instanceId: "json-ld", propName: "code" },
+ })
+ );
+ });
+
+ test("rejects JSON-LD stored as custom page metadata", () => {
+ const pages = new Map<string, Page>(state.pages.pages);
+ const home = pages.get("home")!;
+ pages.set("home", {
+ ...home,
+ meta: {
+ ...home.meta,
+ custom: [
+ {
+ property: "script:ld+json",
+ content: '{"@context":"https://schema.org"}',
+ },
+ ],
+ },
+ });
+
+ expect(
+ audit(
+ { ...state, pages: { ...state.pages, pages } },
+ { scopes: ["seo"], pageId: "home", verbose: true },
+ { projectVersion: 1 }
+ ).findings
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ ruleId: "json-ld-in-custom-metadata",
+ severity: "error",
+ location: expect.objectContaining({
+ pageId: "home",
+ pagePath: "",
+ }),
+ }),
+ ])
+ );
+ });
+
+ test("audits duplicate static HTML ids within one page", () => {
+ const props = new Map<string, Prop>(state.props);
+ props.set("body-id", {
+ id: "body-id",
+ instanceId: "body",
+ name: "id",
+ type: "string",
+ value: "duplicate-id",
+ });
+ props.set("heading-id", {
+ id: "heading-id",
+ instanceId: "heading",
+ name: "id",
+ type: "string",
+ value: "duplicate-id",
+ });
+ expect(
+ analyzeProject(
+ { ...state, props },
+ { scopes: ["accessibility"], pageId: "home" }
+ ).matches
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "duplicate-id",
+ id: "duplicate-id",
+ instanceIds: ["body", "heading"],
+ }),
+ ])
+ );
+
+ props.set("heading-id", {
+ id: "heading-id",
+ instanceId: "heading",
+ name: "id",
+ type: "expression",
+ value: "data.id",
+ });
+ expect(
+ analyzeProject(
+ { ...state, props },
+ { scopes: ["accessibility"], pageId: "home" }
+ ).matches
+ ).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ issue: "duplicate-id" }),
+ ])
+ );
+ });
+
+ test("audits missing static aria-labelledby references", () => {
+ const props = new Map<string, Prop>(state.props);
+ props.set("labelled-by", {
+ id: "labelled-by",
+ instanceId: "heading",
+ name: "aria-labelledby",
+ type: "string",
+ value: "missing-label",
+ });
+ expect(
+ analyzeProject(
+ { ...state, props },
+ { scopes: ["accessibility"], pageId: "home" }
+ ).matches
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "missing-aria-reference",
+ instanceId: "heading",
+ name: "aria-labelledby",
+ id: "missing-label",
+ }),
+ ])
+ );
+
+ props.set("labelled-by", {
+ id: "labelled-by",
+ instanceId: "heading",
+ name: "aria-labelledby",
+ type: "expression",
+ value: "data.labelId",
+ });
+ expect(
+ analyzeProject(
+ { ...state, props },
+ { scopes: ["accessibility"], pageId: "home" }
+ ).matches
+ ).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "missing-aria-reference",
+ name: "aria-labelledby",
+ }),
+ ])
+ );
+ });
+
+ test("audits missing static aria-describedby references", () => {
+ const props = new Map<string, Prop>(state.props);
+ props.set("described-by", {
+ id: "described-by",
+ instanceId: "heading",
+ name: "aria-describedby",
+ type: "string",
+ value: "missing-description",
+ });
+ expect(
+ analyzeProject(
+ { ...state, props },
+ { scopes: ["accessibility"], pageId: "home" }
+ ).matches
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "missing-aria-reference",
+ instanceId: "heading",
+ name: "aria-describedby",
+ id: "missing-description",
+ }),
+ ])
+ );
+ });
+
+ test("audits missing static ARIA ID references", () => {
+ const props = new Map<string, Prop>(state.props);
+ const names = [
+ "aria-activedescendant",
+ "aria-details",
+ "aria-errormessage",
+ "aria-flowto",
+ "aria-owns",
+ ];
+ for (const name of names) {
+ props.set(name, {
+ id: name,
+ instanceId: "heading",
+ name,
+ type: "string",
+ value: `missing-${name}`,
+ });
+ }
+
+ const matches = analyzeProject(
+ { ...state, props },
+ { scopes: ["accessibility"], pageId: "home" }
+ ).matches;
+ for (const name of names) {
+ expect(matches).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "missing-aria-reference",
+ instanceId: "heading",
+ name,
+ id: `missing-${name}`,
+ }),
+ ])
+ );
+ }
+ });
+
+ test("audits static new-tab links without opener protection", () => {
+ const instances = new Map<string, Instance>(state.instances);
+ instances.set("new-tab-link", {
+ type: "instance",
+ id: "new-tab-link",
+ component: "Link",
+ tag: "a",
+ children: [{ type: "text", value: "External site" }],
+ });
+ instances.set("body", {
+ ...instances.get("body")!,
+ children: [
+ ...instances.get("body")!.children,
+ { type: "id", value: "new-tab-link" },
+ ],
+ });
+ const props = new Map<string, Prop>(state.props);
+ props.set("new-tab-target", {
+ id: "new-tab-target",
+ instanceId: "new-tab-link",
+ name: "target",
+ type: "string",
+ value: "_blank",
+ });
+ expect(
+ analyzeProject(
+ { ...state, instances, props },
+ { scopes: ["security"], pageId: "home" }
+ ).matches
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ kind: "security",
+ issue: "target-blank-without-noopener",
+ instanceId: "new-tab-link",
+ }),
+ ])
+ );
+
+ props.set("new-tab-rel", {
+ id: "new-tab-rel",
+ instanceId: "new-tab-link",
+ name: "rel",
+ type: "string",
+ value: "external noopener",
+ });
+ expect(
+ analyzeProject(
+ { ...state, instances, props },
+ { scopes: ["security"], pageId: "home" }
+ ).matches
+ ).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "target-blank-without-noopener",
+ instanceId: "new-tab-link",
+ }),
+ ])
+ );
+
+ props.set("new-tab-target", {
+ id: "new-tab-target",
+ instanceId: "new-tab-link",
+ name: "target",
+ type: "expression",
+ value: "linkTarget",
+ });
+ expect(
+ analyzeProject(
+ { ...state, instances, props },
+ { scopes: ["security"], pageId: "home" }
+ ).matches
+ ).toEqual([]);
+
+ props.set("non-link-target", {
+ id: "non-link-target",
+ instanceId: "heading",
+ name: "target",
+ type: "string",
+ value: "_blank",
+ });
+ expect(
+ analyzeProject(
+ { ...state, instances, props },
+ { scopes: ["security"], pageId: "home" }
+ ).matches
+ ).toEqual([]);
+ });
+
+ test("audits non-GET resources exposed as render-time data", () => {
+ const resources: NonNullable<BuilderState["resources"]> = new Map(
+ state.resources
+ );
+ resources.set("submit", {
+ id: "submit",
+ name: "Submit order",
+ method: "post",
+ url: `"/orders"`,
+ headers: [],
+ searchParams: [],
+ body: `order`,
+ });
+ const dataSources: NonNullable<BuilderState["dataSources"]> = new Map(
+ state.dataSources
+ );
+ dataSources.set("submit-data", {
+ id: "submit-data",
+ type: "resource",
+ name: "Submit order",
+ scopeInstanceId: "heading",
+ resourceId: "submit",
+ });
+
+ expect(
+ audit(
+ { ...state, resources, dataSources },
+ { scopes: ["security"], verbose: true },
+ { projectVersion: 1 }
+ ).findings
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ ruleId: "non-get-resource-exposed-as-data-source",
+ severity: "error",
+ location: {
+ instanceId: "heading",
+ dataSourceId: "submit-data",
+ resourceId: "submit",
+ },
+ evidence: expect.objectContaining({ method: "post" }),
+ }),
+ ])
+ );
+ });
+
+ test("audits duplicate static page titles without flagging dynamic titles", () => {
+ const pages = new Map<string, Page>(state.pages.pages);
+ pages.set("home", {
+ ...pages.get("home")!,
+ title: JSON.stringify("Home"),
+ });
+ pages.set("post", {
+ ...pages.get("post")!,
+ title: JSON.stringify(" home "),
+ });
+ const stateWithDuplicateTitles = {
+ ...state,
+ pages: { ...state.pages, pages },
+ } satisfies BuilderState;
+ expect(
+ analyzeProject(stateWithDuplicateTitles, { scopes: ["seo"] }).matches
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "duplicate-page-title",
+ title: "Home",
+ pageIds: ["home", "post"],
+ pagePaths: ["", "/post"],
+ }),
+ ])
+ );
+ expect(
+ analyzeProject(stateWithDuplicateTitles, {
+ scopes: ["seo"],
+ pageId: "home",
+ }).matches
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ issue: "duplicate-page-title" }),
+ ])
+ );
+
+ pages.set("post", {
+ ...pages.get("post")!,
+ title: "data.pageTitle",
+ });
+ expect(
+ analyzeProject(
+ { ...state, pages: { ...state.pages, pages } },
+ { scopes: ["seo"] }
+ ).matches
+ ).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ issue: "duplicate-page-title" }),
+ ])
+ );
+ });
+
+ test("audits duplicate static page descriptions without flagging dynamic descriptions", () => {
+ const pages = new Map<string, Page>(state.pages.pages);
+ pages.set("home", {
+ ...pages.get("home")!,
+ meta: {
+ ...pages.get("home")!.meta,
+ description: JSON.stringify("Product updates and releases"),
+ },
+ });
+ pages.set("post", {
+ ...pages.get("post")!,
+ meta: {
+ ...pages.get("post")!.meta,
+ description: JSON.stringify(" product updates and releases "),
+ },
+ });
+ const stateWithDuplicateDescriptions = {
+ ...state,
+ pages: { ...state.pages, pages },
+ } satisfies BuilderState;
+ expect(
+ analyzeProject(stateWithDuplicateDescriptions, { scopes: ["seo"] })
+ .matches
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "duplicate-page-description",
+ description: "Product updates and releases",
+ pageIds: ["home", "post"],
+ pagePaths: ["", "/post"],
+ }),
+ ])
+ );
+ expect(
+ analyzeProject(stateWithDuplicateDescriptions, {
+ scopes: ["seo"],
+ pageId: "home",
+ }).matches
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ issue: "duplicate-page-description" }),
+ ])
+ );
+
+ pages.set("post", {
+ ...pages.get("post")!,
+ meta: {
+ ...pages.get("post")!.meta,
+ description: "data.pageDescription",
+ },
+ });
+ expect(
+ analyzeProject(
+ { ...state, pages: { ...state.pages, pages } },
+ { scopes: ["seo"] }
+ ).matches
+ ).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ issue: "duplicate-page-description" }),
+ ])
+ );
+ });
+
+ test("audits styles assigned to a DOM-transparent Collection", () => {
+ const instances: NonNullable<BuilderState["instances"]> = new Map(
+ state.instances
+ );
+ instances.set("collection", {
+ type: "instance",
+ id: "collection",
+ component: "ws:collection",
+ children: [],
+ });
+ const styleSourceSelections: NonNullable<
+ BuilderState["styleSourceSelections"]
+ > = new Map(state.styleSourceSelections);
+ styleSourceSelections.set("collection", {
+ instanceId: "collection",
+ values: ["local"],
+ });
+
+ expect(
+ analyzeProject(
+ { ...state, instances, styleSourceSelections },
+ { scopes: ["styles"] }
+ ).matches
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ issue: "style-on-dom-transparent-component",
+ instanceId: "collection",
+ styleSourceId: "local",
+ declarationCount: 2,
+ }),
+ ])
+ );
+ });
+
+ test("does not audit a structurally base breakpoint as unused", () => {
+ const breakpoints = new Map(state.breakpoints);
+ breakpoints.delete("base");
+ breakpoints.set("imported-base-id", {
+ id: "imported-base-id",
+ label: "Base",
+ });
+
+ const result = audit(
+ { ...state, breakpoints },
+ { scopes: ["styles"], verbose: true },
+ { projectVersion: 1 }
+ );
+
+ expect(result.findings).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ ruleId: "unused-breakpoint",
+ location: expect.objectContaining({
+ breakpointId: "imported-base-id",
+ }),
+ }),
+ ])
+ );
+ });
+
+ test("audits disabled atomic CSS as a performance optimization", () => {
+ const result = audit(
+ {
+ ...state,
+ projectSettings: {
+ ...state.projectSettings,
+ compiler: { atomicStyles: false },
+ },
+ },
+ { scopes: ["performance"], verbose: true },
+ { projectVersion: 1 }
+ );
+
+ expect(result.findings).toEqual([
+ expect.objectContaining({
+ scope: "performance",
+ ruleId: "atomic-css-disabled",
+ severity: "info",
+ evidence: { atomicStyles: false },
+ documentationUrl:
+ "https://docs.webstudio.is/university/foundations/project-settings#atomic-css",
+ }),
+ ]);
+ });
+});
diff --git a/packages/project-build/src/runtime/audit.ts b/packages/project-build/src/runtime/audit.ts
new file mode 100644
index 0000000000..99d073c85b
--- /dev/null
+++ b/packages/project-build/src/runtime/audit.ts
@@ -0,0 +1,1123 @@
+import { isLiteralExpression } from "@webstudio-is/sdk";
+import { z } from "zod";
+import type { BuilderState } from "../state/builder-state";
+import type { BuilderRuntimeContext } from "./context";
+import { throwBuilderRuntimeError } from "./errors";
+import { getInstanceDepths } from "./instances";
+import {
+ findSerializedPageByInput,
+ getSerializedPagePath,
+ getSerializedPages,
+} from "./pages";
+import { validatePageSelector } from "./page-selector";
+import { analyzeProject } from "./search";
+import {
+ getAccessibleContentState,
+ isDynamicPropType,
+} from "./accessibility-analysis";
+
+export const auditScope = z.enum([
+ "accessibility",
+ "security",
+ "seo",
+ "assets",
+ "styles",
+ "performance",
+]);
+
+export const auditSeverity = z.enum(["error", "warning", "info"]);
+export const auditContractVersion = 1 as const;
+
+export const auditRuleId = z.enum([
+ "missing-alt",
+ "missing-image-description",
+ "missing-image-input-alt",
+ "missing-iframe-title",
+ "missing-accessible-name",
+ "missing-form-label",
+ "invalid-aria-role",
+ "unsupported-aria-role-property",
+ "missing-required-aria-role-property",
+ "role-interactive-not-focusable",
+ "aria-hidden-focusable",
+ "positive-tabindex",
+ "invalid-aria-state",
+ "invalid-aria-number",
+ "autoplay-media-with-sound",
+ "invalid-label-reference",
+ "missing-page-heading",
+ "skipped-heading-level",
+ "missing-main-landmark",
+ "multiple-main-landmarks",
+ "duplicate-id",
+ "missing-aria-reference",
+ "target-blank-without-noopener",
+ "non-get-resource-exposed-as-data-source",
+ "missing-page-description",
+ "empty-page-description",
+ "invalid-page-language",
+ "missing-social-image-asset",
+ "empty-page-title",
+ "duplicate-page-title",
+ "duplicate-page-description",
+ "invalid-json-ld",
+ "missing-json-ld-context",
+ "json-ld-in-custom-metadata",
+ "unknown-schema-org-type",
+ "deprecated-schema-org-type",
+ "unknown-schema-org-property",
+ "deprecated-schema-org-property",
+ "unsupported-schema-org-property",
+ "incompatible-schema-org-value",
+ "unused-asset",
+ "unused-design-token",
+ "unused-css-variable",
+ "unused-local-style-source",
+ "unused-breakpoint",
+ "duplicate-design-token-declarations",
+ "style-on-dom-transparent-component",
+ "atomic-css-disabled",
+]);
+
+const auditScopeDescription = [
+ "Audit scopes. Omit to run all scopes.",
+ "accessibility errors: missing-alt, missing-image-input-alt, missing-iframe-title, missing-accessible-name, missing-form-label, invalid-aria-role, missing-required-aria-role-property, role-interactive-not-focusable, aria-hidden-focusable, invalid-aria-state, invalid-aria-number, autoplay-media-with-sound, invalid-label-reference, duplicate-id, and missing-aria-reference; warnings: missing-image-description, unsupported-aria-role-property, positive-tabindex, missing-page-heading, skipped-heading-level, missing-main-landmark, and multiple-main-landmarks. Documentation: https://www.w3.org/WAI/WCAG22/understanding/.",
+ "security errors: non-get-resource-exposed-as-data-source; warning: target-blank-without-noopener. Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/noopener.",
+ "seo errors: empty-page-title, invalid-json-ld, and json-ld-in-custom-metadata; warnings: missing-page-description, empty-page-description, invalid-page-language, missing-social-image-asset, duplicate-page-title, duplicate-page-description, missing-json-ld-context, unknown-schema-org-type, deprecated-schema-org-type, unknown-schema-org-property, deprecated-schema-org-property, unsupported-schema-org-property, and incompatible-schema-org-value. Documentation: https://developers.google.com/search/docs/fundamentals/seo-starter-guide.",
+ "assets info: unused-asset. Documentation: https://docs.webstudio.is/university/foundations/anatomy-of-the-webstudio-builder.",
+ "styles warning: style-on-dom-transparent-component; info: unused-design-token, unused-css-variable, unused-local-style-source, unused-breakpoint, and duplicate-design-token-declarations. Documentation: https://docs.webstudio.is/university/foundations/design-tokens.",
+ "performance info: atomic-css-disabled. Rendered checks add image loading/sizing, render-blocking resource, and legacy font-format evidence. Documentation: https://docs.webstudio.is/university/foundations/project-settings#atomic-css.",
+].join(" ");
+
+export const auditInput = z
+ .object({
+ scopes: z
+ .array(auditScope)
+ .min(1)
+ .optional()
+ .describe(auditScopeDescription),
+ pageId: z.string().optional(),
+ pagePath: z.string().optional(),
+ severities: z
+ .array(auditSeverity)
+ .min(1)
+ .optional()
+ .describe(
+ "Filter returned findings by default rule severity: error, warning, or info. Summary counts remain unfiltered."
+ ),
+ limit: z.number().int().min(1).max(200).optional(),
+ cursor: z.string().min(1).optional(),
+ verbose: z
+ .boolean()
+ .optional()
+ .describe(
+ "Include explanations, remediation, evidence, skipped-check details, and manual-check workflows."
+ ),
+ })
+ .strict()
+ .superRefine(validatePageSelector);
+
+export const auditLocation = z
+ .object({
+ pageId: z.string().optional(),
+ pageIds: z.array(z.string()).optional(),
+ pagePath: z.string().optional(),
+ pagePaths: z.array(z.string()).optional(),
+ instanceId: z.string().optional(),
+ instanceIds: z.array(z.string()).optional(),
+ propName: z.string().optional(),
+ assetId: z.string().optional(),
+ styleSourceId: z.string().optional(),
+ designTokenId: z.string().optional(),
+ designTokenIds: z.array(z.string()).optional(),
+ cssVariableName: z.string().optional(),
+ cssVariableScope: z.string().optional(),
+ breakpointId: z.string().optional(),
+ resourceId: z.string().optional(),
+ dataSourceId: z.string().optional(),
+ htmlId: z.string().optional(),
+ jsonLdPath: z.string().optional(),
+ })
+ .strict();
+
+export const auditFinding = z.object({
+ id: z.string(),
+ scope: auditScope,
+ ruleId: auditRuleId,
+ severity: auditSeverity,
+ message: z.string(),
+ explanation: z.string(),
+ remediation: z.string(),
+ location: auditLocation,
+ evidence: z.record(z.string(), z.unknown()),
+ documentationUrl: z.string().url().optional(),
+});
+
+export const compactAuditFinding = auditFinding.pick({
+ id: true,
+ scope: true,
+ ruleId: true,
+ severity: true,
+ message: true,
+ location: true,
+});
+
+export const auditSummary = z.object({
+ total: z.number().int().nonnegative(),
+ selectedTotal: z.number().int().nonnegative(),
+ bySeverity: z.record(auditSeverity, z.number().int().nonnegative()),
+ byScope: z.record(auditScope, z.number().int().nonnegative()),
+});
+
+export const skippedAuditCheck = z.object({
+ scope: auditScope,
+ checkId: z.string(),
+ reason: z.enum([
+ "dynamic-value",
+ "missing-build-data",
+ "unsupported-component",
+ ]),
+ message: z.string(),
+ location: auditLocation,
+});
+
+export const manualAuditCheck = z.object({
+ checkId: z.string(),
+ message: z.string(),
+ workflow: z.string(),
+});
+
+export const renderedAuditCheck = z.object({
+ pageId: z.string(),
+ pagePath: z.string(),
+ viewport: z.object({
+ width: z.number().int().positive(),
+ height: z.number().int().positive(),
+ }),
+ screenshotPath: z.string(),
+ layout: z.object({
+ viewportWidth: z.number().int().positive(),
+ viewportHeight: z.number().int().positive(),
+ contentWidth: z.number().int().positive(),
+ contentHeight: z.number().int().positive(),
+ horizontalOverflow: z.boolean(),
+ images: z.array(
+ z.object({
+ instanceId: z.string().optional(),
+ loading: z.string(),
+ complete: z.boolean(),
+ naturalWidth: z.number().nonnegative(),
+ naturalHeight: z.number().nonnegative(),
+ renderedWidth: z.number().nonnegative(),
+ renderedHeight: z.number().nonnegative(),
+ top: z.number(),
+ })
+ ),
+ resources: z.array(
+ z.object({
+ pathname: z.string(),
+ initiatorType: z.string(),
+ transferSize: z.number().nonnegative(),
+ encodedBodySize: z.number().nonnegative(),
+ decodedBodySize: z.number().nonnegative(),
+ duration: z.number().nonnegative(),
+ renderBlockingStatus: z.string().optional(),
+ })
+ ),
+ }),
+ issues: z.array(
+ z.enum([
+ "horizontal-overflow",
+ "broken-image",
+ "eager-below-fold-image",
+ "oversized-image",
+ "render-blocking-resource",
+ "legacy-font-format",
+ ])
+ ),
+ imageIssues: z.array(
+ z.object({
+ kind: z.enum([
+ "broken-image",
+ "eager-below-fold-image",
+ "oversized-image",
+ ]),
+ instanceId: z.string().optional(),
+ loading: z.string(),
+ naturalWidth: z.number().nonnegative(),
+ naturalHeight: z.number().nonnegative(),
+ renderedWidth: z.number().nonnegative(),
+ renderedHeight: z.number().nonnegative(),
+ top: z.number(),
+ })
+ ),
+ resourceIssues: z.array(
+ z.object({
+ kind: z.enum(["render-blocking-resource", "legacy-font-format"]),
+ pathname: z.string(),
+ initiatorType: z.string(),
+ transferSize: z.number().nonnegative(),
+ encodedBodySize: z.number().nonnegative(),
+ decodedBodySize: z.number().nonnegative(),
+ duration: z.number().nonnegative(),
+ renderBlockingStatus: z.string().optional(),
+ })
+ ),
+});
+
+export const renderedAuditFailure = z.object({
+ pageId: z.string().optional(),
+ pagePath: z.string().optional(),
+ viewport: z
+ .object({
+ width: z.number().int().positive(),
+ height: z.number().int().positive(),
+ })
+ .optional(),
+ message: z.string(),
+});
+
+const auditResultBase = z.object({
+ contractVersion: z.literal(auditContractVersion),
+ projectVersion: z.number().int().nonnegative(),
+ scopes: z.array(auditScope),
+ pageFilter: z
+ .object({
+ pageId: z.string(),
+ pagePath: z.string(),
+ projectWideScopes: z.array(auditScope),
+ })
+ .nullable(),
+ summary: auditSummary,
+ skippedCheckCount: z.number().int().nonnegative(),
+ manualCheckCount: z.number().int().nonnegative(),
+ renderedCheckCount: z.number().int().nonnegative(),
+ renderedIssueCount: z.number().int().nonnegative(),
+ renderedFailureCount: z.number().int().nonnegative(),
+ nextCursor: z.string().nullable(),
+});
+
+export const compactAuditResult = auditResultBase.extend({
+ verbose: z.literal(false),
+ findings: z.array(compactAuditFinding),
+});
+
+export const verboseAuditResult = auditResultBase.extend({
+ verbose: z.literal(true),
+ findings: z.array(auditFinding),
+ skippedChecks: z.array(skippedAuditCheck),
+ manualChecks: z.array(manualAuditCheck),
+ renderedChecks: z.array(renderedAuditCheck),
+ renderedFailures: z.array(renderedAuditFailure),
+});
+
+export const auditResult = z.discriminatedUnion("verbose", [
+ compactAuditResult,
+ verboseAuditResult,
+]);
+
+export type AuditInput = z.infer<typeof auditInput>;
+export type AuditFinding = z.infer<typeof auditFinding>;
+export type CompactAuditFinding = z.infer<typeof compactAuditFinding>;
+export type AuditSummary = z.infer<typeof auditSummary>;
+export type AuditResult = z.infer<typeof auditResult>;
+export type CompactAuditResult = z.infer<typeof compactAuditResult>;
+export type VerboseAuditResult = z.infer<typeof verboseAuditResult>;
+export type RenderedAuditCheck = z.infer<typeof renderedAuditCheck>;
+export type RenderedAuditFailure = z.infer<typeof renderedAuditFailure>;
+
+type AuditRule = {
+ scope: z.infer<typeof auditScope>;
+ severity: z.infer<typeof auditSeverity>;
+ explanation: string;
+ remediation: string;
+ documentationUrl: string;
+};
+
+type AuditRuleId = z.infer<typeof auditRuleId>;
+
+const auditDocumentationByScope: Record<AuditRule["scope"], string> = {
+ accessibility: "https://www.w3.org/WAI/WCAG22/understanding/",
+ security:
+ "https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/noopener",
+ seo: "https://developers.google.com/search/docs/fundamentals/seo-starter-guide",
+ assets:
+ "https://docs.webstudio.is/university/foundations/anatomy-of-the-webstudio-builder",
+ styles: "https://docs.webstudio.is/university/foundations/design-tokens",
+ performance:
+ "https://docs.webstudio.is/university/foundations/project-settings#atomic-css",
+};
+
+const rule = (
+ scope: AuditRule["scope"],
+ severity: AuditRule["severity"],
+ explanation: string,
+ remediation: string,
+ documentationUrl = auditDocumentationByScope[scope]
+): AuditRule => ({
+ scope,
+ severity,
+ explanation,
+ remediation,
+ documentationUrl,
+});
+
+export const auditRules = {
+ "missing-alt": rule(
+ "accessibility",
+ "error",
+ "Images need text alternatives for people who cannot see them.",
+ "Add concise alt text, or an empty alt value when the image is decorative."
+ ),
+ "missing-image-description": rule(
+ "accessibility",
+ "warning",
+ "An asset-backed image has not been described or marked decorative.",
+ "Inspect the rendered image in context, then save a concise description or mark the image asset decorative with set-image-descriptions."
+ ),
+ "missing-image-input-alt": rule(
+ "accessibility",
+ "error",
+ "Image submit controls need an accessible label.",
+ "Add alt text describing the submitted action."
+ ),
+ "missing-iframe-title": rule(
+ "accessibility",
+ "error",
+ "An iframe title lets assistive technology identify embedded content.",
+ "Add a concise title describing the iframe."
+ ),
+ "missing-accessible-name": rule(
+ "accessibility",
+ "error",
+ "Users of assistive technology cannot identify the control's action.",
+ "Add visible text or a descriptive accessible label."
+ ),
+ "missing-form-label": rule(
+ "accessibility",
+ "error",
+ "Users need a programmatic label to understand a form control.",
+ "Associate a Label or add an accessible label."
+ ),
+ "invalid-aria-role": rule(
+ "accessibility",
+ "error",
+ "Unknown roles do not provide valid accessibility semantics.",
+ "Use a valid ARIA role or remove the role."
+ ),
+ "unsupported-aria-role-property": rule(
+ "accessibility",
+ "warning",
+ "The ARIA property is not supported by the element's explicit role.",
+ "Remove the property or choose a compatible role."
+ ),
+ "missing-required-aria-role-property": rule(
+ "accessibility",
+ "error",
+ "The explicit role is missing state required to communicate its meaning.",
+ "Add the required ARIA property or use a different role."
+ ),
+ "role-interactive-not-focusable": rule(
+ "accessibility",
+ "error",
+ "A custom interactive element cannot be reached from the keyboard.",
+ "Use a native interactive element or make it keyboard-focusable."
+ ),
+ "aria-hidden-focusable": rule(
+ "accessibility",
+ "error",
+ "Focusable content hidden from assistive technology creates inconsistent navigation.",
+ "Remove aria-hidden or remove the element from keyboard navigation."
+ ),
+ "positive-tabindex": rule(
+ "accessibility",
+ "warning",
+ "Positive tabindex values disrupt the natural keyboard order.",
+ "Use DOM order and tabindex 0 or -1 instead."
+ ),
+ "invalid-aria-state": rule(
+ "accessibility",
+ "error",
+ "The static ARIA value is invalid and may be ignored.",
+ "Use one of the values allowed for this ARIA property."
+ ),
+ "invalid-aria-number": rule(
+ "accessibility",
+ "error",
+ "The ARIA property requires a numeric value.",
+ "Set a valid finite numeric value."
+ ),
+ "autoplay-media-with-sound": rule(
+ "accessibility",
+ "error",
+ "Unexpected audio can interfere with navigation and comprehension.",
+ "Mute autoplaying media or require an explicit user action to play it."
+ ),
+ "invalid-label-reference": rule(
+ "accessibility",
+ "error",
+ "The label does not reference a valid labelable control.",
+ "Point the label at the control's unique static id."
+ ),
+ "missing-page-heading": rule(
+ "accessibility",
+ "warning",
+ "A primary heading helps users understand and navigate the page.",
+ "Add one descriptive h1 heading."
+ ),
+ "skipped-heading-level": rule(
+ "accessibility",
+ "warning",
+ "Skipped heading levels can make the document outline confusing.",
+ "Use sequential heading levels that reflect the content hierarchy."
+ ),
+ "missing-main-landmark": rule(
+ "accessibility",
+ "warning",
+ "A main landmark helps assistive-technology users reach primary content.",
+ "Wrap the page's primary content in one main element."
+ ),
+ "multiple-main-landmarks": rule(
+ "accessibility",
+ "warning",
+ "Multiple main landmarks make the page's primary content ambiguous.",
+ "Keep one main landmark for the page."
+ ),
+ "duplicate-id": rule(
+ "accessibility",
+ "error",
+ "Duplicate HTML ids break label and ARIA references.",
+ "Give every static HTML id a unique value on the page."
+ ),
+ "missing-aria-reference": rule(
+ "accessibility",
+ "error",
+ "An ARIA relationship points to an id that does not exist on the page.",
+ "Add the referenced id or update the ARIA property to a valid target."
+ ),
+ "target-blank-without-noopener": rule(
+ "security",
+ "warning",
+ "A new-tab link can retain access to the opener in affected environments.",
+ "Add noopener or noreferrer to rel."
+ ),
+ "non-get-resource-exposed-as-data-source": rule(
+ "security",
+ "error",
+ "A mutation-style HTTP resource is exposed as render-time data and may perform side effects when the page renders.",
+ "Remove the data-source exposure, or use a GET resource for render-time data and keep mutation resources bound only to explicit actions.",
+ "https://docs.webstudio.is/university/foundations/variables#resource"
+ ),
+ "missing-page-description": rule(
+ "seo",
+ "warning",
+ "The page has no description for search and sharing surfaces.",
+ "Add a concise page description."
+ ),
+ "empty-page-description": rule(
+ "seo",
+ "warning",
+ "An empty description provides no useful page summary.",
+ "Write a concise page description or remove the empty metadata entry."
+ ),
+ "invalid-page-language": rule(
+ "seo",
+ "warning",
+ "An invalid language tag harms language detection and accessibility.",
+ "Use a valid BCP 47 language tag."
+ ),
+ "missing-social-image-asset": rule(
+ "seo",
+ "warning",
+ "The configured social image no longer resolves to a project asset.",
+ "Select an existing image asset or remove the stale reference."
+ ),
+ "empty-page-title": rule(
+ "seo",
+ "error",
+ "The page has no useful title for browser and search results.",
+ "Add a concise, unique page title."
+ ),
+ "duplicate-page-title": rule(
+ "seo",
+ "warning",
+ "Duplicate titles make pages difficult to distinguish in search results.",
+ "Give each indexable page a unique title."
+ ),
+ "duplicate-page-description": rule(
+ "seo",
+ "warning",
+ "Duplicate descriptions provide weak page-specific search summaries.",
+ "Give each indexable page a distinct description."
+ ),
+ "invalid-json-ld": rule(
+ "seo",
+ "error",
+ "Invalid JSON-LD cannot be interpreted as structured data.",
+ "Set the JSON-LD component code to a valid JSON object or array.",
+ "https://developers.google.com/search/docs/appearance/structured-data/intro-structured-data"
+ ),
+ "missing-json-ld-context": rule(
+ "seo",
+ "warning",
+ "Most JSON-LD documents need a top-level @context to define their terms. Documents using only absolute IRIs may not need one.",
+ "Add the appropriate @context, commonly https://schema.org, or verify that every term is an absolute IRI.",
+ "https://developers.google.com/search/docs/appearance/structured-data/intro-structured-data"
+ ),
+ "json-ld-in-custom-metadata": rule(
+ "seo",
+ "error",
+ "Custom metadata creates meta elements and cannot emit a JSON-LD script.",
+ "Remove this custom metadata entry and add a JsonLd component, preferably inside HeadSlot.",
+ "https://developers.google.com/search/docs/appearance/structured-data/intro-structured-data"
+ ),
+ "unknown-schema-org-type": rule(
+ "seo",
+ "warning",
+ "The JSON-LD type is not defined by the current Schema.org vocabulary.",
+ "Correct the type name or use an explicit custom vocabulary context.",
+ "https://schema.org/docs/schemas.html"
+ ),
+ "deprecated-schema-org-type": rule(
+ "seo",
+ "warning",
+ "The Schema.org type has been superseded.",
+ "Replace it with the current type named in the finding.",
+ "https://schema.org/docs/attic.html"
+ ),
+ "unknown-schema-org-property": rule(
+ "seo",
+ "warning",
+ "The JSON-LD property is not defined by the current Schema.org vocabulary.",
+ "Correct the property name or define it through an explicit custom context.",
+ "https://schema.org/docs/schemas.html"
+ ),
+ "deprecated-schema-org-property": rule(
+ "seo",
+ "warning",
+ "The Schema.org property has been superseded.",
+ "Replace it with the current property named in the finding.",
+ "https://schema.org/docs/attic.html"
+ ),
+ "unsupported-schema-org-property": rule(
+ "seo",
+ "warning",
+ "The Schema.org property is not declared for the supplied type.",
+ "Use a property supported by this type or correct the entity type.",
+ "https://schema.org/docs/schemas.html"
+ ),
+ "incompatible-schema-org-value": rule(
+ "seo",
+ "warning",
+ "The value type conflicts with the Schema.org property's declared range.",
+ "Use one of the expected value types named in the finding.",
+ "https://schema.org/docs/schemas.html"
+ ),
+ "unused-asset": rule(
+ "assets",
+ "info",
+ "The asset has no references in editable project data.",
+ "Confirm it is not used externally, then remove it if unnecessary."
+ ),
+ "unused-design-token": rule(
+ "styles",
+ "info",
+ "The design token is not assigned to any element.",
+ "Apply the token or remove it."
+ ),
+ "unused-css-variable": rule(
+ "styles",
+ "info",
+ "The CSS variable has no references in project styles or embeds.",
+ "Use the variable or remove it."
+ ),
+ "unused-local-style-source": rule(
+ "styles",
+ "info",
+ "The local style source has declarations but no element assignment.",
+ "Assign the style source or remove it."
+ ),
+ "unused-breakpoint": rule(
+ "styles",
+ "info",
+ "The breakpoint has no style declarations.",
+ "Add responsive styles at this breakpoint or remove it."
+ ),
+ "duplicate-design-token-declarations": rule(
+ "styles",
+ "info",
+ "Multiple tokens contain identical declarations and may be redundant.",
+ "Confirm the duplication is intentional or consolidate the tokens."
+ ),
+ "style-on-dom-transparent-component": rule(
+ "styles",
+ "warning",
+ "The component does not render a DOM wrapper, so styles assigned directly to it have no visual effect.",
+ "Move the style to a rendered child or wrap the component in an Element and style that wrapper.",
+ "https://docs.webstudio.is/university/core-components/collection"
+ ),
+ "atomic-css-disabled": rule(
+ "performance",
+ "info",
+ "Atomic CSS generation is disabled, which can produce substantially larger published CSS.",
+ "Enable atomic CSS for optimized published output unless human-readable exported classes are required.",
+ "https://docs.webstudio.is/university/foundations/project-settings#atomic-css"
+ ),
+} satisfies Record<AuditRuleId, AuditRule>;
+
+const getRule = (ruleId: string) => {
+ const registered = auditRules[ruleId as AuditRuleId];
+ if (registered !== undefined) {
+ return registered;
+ }
+ throw new Error(`Unregistered audit rule ${JSON.stringify(ruleId)}`);
+};
+
+const locationKeys = new Set([
+ "pageId",
+ "pageIds",
+ "pagePath",
+ "pagePaths",
+ "instanceId",
+ "instanceIds",
+ "propName",
+ "assetId",
+ "styleSourceId",
+ "designTokenId",
+ "designTokenIds",
+ "breakpointId",
+ "resourceId",
+ "dataSourceId",
+ "jsonLdPath",
+]);
+
+export const normalizeAuditFinding = (
+ match: Record<string, unknown>
+): AuditFinding => {
+ const ruleId = match.issue;
+ if (typeof ruleId !== "string") {
+ throw new Error("Audit detector returned a match without an issue code");
+ }
+ const metadata = getRule(ruleId);
+ const location: Record<string, unknown> = {};
+ const evidence: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(match)) {
+ if (locationKeys.has(key)) {
+ location[key] = value;
+ } else if (key !== "issue" && key !== "message" && key !== "kind") {
+ evidence[key] = value;
+ }
+ }
+ if (match.kind === "css-variable" && typeof match.name === "string") {
+ location.cssVariableName = match.name;
+ if (typeof match.scope === "string") {
+ location.cssVariableScope = match.scope;
+ delete evidence.scope;
+ }
+ }
+ if (typeof match.id === "string") {
+ location.htmlId = match.id;
+ delete evidence.id;
+ }
+ if (typeof match.name === "string" && ruleId.includes("aria")) {
+ location.propName = match.name;
+ }
+ const identity = Object.entries(location)
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(
+ ([key, value]) =>
+ `${key}:${Array.isArray(value) ? value.join(",") : String(value)}`
+ )
+ .join("/");
+ return auditFinding.parse({
+ id: `${metadata.scope}/${ruleId}/${identity || "project"}`,
+ scope: metadata.scope,
+ ruleId,
+ severity: metadata.severity,
+ message:
+ typeof match.message === "string" ? match.message : metadata.explanation,
+ explanation: metadata.explanation,
+ remediation: metadata.remediation,
+ documentationUrl: metadata.documentationUrl,
+ location,
+ evidence,
+ });
+};
+
+const severityOrder: Record<AuditFinding["severity"], number> = {
+ error: 0,
+ warning: 1,
+ info: 2,
+};
+
+const cursorSchema = z.object({
+ version: z.number().int().nonnegative(),
+ offset: z.number().int().nonnegative(),
+ signature: z.string(),
+});
+
+const encodeCursor = (version: number, offset: number, signature: string) =>
+ encodeURIComponent(JSON.stringify({ version, offset, signature }));
+
+const decodeCursor = (cursor: string) => {
+ try {
+ return cursorSchema.parse(JSON.parse(decodeURIComponent(cursor)));
+ } catch {
+ return throwBuilderRuntimeError("BAD_REQUEST", "Invalid audit cursor");
+ }
+};
+
+const accessibilityDynamicProps = new Set([
+ "alt",
+ "title",
+ "role",
+ "tabindex",
+ "for",
+ "id",
+ "autoplay",
+ "muted",
+]);
+
+const getSkippedChecks = (
+ state: BuilderState,
+ input: AuditInput,
+ scopes: readonly z.infer<typeof auditScope>[]
+) => {
+ const checks: Array<z.infer<typeof skippedAuditCheck>> = [];
+ let instanceIds: ReadonlySet<string> | undefined;
+ let selectedPageId: string | undefined;
+ if (input.pageId !== undefined || input.pagePath !== undefined) {
+ const pages = getSerializedPages(state);
+ const page = findSerializedPageByInput(pages, input);
+ if (page === undefined) {
+ return throwBuilderRuntimeError("NOT_FOUND", "Page not found");
+ }
+ selectedPageId = page.id;
+ if (state.instances === undefined) {
+ return throwBuilderRuntimeError("BAD_REQUEST", "Instances are required");
+ }
+ instanceIds = new Set(
+ getInstanceDepths(state.instances, [page.rootInstanceId]).keys()
+ );
+ }
+ for (const prop of state.props?.values() ?? []) {
+ if (
+ isDynamicPropType(prop.type) === false ||
+ (instanceIds !== undefined && instanceIds.has(prop.instanceId) === false)
+ ) {
+ continue;
+ }
+ if (
+ scopes.includes("accessibility") &&
+ (accessibilityDynamicProps.has(prop.name) ||
+ prop.name.startsWith("aria-"))
+ ) {
+ checks.push({
+ scope: "accessibility",
+ checkId: "dynamic-accessibility-prop",
+ reason: "dynamic-value",
+ message: `${prop.name} is ${prop.type}-backed and cannot be audited statically.`,
+ location: { instanceId: prop.instanceId, propName: prop.name },
+ });
+ }
+ if (
+ scopes.includes("security") &&
+ (prop.name === "target" || prop.name === "rel")
+ ) {
+ checks.push({
+ scope: "security",
+ checkId: "dynamic-link-security-prop",
+ reason: "dynamic-value",
+ message: `${prop.name} is ${prop.type}-backed and cannot be audited statically.`,
+ location: { instanceId: prop.instanceId, propName: prop.name },
+ });
+ }
+ if (
+ scopes.includes("seo") &&
+ prop.name === "code" &&
+ state.instances?.get(prop.instanceId)?.component === "JsonLd"
+ ) {
+ checks.push({
+ scope: "seo",
+ checkId: "dynamic-json-ld",
+ reason: "dynamic-value",
+ message: `JSON-LD code is ${prop.type}-backed and cannot be audited statically.`,
+ location: { instanceId: prop.instanceId, propName: prop.name },
+ });
+ }
+ }
+ if (scopes.includes("accessibility") && state.instances !== undefined) {
+ const staticAccessibleNameByInstance = new Set<string>();
+ for (const prop of state.props?.values() ?? []) {
+ if (
+ isDynamicPropType(prop.type) === false &&
+ (prop.name === "aria-label" ||
+ prop.name === "aria-labelledby" ||
+ prop.name === "title") &&
+ typeof prop.value === "string" &&
+ prop.value.trim().length > 0
+ ) {
+ staticAccessibleNameByInstance.add(prop.instanceId);
+ }
+ }
+ for (const instance of state.instances.values()) {
+ if (
+ (instanceIds !== undefined && instanceIds.has(instance.id) === false) ||
+ (instance.component !== "Button" &&
+ instance.component !== "Link" &&
+ instance.tag !== "button" &&
+ instance.tag !== "a") ||
+ staticAccessibleNameByInstance.has(instance.id)
+ ) {
+ continue;
+ }
+ const text = getAccessibleContentState(instance.id, state.instances);
+ if (text.hasStatic === false && text.hasDynamic) {
+ checks.push({
+ scope: "accessibility",
+ checkId: "dynamic-accessible-name",
+ reason: "dynamic-value",
+ message:
+ "Accessible name depends on expression-backed text and cannot be audited statically.",
+ location: { instanceId: instance.id },
+ });
+ }
+ }
+ }
+ if (scopes.includes("seo")) {
+ const pages = getSerializedPages(state);
+ for (const page of pages.pages) {
+ if (selectedPageId !== undefined && page.id !== selectedPageId) {
+ continue;
+ }
+ for (const [field, expression] of [
+ ["title", page.title],
+ ["description", page.meta.description],
+ ["language", page.meta.language],
+ ] as const) {
+ if (
+ expression === undefined ||
+ isLiteralExpression(expression) === true
+ ) {
+ continue;
+ }
+ checks.push({
+ scope: "seo",
+ checkId: "dynamic-page-metadata",
+ reason: "dynamic-value",
+ message: `${field} is expression-backed and cannot be audited statically.`,
+ location: {
+ pageId: page.id,
+ pagePath: getSerializedPagePath(pages, page),
+ },
+ });
+ }
+ }
+ }
+ return checks.sort(
+ (left, right) =>
+ left.scope.localeCompare(right.scope) ||
+ left.checkId.localeCompare(right.checkId) ||
+ (left.location.pagePath ?? "").localeCompare(
+ right.location.pagePath ?? ""
+ ) ||
+ (left.location.instanceId ?? "").localeCompare(
+ right.location.instanceId ?? ""
+ ) ||
+ (left.location.propName ?? "").localeCompare(
+ right.location.propName ?? ""
+ )
+ );
+};
+
+export function audit(
+ state: BuilderState,
+ input: AuditInput & { verbose: true },
+ context?: Pick<BuilderRuntimeContext, "projectVersion">
+): VerboseAuditResult;
+export function audit(
+ state: BuilderState,
+ input: AuditInput & { verbose?: false | undefined },
+ context?: Pick<BuilderRuntimeContext, "projectVersion">
+): CompactAuditResult;
+export function audit(
+ state: BuilderState,
+ input: AuditInput,
+ context?: Pick<BuilderRuntimeContext, "projectVersion">
+): AuditResult;
+export function audit(
+ state: BuilderState,
+ input: AuditInput,
+ context: Pick<BuilderRuntimeContext, "projectVersion"> = {}
+): AuditResult {
+ if (context.projectVersion === undefined) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "Audit requires the current project version"
+ );
+ }
+ const scopes = input.scopes ?? auditScope.options;
+ const selectedSeverities = input.severities ?? auditSeverity.options;
+ const cursorSignature = JSON.stringify({
+ scopes: [...scopes].sort(),
+ severities: [...selectedSeverities].sort(),
+ pageId: input.pageId,
+ pagePath: input.pagePath,
+ verbose: input.verbose === true,
+ });
+ const raw = analyzeProject(state, {
+ scopes,
+ pageId: input.pageId,
+ pagePath: input.pagePath,
+ limit: Number.MAX_SAFE_INTEGER,
+ });
+ const allFindings = raw.matches
+ .map(normalizeAuditFinding)
+ .sort(
+ (left, right) =>
+ severityOrder[left.severity] - severityOrder[right.severity] ||
+ left.scope.localeCompare(right.scope) ||
+ left.ruleId.localeCompare(right.ruleId) ||
+ (left.location.pagePath ?? "").localeCompare(
+ right.location.pagePath ?? ""
+ ) ||
+ left.id.localeCompare(right.id)
+ );
+ const severities = new Set(selectedSeverities);
+ const findings = allFindings.filter((finding) =>
+ severities.has(finding.severity)
+ );
+ const limit = input.limit ?? 50;
+ let offset = 0;
+ if (input.cursor !== undefined) {
+ const cursor = decodeCursor(input.cursor);
+ if (context.projectVersion === undefined) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "Audit cursor requires a project version"
+ );
+ }
+ if (cursor.version !== context.projectVersion) {
+ return throwBuilderRuntimeError(
+ "CONFLICT",
+ "Audit cursor is stale; restart the audit on the latest project version"
+ );
+ }
+ if (cursor.signature !== cursorSignature) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "Audit cursor does not match the selected scopes, severities, or page"
+ );
+ }
+ offset = cursor.offset;
+ }
+ const bySeverity = Object.fromEntries(
+ auditSeverity.options.map((severity) => [
+ severity,
+ allFindings.filter((finding) => finding.severity === severity).length,
+ ])
+ ) as AuditSummary["bySeverity"];
+ const byScope = Object.fromEntries(
+ auditScope.options.map((scope) => [
+ scope,
+ allFindings.filter((finding) => finding.scope === scope).length,
+ ])
+ ) as AuditSummary["byScope"];
+ let pageFilter: AuditResult["pageFilter"] = null;
+ if (input.pageId !== undefined || input.pagePath !== undefined) {
+ const pages = getSerializedPages(state);
+ const page = findSerializedPageByInput(pages, input);
+ if (page === undefined) {
+ return throwBuilderRuntimeError("NOT_FOUND", "Page not found");
+ }
+ pageFilter = {
+ pageId: page.id,
+ pagePath: getSerializedPagePath(pages, page),
+ projectWideScopes: scopes.filter(
+ (scope) =>
+ scope === "assets" || scope === "styles" || scope === "performance"
+ ),
+ };
+ }
+ const skippedChecks = getSkippedChecks(state, input, scopes);
+ const manualChecks = [
+ ...(scopes.some((scope) =>
+ ["accessibility", "styles", "performance"].includes(scope)
+ )
+ ? [
+ {
+ checkId: "responsive-visual-review",
+ message:
+ "Check responsive layout, overflow, clipping, and text wrapping at project breakpoints.",
+ workflow:
+ "Preview the project and capture screenshots at desktop and every breakpoint edge. Treat screenshot.layout.horizontalOverflow as deterministic overflow evidence, then inspect clipping and text wrapping with vision.",
+ },
+ ]
+ : []),
+ ...(scopes.some((scope) => ["accessibility", "styles"].includes(scope))
+ ? [
+ {
+ checkId: "visual-contrast-review",
+ message:
+ "Check text and control contrast against rendered backgrounds.",
+ workflow:
+ "Inspect rendered screenshots with vision and use measured color contrast when exact WCAG ratios are required.",
+ },
+ {
+ checkId: "visual-hierarchy-review",
+ message:
+ "Check whether headings, actions, grouping, and reading order are visually clear.",
+ workflow:
+ "Inspect desktop and mobile screenshots with vision, then compare the visual hierarchy with the editable heading and landmark structure.",
+ },
+ ]
+ : []),
+ ];
+ const paginatedFindings = findings.slice(offset, offset + limit);
+ const resultBase = {
+ contractVersion: auditContractVersion,
+ projectVersion: context.projectVersion,
+ scopes: [...scopes],
+ pageFilter,
+ summary: {
+ total: allFindings.length,
+ selectedTotal: findings.length,
+ bySeverity,
+ byScope,
+ },
+ skippedCheckCount: skippedChecks.length,
+ manualCheckCount: manualChecks.length,
+ renderedCheckCount: 0,
+ renderedIssueCount: 0,
+ renderedFailureCount: 0,
+ nextCursor:
+ offset + limit < findings.length
+ ? encodeCursor(context.projectVersion, offset + limit, cursorSignature)
+ : null,
+ };
+ if (input.verbose === true) {
+ return verboseAuditResult.parse({
+ ...resultBase,
+ verbose: true,
+ findings: paginatedFindings,
+ skippedChecks,
+ manualChecks,
+ renderedChecks: [],
+ renderedFailures: [],
+ });
+ }
+ return compactAuditResult.parse({
+ ...resultBase,
+ verbose: false,
+ findings: paginatedFindings.map(
+ ({ id, scope, ruleId, severity, message, location }) => ({
+ id,
+ scope,
+ ruleId,
+ severity,
+ message,
+ location,
+ })
+ ),
+ });
+}
diff --git a/packages/project-build/src/runtime/content-mode-permissions.ts b/packages/project-build/src/runtime/content-mode-permissions.ts
index d2f9677792..ffe1c13c15 100644
--- a/packages/project-build/src/runtime/content-mode-permissions.ts
+++ b/packages/project-build/src/runtime/content-mode-permissions.ts
@@ -1,4 +1,5 @@
import type { Patch } from "immer";
+import { isRecord } from "../shared/type-utils";
import {
instance,
instanceChild,
@@ -83,9 +84,6 @@ export const isContentModePagePath = (value: unknown) =>
value.includes(":") === false &&
value.includes("*") === false;
-const isRecord = (value: unknown): value is Record<string, unknown> =>
- typeof value === "object" && value !== null;
-
const isString = (value: unknown) => typeof value === "string";
const isOptionalString = (value: unknown) =>
value === undefined || typeof value === "string";
diff --git a/packages/project-build/src/runtime/content-model.test.tsx b/packages/project-build/src/runtime/content-model.test.tsx
index 47f692994c..296dfa92f9 100644
--- a/packages/project-build/src/runtime/content-model.test.tsx
+++ b/packages/project-build/src/runtime/content-model.test.tsx
@@ -554,6 +554,34 @@ test("support links inside of details", () => {
});
describe("component content model", () => {
+ test("accepts childless JSON-LD in page flow", () => {
+ expect(
+ isTreeSatisfyingContentModel({
+ ...renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <$.JsonLd code='{"@context":"https://schema.org"}' />
+ </ws.element>
+ ),
+ metas: defaultMetas,
+ instanceSelector: ["bodyId"],
+ })
+ ).toBeTruthy();
+ });
+
+ test("accepts JSON-LD in Head Slot", () => {
+ expect(
+ isTreeSatisfyingContentModel({
+ ...renderData(
+ <$.HeadSlot ws:id="headSlotId">
+ <$.JsonLd code='{"@context":"https://schema.org"}' />
+ </$.HeadSlot>
+ ),
+ metas: defaultMetas,
+ instanceSelector: ["headSlotId"],
+ })
+ ).toBeTruthy();
+ });
+
test("restrict children with specific component", () => {
expect(
isTreeSatisfyingContentModel({
diff --git a/packages/project-build/src/runtime/context.ts b/packages/project-build/src/runtime/context.ts
index 534c6b5aa1..a142ac0732 100644
--- a/packages/project-build/src/runtime/context.ts
+++ b/packages/project-build/src/runtime/context.ts
@@ -3,6 +3,7 @@ import { nanoid } from "nanoid";
export type BuilderRuntimeContext = {
createId: () => string;
projectId?: string;
+ projectVersion?: number;
};
export const builderRuntimeContext: BuilderRuntimeContext = {
diff --git a/packages/project-build/src/runtime/cutover.ts b/packages/project-build/src/runtime/cutover.ts
index 0b6b27d735..b5566aa00e 100644
--- a/packages/project-build/src/runtime/cutover.ts
+++ b/packages/project-build/src/runtime/cutover.ts
@@ -105,6 +105,11 @@ export const builderRuntimeCutoverManifests = [
] as const,
callers: ["appRouter.api.instances"] as const,
},
+ {
+ family: "project-inspection-read",
+ operationIds: ["project.search", "project.audit"] as const,
+ callers: ["MCP/CLI project search and audit"] as const,
+ },
{
family: "instance-structural-api-mutations",
operationIds: [
@@ -136,6 +141,7 @@ export const builderRuntimeCutoverManifests = [
family: "text-content-mutations",
operationIds: [
"instances.updateText",
+ "instances.replaceText",
"instances.setTextContent",
"instances.updateTextTree",
] as const,
@@ -148,6 +154,7 @@ export const builderRuntimeCutoverManifests = [
family: "prop-mutations",
operationIds: [
"instances.updateProps",
+ "instances.replacePropText",
"instances.deleteProps",
"instances.bindProps",
] as const,
@@ -234,18 +241,25 @@ export const builderRuntimeCutoverManifests = [
operationIds: [
"resources.create",
"resources.update",
+ "resources.replaceText",
"resources.delete",
"resources.upsert",
"resources.upsertProp",
] as const,
callers: ["appRouter.api.resources"] as const,
},
+ {
+ family: "font-read",
+ operationIds: ["fonts.list"] as const,
+ callers: ["MCP/CLI font discovery"] as const,
+ },
{
family: "asset-reference-operations",
operationIds: [
"assets.list",
"assets.findUsage",
"assets.update",
+ "assets.setImageDescriptions",
"assets.add",
"assets.replace",
"assets.delete",
diff --git a/packages/project-build/src/runtime/data.test.tsx b/packages/project-build/src/runtime/data.test.tsx
index c1de4c90e5..37731cdd0a 100644
--- a/packages/project-build/src/runtime/data.test.tsx
+++ b/packages/project-build/src/runtime/data.test.tsx
@@ -32,6 +32,7 @@ import {
createDataVariableUpdatePayload,
createDataVariableValueFromInput,
createResourceFieldsFromResource,
+ createResource,
createResourceCreatePayload,
createResourceDeletePayload,
createResourceFieldsFromFormData,
@@ -51,11 +52,13 @@ import {
getDataVariableJsonExpressionErrors,
getResourceExpressionErrors,
rebindTreeVariablesMutable,
+ replaceResourceText,
replaceDataSourcesInExpression,
restoreExpressionVariables,
resourceCreateInput,
resourceFieldsInput,
resourceFieldsUpdateInput,
+ produceWebstudioDataMutation,
serializeDataVariables,
serializeResources,
unsetExpressionVariables,
@@ -71,6 +74,47 @@ import {
validateResourceUrlExpression,
} from "./data";
+test("creates Map-backed patches without mutating caller-owned data", () => {
+ const before = {
+ instances: new Map([
+ [
+ "instance",
+ {
+ id: "instance",
+ children: [{ type: "text", value: "Before" }],
+ },
+ ],
+ ]),
+ };
+ const original = structuredClone(before);
+
+ const result = produceWebstudioDataMutation(before, (draft) => {
+ draft.instances.get("instance")?.children.push({
+ type: "text",
+ value: "After",
+ });
+ });
+
+ expect(before).toEqual(original);
+ expect(result.data).not.toBe(before);
+ expect(result.data.instances.get("instance")?.children).toEqual([
+ { type: "text", value: "Before" },
+ { type: "text", value: "After" },
+ ]);
+ expect(result.payload).toEqual([
+ {
+ namespace: "instances",
+ patches: [
+ {
+ op: "add",
+ path: ["instance", "children", 1],
+ value: { type: "text", value: "After" },
+ },
+ ],
+ },
+ ]);
+});
+
test("rejects client-supplied ids on data create inputs", () => {
expect(
dataVariableCreateInput.safeParse({
@@ -1932,6 +1976,45 @@ describe("createResourceValue", () => {
});
});
+ test("accepts explicit literal request values without changing expressions", () => {
+ expect(
+ resourceFieldsInput.parse({
+ name: "Users",
+ method: "post",
+ url: "https://example.com/users",
+ searchParams: [
+ { name: "source", value: { type: "literal", value: "homepage" } },
+ { name: "page", value: "filters.page" },
+ ],
+ headers: [
+ {
+ name: "Content-Type",
+ value: { type: "literal", value: "application/json" },
+ },
+ { name: "Authorization", value: '"Bearer " + auth.token' },
+ ],
+ body: { type: "literal", value: "Plain text body" },
+ })
+ ).toMatchObject({
+ url: '"https://example.com/users"',
+ searchParams: [
+ {
+ name: "source",
+ value: { type: "literal", value: "homepage" },
+ },
+ { name: "page", value: "filters.page" },
+ ],
+ headers: [
+ {
+ name: "Content-Type",
+ value: { type: "literal", value: "application/json" },
+ },
+ { name: "Authorization", value: '"Bearer " + auth.token' },
+ ],
+ body: { type: "literal", value: "Plain text body" },
+ });
+ });
+
test("reject invalid resource controls", () => {
expect(() =>
resourceFieldsInput.parse({
@@ -1950,7 +2033,7 @@ describe("createResourceValue", () => {
resourceFieldsInput.parse({
name: "Users",
method: "get",
- url: "https://example.com/users",
+ url: '"https://example.com/users" +',
searchParams: [],
headers: [],
})
@@ -2209,6 +2292,135 @@ describe("resource patch helpers", () => {
headers: [],
};
+ const createResourceState = () => ({
+ pages: createDefaultPages({ rootInstanceId: "body" }),
+ instances: new Map(),
+ props: new Map(),
+ dataSources: new Map(),
+ resources: new Map(),
+ breakpoints: new Map(),
+ styleSources: new Map(),
+ styleSourceSelections: new Map(),
+ styles: new Map(),
+ });
+
+ test("normalizes literal expressions when creating a resource", () => {
+ const result = createResource(
+ createResourceState(),
+ {
+ resource: resourceFieldsInput.parse({
+ name: "Users",
+ method: "post",
+ url: "https://example.com/users",
+ searchParams: [
+ { name: "status", value: { type: "literal", value: "active" } },
+ ],
+ headers: [
+ {
+ name: "Content-Type",
+ value: { type: "literal", value: "application/json" },
+ },
+ ],
+ body: { type: "literal", value: "request body" },
+ }),
+ },
+ { createId: () => "resource-id" }
+ );
+
+ expect(result.payload).toContainEqual({
+ namespace: "resources",
+ patches: [
+ {
+ op: "add",
+ path: ["resource-id"],
+ value: {
+ id: "resource-id",
+ name: "Users",
+ control: undefined,
+ method: "post",
+ url: '"https://example.com/users"',
+ searchParams: [{ name: "status", value: '"active"' }],
+ headers: [{ name: "Content-Type", value: '"application/json"' }],
+ body: '"request body"',
+ },
+ },
+ ],
+ });
+ });
+
+ test("does not invalidate resources when text replacement finds no matches", () => {
+ const result = replaceResourceText(
+ { resources: new Map([[resource.id, resource]]) },
+ {
+ find: "Not present",
+ replace: "Replacement",
+ match: "substring",
+ fields: ["name", "url"],
+ limit: 100,
+ }
+ );
+
+ expect(result.payload).toEqual([]);
+ expect(result.invalidatesNamespaces).toEqual([]);
+ expect(result.result).toMatchObject({
+ changedCount: 0,
+ matchingFieldCount: 0,
+ });
+ });
+
+ test("replaces selected resource names and literal URLs", () => {
+ const selected: Resource = {
+ ...resource,
+ name: "Old users",
+ url: '"https://example.com/Old-users"',
+ };
+ const ignored: Resource = {
+ ...resource,
+ id: "ignored",
+ name: "Old ignored",
+ };
+ const result = replaceResourceText(
+ {
+ resources: new Map([
+ [selected.id, selected],
+ [ignored.id, ignored],
+ ]),
+ },
+ {
+ resourceIds: [selected.id],
+ find: "Old",
+ replace: "New",
+ match: "substring",
+ fields: ["name", "url"],
+ limit: 100,
+ }
+ );
+
+ expect(result.result).toMatchObject({
+ changedCount: 2,
+ matchingFieldCount: 2,
+ truncated: false,
+ });
+ expect(result.payload).toEqual([
+ {
+ namespace: "resources",
+ patches: [
+ {
+ op: "replace",
+ path: [selected.id, "name"],
+ value: "New users",
+ },
+ {
+ op: "replace",
+ path: [selected.id, "url"],
+ value: '"https://example.com/New-users"',
+ },
+ ],
+ },
+ ]);
+ expect(result.invalidatesNamespaces).toEqual(["resources"]);
+ });
+
test("upserts resource variables and rebinds expressions", () => {
const body: Instance = {
type: "instance",
@@ -2453,12 +2665,12 @@ describe("resource patch helpers", () => {
{
scopeInstanceId: "box",
dataSourceId: "variable-id",
- resource: {
+ resource: resourceFieldsInput.parse({
name: "Users",
method: "get",
- url: `"https://example.com/users"`,
+ url: "https://example.com/users",
headers: [],
- },
+ }),
},
{ createId: () => "resource-id" }
);
@@ -2638,12 +2850,12 @@ describe("resource patch helpers", () => {
{
instanceId: "box",
propName: "data",
- resource: {
+ resource: resourceFieldsInput.parse({
name: "Users",
method: "get",
- url: '"https://example.com/users"',
+ url: "https://example.com/users",
headers: [],
- },
+ }),
},
{ createId: () => ids.shift() ?? "extra-id" }
);
@@ -2710,6 +2922,62 @@ describe("resource patch helpers", () => {
values: { url: `"not-a-url"` },
})
).toThrow("url: URL is invalid");
+
+ expect(
+ updateResource(state, {
+ resourceId: "resource",
+ values: resourceFieldsUpdateInput.parse({
+ headers: [
+ {
+ name: "Content-Type",
+ value: { type: "literal", value: "application/json" },
+ },
+ ],
+ body: { type: "literal", value: "Plain text body" },
+ }),
+ }).payload
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ namespace: "resources",
+ patches: expect.arrayContaining([
+ expect.objectContaining({
+ value: expect.objectContaining({
+ headers: [
+ { name: "Content-Type", value: '"application/json"' },
+ ],
+ body: '"Plain text body"',
+ }),
+ }),
+ ]),
+ }),
+ ])
+ );
+ });
+
+ test("preserves omitted resource fields during partial updates", () => {
+ const state = createResourceState();
+ state.resources.set("resource", {
+ ...resource,
+ headers: [{ name: "Authorization", value: '"Bearer token"' }],
+ body: '"request body"',
+ });
+
+ const result = updateResource(state, {
+ resourceId: "resource",
+ values: { name: "Renamed" },
+ });
+ const resourcePatch = result.payload
+ .find(({ namespace }) => namespace === "resources")
+ ?.patches.find(({ path }) => path[0] === "resource");
+
+ expect(resourcePatch).toMatchObject({
+ value: {
+ name: "Renamed",
+ headers: [{ name: "Authorization", value: '"Bearer token"' }],
+ body: '"request body"',
+ },
+ });
});
test("reports resource create id conflicts", () => {
diff --git a/packages/project-build/src/runtime/data.ts b/packages/project-build/src/runtime/data.ts
index 8c24918c78..5234e28452 100644
--- a/packages/project-build/src/runtime/data.ts
+++ b/packages/project-build/src/runtime/data.ts
@@ -42,8 +42,10 @@ import {
} from "../contracts/patch";
import { createBuilderPatchPayloadFromImmerPatches } from "../state/patch";
import type { BuilderState } from "../state/builder-state";
+import "../state/immer";
import type { BuilderRuntimeContext } from "./context";
import { throwBuilderRuntimeError } from "./errors";
+import { getStaticStringLiteral, replaceTextValue } from "./text-replacement";
import {
getNamedExpressionErrors,
hasExpressionDiagnostics,
@@ -1482,24 +1484,102 @@ const addExpressionIssues = (
}
};
-const resourceFieldsInputBase = resource
- .omit({ id: true })
- .extend({ control: z.enum(["system", "graphql"]).optional() });
+const resourceUrlLiteralPattern = /^(?:[A-Za-z][A-Za-z0-9+.-]*:\/\/|\/)/;
+const resourceExpressionStartPattern = /^\s*(?:["'`[{(]|(?:await|new)\b)/;
+
+const normalizeResourceUrlInput = (value: string) => {
+ if (
+ resourceUrlLiteralPattern.test(value) &&
+ resourceExpressionStartPattern.test(value) === false
+ ) {
+ return JSON.stringify(value);
+ }
+ return value;
+};
+
+const resourceExpressionInput = z
+ .union([
+ z.string(),
+ z.object({ type: z.literal("literal"), value: z.string() }),
+ ])
+ .describe(
+ 'Dynamic JavaScript expression, or { type: "literal", value: string } for fixed text.'
+ );
+
+const resourceExpressionEntryInput = z.object({
+ name: z.string(),
+ value: resourceExpressionInput,
+});
+
+const resourceFieldsInputBase = resource.omit({ id: true }).extend({
+ control: z.enum(["system", "graphql"]).optional(),
+ url: z.preprocess(
+ (value) =>
+ typeof value === "string" ? normalizeResourceUrlInput(value) : value,
+ z.string()
+ ),
+ searchParams: z.array(resourceExpressionEntryInput).optional(),
+ headers: z.array(resourceExpressionEntryInput),
+ body: resourceExpressionInput.optional(),
+});
export const resourceFieldsInput = resourceFieldsInputBase.superRefine(
(fields, context) => {
- addExpressionIssues(context, getResourceExpressionErrors(fields));
- addExpressionIssues(context, getResourceLiteralUrlErrors(fields));
+ const normalizedFields = normalizeResourceFieldsInput(fields);
+ addExpressionIssues(context, getResourceExpressionErrors(normalizedFields));
+ addExpressionIssues(context, getResourceLiteralUrlErrors(normalizedFields));
}
);
export const resourceFieldsUpdateInput = resourceFieldsInputBase
.partial()
.superRefine((fields, context) => {
- addExpressionIssues(context, getResourceExpressionErrors(fields));
- addExpressionIssues(context, getResourceLiteralUrlErrors(fields));
+ const normalizedFields = normalizeResourceFieldsUpdateInput(fields);
+ addExpressionIssues(context, getResourceExpressionErrors(normalizedFields));
+ addExpressionIssues(context, getResourceLiteralUrlErrors(normalizedFields));
});
+const normalizeResourceExpressionInput = (
+ value: z.infer<typeof resourceExpressionInput>
+) => (typeof value === "string" ? value : JSON.stringify(value.value));
+
+type ResourceFields = Omit<Resource, "id">;
+type ResourceFieldsUpdate = Partial<ResourceFields>;
+
+const normalizeResourceFields = (
+ fields: z.infer<typeof resourceFieldsUpdateInput>
+): ResourceFieldsUpdate => {
+ const { searchParams, headers, body, ...scalarFields } = fields;
+ return {
+ ...scalarFields,
+ ...(fields.searchParams === undefined
+ ? {}
+ : {
+ searchParams: fields.searchParams.map((entry) => ({
+ name: entry.name,
+ value: normalizeResourceExpressionInput(entry.value),
+ })),
+ }),
+ ...(fields.headers === undefined
+ ? {}
+ : {
+ headers: fields.headers.map((entry) => ({
+ name: entry.name,
+ value: normalizeResourceExpressionInput(entry.value),
+ })),
+ }),
+ ...(fields.body === undefined
+ ? {}
+ : { body: normalizeResourceExpressionInput(fields.body) }),
+ };
+};
+
+const normalizeResourceFieldsInput = (
+ fields: z.infer<typeof resourceFieldsInput>
+): ResourceFields => normalizeResourceFields(fields) as ResourceFields;
+
+const normalizeResourceFieldsUpdateInput = normalizeResourceFields;
+
export const resourceCreateInput = z.object({
resourceId: runtimeGeneratedIdInput,
resource: resourceFieldsInput,
@@ -1515,6 +1595,34 @@ export const resourceUpdateInput = z.object({
scopeInstanceId: z.string().optional(),
});
+export const replaceResourceTextInput = z.object({
+ find: z.string().min(1).describe("Fixed resource text to find."),
+ replace: z.string().describe("Replacement fixed resource text."),
+ match: z
+ .enum(["exact", "substring"])
+ .default("exact")
+ .describe(
+ 'Use "exact" to replace complete values, or "substring" to replace every literal occurrence in matching values.'
+ ),
+ fields: z
+ .array(z.enum(["name", "url"]))
+ .min(1)
+ .default(["name", "url"])
+ .describe("Resource text fields to replace."),
+ resourceIds: z
+ .array(z.string())
+ .min(1)
+ .optional()
+ .describe("Optional resource ids to limit scope."),
+ limit: z
+ .number()
+ .int()
+ .min(1)
+ .max(200)
+ .default(50)
+ .describe("Maximum number of resource fields to change."),
+});
+
export const resourceUpsertInput = z.object({
resourceId: z.string().optional(),
resource: resourceFieldsInput,
@@ -1583,7 +1691,9 @@ export const createResourceValueFromFormData = ({
}): Resource =>
createResourceValue({
id,
- ...createResourceFieldsFromFormData({ control, name, formData }),
+ ...normalizeResourceFieldsInput(
+ createResourceFieldsFromFormData({ control, name, formData })
+ ),
});
export const createResourceValue = ({
@@ -1889,7 +1999,7 @@ export const createResourceCreatePayload = ({
dataSourceName,
}: {
resourceId: Resource["id"];
- resource: z.infer<typeof resourceFieldsInput>;
+ resource: ResourceFields;
resources: Iterable<Resource>;
dataSources: Iterable<DataSource>;
dataSourceId?: DataSource["id"];
@@ -2147,14 +2257,15 @@ export const createResource = (
input: z.infer<typeof resourceCreateInput>,
context: BuilderRuntimeContext
) => {
- validateResourceFields(input.resource);
+ const resourceInput = normalizeResourceFieldsInput(input.resource);
+ validateResourceFields(resourceInput);
const build = getRequiredBuildData(state);
const resourceId = context.createId();
const dataSourceId =
input.scopeInstanceId === undefined ? undefined : context.createId();
const resultPayload = createResourceCreatePayload({
resourceId,
- resource: input.resource,
+ resource: resourceInput,
resources: build.resources,
dataSources: build.dataSources,
dataSourceId,
@@ -2173,13 +2284,13 @@ export const createResource = (
}
const resource = createResourceValue({
id: resourceId,
- name: input.resource.name,
- control: input.resource.control,
- method: input.resource.method,
- url: input.resource.url,
- searchParams: input.resource.searchParams,
- headers: input.resource.headers,
- body: input.resource.body,
+ name: resourceInput.name,
+ control: resourceInput.control,
+ method: resourceInput.method,
+ url: resourceInput.url,
+ searchParams: resourceInput.searchParams,
+ headers: resourceInput.headers,
+ body: resourceInput.body,
});
return createRuntimeMutation({
payload: createResourceUpsertPatchPayload({
@@ -2219,7 +2330,8 @@ export const updateResource = (
>,
input: z.infer<typeof resourceUpdateInput>
) => {
- validateResourceFields(input.values);
+ const values = normalizeResourceFieldsUpdateInput(input.values);
+ validateResourceFields(values);
const build = getRequiredBuildData(state);
const resource = findResource(build.resources, input.resourceId);
if (resource === undefined) {
@@ -2227,7 +2339,7 @@ export const updateResource = (
}
const directPayload = createResourceUpdatePayload({
resource,
- values: input.values,
+ values,
dataSources: build.dataSources,
dataSourceName: input.dataSourceName,
scopeInstanceId: input.scopeInstanceId,
@@ -2241,7 +2353,7 @@ export const updateResource = (
}
const nextResource = createResourceValue({
...resource,
- ...input.values,
+ ...values,
});
const dataSource = build.dataSources.find(
(dataSource) =>
@@ -2270,6 +2382,79 @@ export const updateResource = (
});
};
+export const replaceResourceText = (
+ state: Pick<BuilderState, "resources">,
+ input: z.infer<typeof replaceResourceTextInput>
+) => {
+ const resourceIds =
+ input.resourceIds === undefined ? undefined : new Set(input.resourceIds);
+ const matches: Array<{
+ resourceId: string;
+ field: "name" | "url";
+ before: string;
+ after: string;
+ }> = [];
+ let matchingFieldCount = 0;
+ for (const resource of getRequiredResources(state).values()) {
+ if (resourceIds !== undefined && resourceIds.has(resource.id) === false) {
+ continue;
+ }
+ const fields: Array<{
+ field: "name" | "url";
+ before: string | undefined;
+ }> = [];
+ if (input.fields.includes("name")) {
+ fields.push({ field: "name", before: resource.name });
+ }
+ if (input.fields.includes("url")) {
+ fields.push({
+ field: "url",
+ before: getStaticStringLiteral(resource.url),
+ });
+ }
+ for (const { field, before } of fields) {
+ if (before === undefined) {
+ continue;
+ }
+ const after = replaceTextValue(before, input);
+ if (after === before) {
+ continue;
+ }
+ matchingFieldCount += 1;
+ if (matches.length >= input.limit) {
+ continue;
+ }
+ if (field === "url") {
+ validateResourceFields({ url: JSON.stringify(after) });
+ }
+ matches.push({ resourceId: resource.id, field, before, after });
+ }
+ }
+ const result = {
+ changedCount: matches.length,
+ matchingFieldCount,
+ truncated: matchingFieldCount > matches.length,
+ matches,
+ };
+ return createRuntimeMutation({
+ payload:
+ matches.length === 0
+ ? []
+ : [
+ {
+ namespace: "resources",
+ patches: matches.map(({ resourceId, field, after }) => ({
+ op: "replace" as const,
+ path: [resourceId, field],
+ value: field === "url" ? JSON.stringify(after) : after,
+ })),
+ },
+ ],
+ result,
+ invalidatesNamespaces: matches.length === 0 ? [] : ["resources"],
+ });
+};
+
export const upsertResource = (
state: Pick<
BuilderState,
@@ -2286,7 +2471,8 @@ export const upsertResource = (
input: z.infer<typeof resourceUpsertInput>,
context: BuilderRuntimeContext
) => {
- validateResourceFields(input.resource);
+ const resourceInput = normalizeResourceFieldsInput(input.resource);
+ validateResourceFields(resourceInput);
const build = getRequiredBuildData(state);
if (
input.resourceId !== undefined &&
@@ -2307,13 +2493,13 @@ export const upsertResource = (
const dataSourceId = input.dataSourceId ?? context.createId();
const resource = createResourceValue({
id: resourceId,
- name: input.resource.name,
- control: input.resource.control,
- method: input.resource.method,
- url: input.resource.url,
- searchParams: input.resource.searchParams,
- headers: input.resource.headers,
- body: input.resource.body,
+ name: resourceInput.name,
+ control: resourceInput.control,
+ method: resourceInput.method,
+ url: resourceInput.url,
+ searchParams: resourceInput.searchParams,
+ headers: resourceInput.headers,
+ body: resourceInput.body,
});
return createRuntimeMutation({
@@ -2355,7 +2541,8 @@ export const upsertResourceProp = (
input: z.infer<typeof resourcePropUpsertInput>,
context: BuilderRuntimeContext
) => {
- validateResourceFields(input.resource);
+ const resourceInput = normalizeResourceFieldsInput(input.resource);
+ validateResourceFields(resourceInput);
const build = getRequiredBuildData(state);
if (
build.instances.some((instance) => instance.id === input.instanceId) ===
@@ -2373,13 +2560,13 @@ export const upsertResourceProp = (
const resourceId = input.resourceId ?? context.createId();
const resource = createResourceValue({
id: resourceId,
- name: input.resource.name,
- control: input.resource.control,
- method: input.resource.method,
- url: input.resource.url,
- searchParams: input.resource.searchParams,
- headers: input.resource.headers,
- body: input.resource.body,
+ name: resourceInput.name,
+ control: resourceInput.control,
+ method: resourceInput.method,
+ url: resourceInput.url,
+ searchParams: resourceInput.searchParams,
+ headers: resourceInput.headers,
+ body: resourceInput.body,
});
const dataSource = build.dataSources.find(
(dataSource) =>
diff --git a/packages/project-build/src/runtime/fonts.ts b/packages/project-build/src/runtime/fonts.ts
new file mode 100644
index 0000000000..eb2edd4a65
--- /dev/null
+++ b/packages/project-build/src/runtime/fonts.ts
@@ -0,0 +1,61 @@
+import { SYSTEM_FONTS } from "@webstudio-is/fonts";
+import { z } from "zod";
+import type { BuilderState } from "../state/builder-state";
+import { throwBuilderRuntimeError } from "./errors";
+
+export const fontListInput = z.object({
+ includeSystem: z
+ .boolean()
+ .default(true)
+ .describe("Include built-in system font stacks."),
+});
+
+export const listFonts = (
+ state: Pick<BuilderState, "assets">,
+ input: z.infer<typeof fontListInput>
+) => {
+ if (state.assets === undefined) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "Assets namespace is missing"
+ );
+ }
+ const uploadedByFamily = new Map<
+ string,
+ Array<{
+ assetId: string;
+ format: string;
+ style?: string;
+ weight?: number;
+ variable: boolean;
+ }>
+ >();
+ for (const asset of state.assets.values()) {
+ if (asset.type !== "font") {
+ continue;
+ }
+ const entries = uploadedByFamily.get(asset.meta.family) ?? [];
+ entries.push({
+ assetId: asset.id,
+ format: asset.format,
+ ...("style" in asset.meta ? { style: asset.meta.style } : {}),
+ ...("weight" in asset.meta ? { weight: asset.meta.weight } : {}),
+ variable: "variationAxes" in asset.meta,
+ });
+ uploadedByFamily.set(asset.meta.family, entries);
+ }
+ const uploaded = Array.from(uploadedByFamily, ([family, assets]) => ({
+ family,
+ source: "uploaded" as const,
+ assets,
+ })).sort((left, right) => left.family.localeCompare(right.family));
+ const system = input.includeSystem
+ ? Array.from(SYSTEM_FONTS, ([family, config]) => ({
+ family,
+ source: "system" as const,
+ stack: config.stack,
+ description: config.description,
+ }))
+ : [];
+ return { uploaded, system };
+};
diff --git a/packages/project-build/src/runtime/instances.test.ts b/packages/project-build/src/runtime/instances.test.ts
index 8897e80884..a95964335b 100644
--- a/packages/project-build/src/runtime/instances.test.ts
+++ b/packages/project-build/src/runtime/instances.test.ts
@@ -45,6 +45,7 @@ import {
listInstances,
deleteInstances,
moveInstances,
+ replaceTextInput,
serializeTextNodes,
setInstanceLabel,
setInstanceTag,
@@ -61,6 +62,17 @@ import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";
const runtimeContext = { createId: () => "generated" };
+test("rejects conflicting page selectors for text replacement", () => {
+ expect(
+ replaceTextInput.safeParse({
+ find: "Old",
+ replace: "New",
+ pageId: "home",
+ pagePath: "/other",
+ }).success
+ ).toBe(false);
+});
+
const createInstance = (
id: Instance["id"],
componentOrChildren: string | Instance["children"] = [],
@@ -409,6 +421,57 @@ test("creates instance clone payload with child references and props", () => {
],
});
});
+
+test("preserves asset references when cloning instance props", () => {
+ const ids = ["source-copy", "asset-prop-copy"];
+ const result = createInstanceClonePayload({
+ instances: new Map([
+ ["source", createCloneInstance("source")],
+ ["parent", createCloneInstance("parent")],
+ ]),
+ sourceInstanceId: "source",
+ targetParent: createCloneInstance("parent"),
+ insertIndex: 0,
+ props: [
+ {
+ id: "image-src",
+ instanceId: "source",
+ name: "src",
+ type: "asset",
+ value: "hero-image",
+ },
+ ],
+ styleSourceSelections: [],
+ styleSources: [],
+ styles: new Map(),
+ createId: () => ids.shift() ?? "missing",
+ });
+
+ if (result === undefined) {
+ throw new Error(
+ "Expected valid source instance to produce a clone payload"
+ );
+ }
+ const propsPayload = result.payload.find(
+ (item) => item.namespace === "props"
+ );
+ expect(propsPayload).toEqual({
+ namespace: "props",
+ patches: [
+ {
+ op: "add",
+ path: [expect.any(String)],
+ value: {
+ id: expect.any(String),
+ instanceId: "source-copy",
+ name: "src",
+ type: "asset",
+ value: "hero-image",
+ },
+ },
+ ],
+ });
+});
describe("text content utils", () => {
test("creates text and expression children", () => {
expect(createTextContentChild({ type: "text", value: "Hello" })).toEqual({
@@ -2154,6 +2217,64 @@ test("updates text editing tree and removes stale descendants", () => {
expect(data.instances.has("old-link")).toBe(false);
});
+test("removes props from rich-text descendants removed by text editing", () => {
+ const data = {
+ instances: new Map<Instance["id"], Instance>([
+ [
+ "root",
+ createInstance("root", elementComponent, [
+ { type: "id", value: "link" },
+ ]),
+ ],
+ [
+ "link",
+ createInstance("link", elementComponent, [
+ { type: "text", value: "Read more" },
+ ]),
+ ],
+ ]),
+ props: new Map<Prop["id"], Prop>([
+ [
+ "link-href",
+ {
+ id: "link-href",
+ instanceId: "link",
+ name: "href",
+ type: "string",
+ value: "/read-more",
+ },
+ ],
+ ]),
+ dataSources: new Map<DataSource["id"], DataSource>(),
+ styleSources: new Map<StyleSource["id"], StyleSource>(),
+ styleSourceSelections: new Map<
+ StyleSourceSelection["instanceId"],
+ StyleSourceSelection
+ >(),
+ styles: new Map<string, StyleDecl>(),
+ };
+ const result = updateTextTree(
+ data,
+ {
+ rootInstanceId: "root",
+ instances: [
+ createInstance("root", elementComponent, [
+ { type: "text", value: "Read more" },
+ ]),
+ ],
+ },
+ runtimeContext
+ );
+
+ applyBuilderPatchPayloadMutable(
+ (namespace) => data[namespace as keyof typeof data],
+ result.payload
+ );
+
+ expect(data.instances.has("link")).toBe(false);
+ expect(data.props.has("link-href")).toBe(false);
+});
+
test("runtime remaps text editing temporary ids before persisting", () => {
const data = {
instances: new Map<Instance["id"], Instance>([
diff --git a/packages/project-build/src/runtime/instances.ts b/packages/project-build/src/runtime/instances.ts
index 74a1253a68..c236440298 100644
--- a/packages/project-build/src/runtime/instances.ts
+++ b/packages/project-build/src/runtime/instances.ts
@@ -23,9 +23,11 @@ import {
import type { BuilderState } from "../state/builder-state";
import type { BuilderRuntimeContext } from "./context";
import { throwBuilderRuntimeError } from "./errors";
+import { replaceTextValue } from "./text-replacement";
import { getExpressionErrors } from "./expression-validation";
import { createRuntimeMutation } from "./mutation";
import { findSerializedPageByInput, getSerializedPages } from "./pages";
+import { validatePageSelector } from "./page-selector";
import {
createPropClonePatches,
createPropDeletePayload,
@@ -526,7 +528,7 @@ const getWebstudioDataNamespace = (
data: WebstudioData,
namespace: BuilderPatchChange["namespace"]
) => {
- if (namespace === "marketplaceProduct") {
+ if (namespace === "marketplaceProduct" || namespace === "projectSettings") {
return;
}
return data[namespace];
@@ -733,6 +735,28 @@ export const cloneInstanceWithNewIds = ({
),
});
+export const replaceTextInput = z
+ .object({
+ find: z.string().min(1).describe("Literal text to find."),
+ replace: z.string().describe("Replacement literal text."),
+ match: z
+ .enum(["exact", "substring"])
+ .default("exact")
+ .describe(
+ 'Use "exact" to replace complete text children, or "substring" to replace every literal occurrence inside matching text children.'
+ ),
+ pageId: z.string().optional(),
+ pagePath: z.string().optional(),
+ limit: z
+ .number()
+ .int()
+ .min(1)
+ .max(200)
+ .default(50)
+ .describe("Maximum number of text children to replace."),
+ })
+ .superRefine(validatePageSelector);
+
export const cloneInstanceSubtree = ({
instances,
rootInstanceId,
@@ -2987,7 +3011,15 @@ export const deleteInstanceBySelector = (
};
export const updateTextTree = (
- state: Pick<BuilderState, "instances">,
+ state: Pick<
+ BuilderState,
+ | "instances"
+ | "props"
+ | "dataSources"
+ | "styleSources"
+ | "styleSourceSelections"
+ | "styles"
+ >,
input: z.infer<typeof updateTextTreeInput>,
context: BuilderRuntimeContext
) => {
@@ -3031,14 +3063,39 @@ export const updateTextTree = (
`Updated text tree instance "${error.instanceId}" references missing child "${error.childId}"`
);
}
+ const removedInstanceIds = new Set(
+ Array.from(findTreeInstanceIds(instances, input.rootInstanceId)).filter(
+ (instanceId) =>
+ remapped.updates.some((instance) => instance.id === instanceId) ===
+ false
+ )
+ );
+ const instancePatches = payload.flatMap((change) =>
+ change.namespace === "instances"
+ ? change.patches.filter(
+ (patch) => patch.op !== "remove" || patch.path.length !== 1
+ )
+ : []
+ );
+ const cleanupPayload = createInstanceCleanupPayload({
+ instanceIds: removedInstanceIds,
+ props: state.props?.values() ?? [],
+ dataSources: state.dataSources?.values() ?? [],
+ styleSources: state.styleSources?.values() ?? [],
+ styleSourceSelections: state.styleSourceSelections?.values() ?? [],
+ styles: state.styles?.values() ?? [],
+ });
return createRuntimeMutation({
- payload,
+ payload: compactBuilderPatchPayload([
+ { namespace: "instances", patches: instancePatches },
+ ...cleanupPayload,
+ ]),
result: {
rootInstanceId: input.rootInstanceId,
instanceIds: remapped.updates.map((instance) => instance.id),
idMap: Object.fromEntries(remapped.idMap),
},
- invalidatesNamespaces: ["instances"],
+ invalidatesNamespaces: treeInvalidates,
});
};
@@ -3102,7 +3159,8 @@ export const cloneInstance = (
export const serializeInstanceSummary = (
instance: Instance,
- depth: number
+ depth: number,
+ parent?: { id: Instance["id"]; index: number }
) => ({
id: instance.id,
component: instance.component,
@@ -3110,8 +3168,51 @@ export const serializeInstanceSummary = (
label: instance.label,
childCount: instance.children.length,
depth,
+ parentId: parent?.id,
+ indexWithinParent: parent?.index,
});
+const getInstanceParents = (instances: Instances) => {
+ const parents = new Map<
+ Instance["id"],
+ { id: Instance["id"]; index: number }
+ >();
+ for (const instance of instances.values()) {
+ for (const [index, child] of instance.children.entries()) {
+ if (child.type === "id") {
+ parents.set(child.value, { id: instance.id, index });
+ }
+ }
+ }
+ return parents;
+};
+
+const getInstanceAncestors = (
+ instances: Instances,
+ instanceId: Instance["id"]
+) => {
+ const parents = getInstanceParents(instances);
+ const ancestorPath = [];
+ const visited = new Set<Instance["id"]>();
+ let parent = parents.get(instanceId);
+ while (parent !== undefined) {
+ if (visited.has(parent.id)) {
+ break;
+ }
+ visited.add(parent.id);
+ const instance = instances.get(parent.id);
+ if (instance === undefined) {
+ break;
+ }
+ ancestorPath.push({ instance, childIndex: parent.index });
+ parent = parents.get(parent.id);
+ }
+ return ancestorPath.reverse().map(({ instance, childIndex }, depth) => ({
+ ...serializeInstanceSummary(instance, depth, parents.get(instance.id)),
+ childIndex,
+ }));
+};
+
export const isTextContentChild = (
child: Instance["children"][number] | undefined
): child is TextContentChild =>
@@ -3325,6 +3426,7 @@ export const listInstances = (
? getPageFilteredRootInstanceIds(state, input)
: [input.rootInstanceId];
const depths = getInstanceDepths(instances, rootInstanceIds);
+ const parents = getInstanceParents(instances);
const results = [];
for (const [instanceId, depth] of depths) {
const instance = instances.get(instanceId);
@@ -3352,7 +3454,9 @@ export const listInstances = (
) {
continue;
}
- results.push(serializeInstanceSummary(instance, depth));
+ results.push(
+ serializeInstanceSummary(instance, depth, parents.get(instance.id))
+ );
}
return { instances: results };
};
@@ -3394,7 +3498,9 @@ export const inspectInstance = (
>,
input: {
instanceId: string;
- include?: Array<"props" | "styles" | "children" | "bindings" | "sources">;
+ include?: Array<
+ "props" | "styles" | "children" | "bindings" | "sources" | "ancestors"
+ >;
childDepth?: number;
}
) => {
@@ -3404,11 +3510,16 @@ export const inspectInstance = (
return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");
}
const depths = getInstanceDepths(instances, [input.instanceId]);
+ const parents = getInstanceParents(instances);
const include = new Set(input.include ?? []);
const details: Record<string, unknown> = serializeInstanceSummary(
instance,
- depths.get(instance.id) ?? 0
+ depths.get(instance.id) ?? 0,
+ parents.get(instance.id)
);
+ if (include.has("ancestors")) {
+ details.ancestors = getInstanceAncestors(instances, instance.id);
+ }
if (include.has("props")) {
details.props = Array.from(state.props?.values() ?? []).filter(
(prop) => prop.instanceId === instance.id
@@ -3430,7 +3541,11 @@ export const inspectInstance = (
return depth !== undefined && depth > 0 && depth <= maxDepth;
})
.map((child) =>
- serializeInstanceSummary(child, depths.get(child.id) ?? 0)
+ serializeInstanceSummary(
+ child,
+ depths.get(child.id) ?? 0,
+ parents.get(child.id)
+ )
);
}
if (include.has("bindings")) {
@@ -3498,6 +3613,74 @@ export const updateTextInstance = (
});
};
+export const replaceText = (
+ state: Pick<BuilderState, "pages" | "instances">,
+ input: z.infer<typeof replaceTextInput>
+) => {
+ const instances = getRequiredInstances(state);
+ const rootInstanceIds = getPageFilteredRootInstanceIds(state, input);
+ const instanceIds = new Set(
+ getInstanceDepths(instances, rootInstanceIds).keys()
+ );
+ const matches: Array<{
+ instanceId: string;
+ childIndex: number;
+ before: string;
+ after: string;
+ }> = [];
+ let matchingChildCount = 0;
+
+ for (const instance of instances.values()) {
+ if (instanceIds.has(instance.id) === false) {
+ continue;
+ }
+ for (const [childIndex, child] of instance.children.entries()) {
+ if (child.type !== "text") {
+ continue;
+ }
+ const after = replaceTextValue(child.value, input);
+ if (after === child.value) {
+ continue;
+ }
+ matchingChildCount += 1;
+ if (matches.length < input.limit) {
+ matches.push({
+ instanceId: instance.id,
+ childIndex,
+ before: child.value,
+ after,
+ });
+ }
+ }
+ }
+
+ return createRuntimeMutation({
+ payload:
+ matches.length === 0
+ ? []
+ : [
+ {
+ namespace: "instances",
+ patches: matches.map((match) => ({
+ op: "replace" as const,
+ path: [match.instanceId, "children", match.childIndex],
+ value: createTextContentChild({
+ type: "text",
+ value: match.after,
+ }),
+ })),
+ },
+ ],
+ result: {
+ changedCount: matches.length,
+ matchingChildCount,
+ truncated: matchingChildCount > matches.length,
+ matches,
+ },
+ invalidatesNamespaces: matches.length === 0 ? [] : ["instances"],
+ });
+};
+
export const setTextContent = (
state: Pick<BuilderState, "instances">,
input: z.infer<typeof setTextContentInput>
diff --git a/packages/project-build/src/runtime/migrations.ts b/packages/project-build/src/runtime/migrations.ts
index 01d5327418..214e4c0b0e 100644
--- a/packages/project-build/src/runtime/migrations.ts
+++ b/packages/project-build/src/runtime/migrations.ts
@@ -1,17 +1,14 @@
-import { enableMapSet, enablePatches, produceWithPatches } from "immer";
+import { produceWithPatches } from "immer";
import { z } from "zod";
import type { WebstudioData } from "@webstudio-is/sdk";
import { migrateWebstudioDataMutable } from "@webstudio-is/project-migrations";
import type { BuilderNamespace } from "../contracts/namespaces";
import { createBuilderPatchPayloadFromImmerPatches } from "../state/patch";
import type { BuilderState } from "../state/builder-state";
+import "../state/immer";
import { breakCyclesMutable, findCycles } from "../shared/graph-utils";
import { createRuntimeMutation } from "./mutation";
-// Migration patch generation uses Immer patches against Map-backed namespaces.
-enableMapSet();
-enablePatches();
-
const webstudioDataNamespaces = [
"pages",
"instances",
diff --git a/packages/project-build/src/runtime/page-selector.ts b/packages/project-build/src/runtime/page-selector.ts
new file mode 100644
index 0000000000..82e453a6c3
--- /dev/null
+++ b/packages/project-build/src/runtime/page-selector.ts
@@ -0,0 +1,14 @@
+import { z } from "zod";
+
+export const validatePageSelector = (
+ input: { pageId?: string; pagePath?: string },
+ context: z.RefinementCtx
+) => {
+ if (input.pageId !== undefined && input.pagePath !== undefined) {
+ context.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["pagePath"],
+ message: "pageId and pagePath are mutually exclusive",
+ });
+ }
+};
diff --git a/packages/project-build/src/runtime/pages.test.ts b/packages/project-build/src/runtime/pages.test.ts
index 551653a9f2..792e6688a9 100644
--- a/packages/project-build/src/runtime/pages.test.ts
+++ b/packages/project-build/src/runtime/pages.test.ts
@@ -1192,14 +1192,12 @@ describe("page input schemas", () => {
},
})
).toEqual([
+ expect.stringMatching(/^title: .*Plain fixed text is accepted/),
expect.stringMatching(
- /^title: .*For fixed text, pass a string literal expression/
+ /^meta.description: .*Plain fixed text is accepted/
),
expect.stringMatching(
- /^meta.description: .*For fixed text, pass a string literal expression/
- ),
- expect.stringMatching(
- /^meta.custom.0.content: .*For fixed text, pass a string literal expression/
+ /^meta.custom.0.content: .*Plain fixed text is accepted/
),
]);
});
@@ -1810,7 +1808,7 @@ describe("createPage", () => {
},
{ createId: createIdFactory() }
)
- ).toThrow(/title: .*stores JavaScript expression source/);
+ ).toThrow(/title: .*Plain fixed text is accepted/);
});
});
@@ -1869,7 +1867,7 @@ describe("updatePage", () => {
},
}
)
- ).toThrow(/title: .*stores JavaScript expression source/);
+ ).toThrow(/title: .*Plain fixed text is accepted/);
});
test("rejects updated page paths with unsupported URL pattern syntax", () => {
diff --git a/packages/project-build/src/runtime/pages.ts b/packages/project-build/src/runtime/pages.ts
index 37df70c69b..ead1fd7a3d 100644
--- a/packages/project-build/src/runtime/pages.ts
+++ b/packages/project-build/src/runtime/pages.ts
@@ -795,7 +795,7 @@ const pageMetaExpressionFields = [
] as const satisfies readonly (keyof PageMetaPatchInput)[];
export const pageExpressionFieldHint =
- 'This field stores JavaScript expression source. For fixed text, pass a string literal expression, for example "\\"Plans for teams\\"". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.';
+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass JavaScript expression code such as `pageTitle ?? "Plans for teams"`.';
const jsExpressionStartPattern =
/^\s*(?:["'`[{(]|(?:await|new|typeof|void)\b|(?:undefined|null|true|false)\s*$)/;
diff --git a/packages/project-build/src/runtime/project-settings.test.ts b/packages/project-build/src/runtime/project-settings.test.ts
index 28685583c8..d935d2f44e 100644
--- a/packages/project-build/src/runtime/project-settings.test.ts
+++ b/packages/project-build/src/runtime/project-settings.test.ts
@@ -30,9 +30,11 @@ import {
const createState = (): BuilderState =>
({
pages: {
+ redirects: [{ old: "/old", new: "/new", status: "301" }],
+ },
+ projectSettings: {
meta: { siteName: "Existing site", faviconAssetId: "old-asset" },
compiler: { atomicStyles: true },
- redirects: [{ old: "/old", new: "/new", status: "301" }],
},
breakpoints: new Map([
["base", { id: "base", label: "Base" }],
@@ -129,7 +131,7 @@ describe("project settings runtime", () => {
});
});
- test("reads project settings from pages namespace", () => {
+ test("reads project settings from their first-class namespace", () => {
expect(getProjectSettings(createState())).toEqual({
meta: { siteName: "Existing site", faviconAssetId: "old-asset" },
compiler: { atomicStyles: true },
@@ -140,19 +142,28 @@ describe("project settings runtime", () => {
test("updates project meta and compiler settings", () => {
expect(
updateProjectSettings(createState(), {
- meta: { siteName: "New site", faviconAssetId: null },
+ meta: {
+ siteName: "New site",
+ faviconAssetId: null,
+ agentInstructions: "Use existing design tokens.",
+ },
compiler: { atomicStyles: false },
})
).toEqual({
kind: "mutation",
- invalidatesNamespaces: ["pages"],
+ invalidatesNamespaces: ["projectSettings"],
noop: false,
result: { updated: true },
payload: [
{
- namespace: "pages",
+ namespace: "projectSettings",
patches: [
{ op: "replace", path: ["meta", "siteName"], value: "New site" },
+ {
+ op: "add",
+ path: ["meta", "agentInstructions"],
+ value: "Use existing design tokens.",
+ },
{ op: "remove", path: ["meta", "faviconAssetId"] },
{
op: "replace",
@@ -284,11 +295,11 @@ describe("project settings runtime", () => {
test("creates project meta and compiler settings when missing", () => {
const state = createState();
- if (state.pages === undefined) {
- throw new Error("Expected pages");
+ if (state.projectSettings === undefined) {
+ throw new Error("Expected project settings");
}
- state.pages.meta = undefined;
- state.pages.compiler = undefined;
+ state.projectSettings.meta = {};
+ state.projectSettings.compiler = {};
expect(
updateProjectSettings(state, {
@@ -297,15 +308,19 @@ describe("project settings runtime", () => {
})
).toEqual({
kind: "mutation",
- invalidatesNamespaces: ["pages"],
+ invalidatesNamespaces: ["projectSettings"],
noop: false,
result: { updated: true },
payload: [
{
- namespace: "pages",
+ namespace: "projectSettings",
patches: [
- { op: "add", path: ["meta"], value: { siteName: "New site" } },
- { op: "add", path: ["compiler"], value: { atomicStyles: true } },
+ { op: "add", path: ["meta", "siteName"], value: "New site" },
+ {
+ op: "add",
+ path: ["compiler", "atomicStyles"],
+ value: true,
+ },
],
},
],
@@ -320,7 +335,7 @@ describe("project settings runtime", () => {
})
).toEqual({
kind: "mutation",
- invalidatesNamespaces: ["pages"],
+ invalidatesNamespaces: [],
noop: true,
result: { updated: true },
payload: [],
diff --git a/packages/project-build/src/runtime/project-settings.ts b/packages/project-build/src/runtime/project-settings.ts
index 2cd5326ced..16eb4ad261 100644
--- a/packages/project-build/src/runtime/project-settings.ts
+++ b/packages/project-build/src/runtime/project-settings.ts
@@ -47,6 +47,18 @@ const getRequiredBreakpoints = (state: Pick<BuilderState, "breakpoints">) => {
return state.breakpoints;
};
+const getRequiredProjectSettings = (
+ state: Pick<BuilderState, "projectSettings">
+) => {
+ if (state.projectSettings === undefined) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "Project settings namespace is missing"
+ );
+ }
+ return state.projectSettings;
+};
+
type Settable<T> = {
[Property in keyof T]?: T[Property] | null;
};
@@ -195,11 +207,14 @@ const parseCompilerSettings = (input: Record<string, unknown>) => {
return values;
};
-export const getProjectSettings = (state: Pick<BuilderState, "pages">) => {
+export const getProjectSettings = (
+ state: Pick<BuilderState, "pages" | "projectSettings">
+) => {
const pages = getRequiredPages(state);
+ const settings = getRequiredProjectSettings(state);
return {
- meta: pages.meta ?? {},
- compiler: pages.compiler ?? {},
+ meta: settings.meta,
+ compiler: settings.compiler,
redirects: pages.redirects ?? [],
};
};
@@ -239,17 +254,17 @@ const pushObjectFieldPatches = ({
};
export const updateProjectSettings = (
- state: Pick<BuilderState, "pages">,
+ state: Pick<BuilderState, "projectSettings">,
input: z.infer<typeof projectSettingsUpdateInput>
) => {
- const pages = getRequiredPages(state);
+ const settings = getRequiredProjectSettings(state);
const patches: BuilderPatchChange["patches"] = [];
if (input.meta !== undefined) {
const values = parseProjectMeta(input.meta);
pushObjectFieldPatches({
patches,
basePath: ["meta"],
- current: pages.meta,
+ current: settings.meta,
values,
});
}
@@ -258,14 +273,16 @@ export const updateProjectSettings = (
pushObjectFieldPatches({
patches,
basePath: ["compiler"],
- current: pages.compiler,
+ current: settings.compiler,
values,
});
}
return createRuntimeMutation({
- payload: compactBuilderPatchPayload([{ namespace: "pages", patches }]),
+ payload: compactBuilderPatchPayload([
+ { namespace: "projectSettings", patches },
+ ]),
result: { updated: true },
- invalidatesNamespaces: ["pages"],
+ invalidatesNamespaces: patches.length === 0 ? [] : ["projectSettings"],
});
};
diff --git a/packages/project-build/src/runtime/props.test.ts b/packages/project-build/src/runtime/props.test.ts
index 7bba60bc42..f4de0f753a 100644
--- a/packages/project-build/src/runtime/props.test.ts
+++ b/packages/project-build/src/runtime/props.test.ts
@@ -20,6 +20,7 @@ import {
propBindingInput,
propUpdatesInput,
propValueInput,
+ replacePropText,
showAttributeMeta,
updateProps,
validatePrimitiveValue,
@@ -42,6 +43,75 @@ const prop = (name: string, overrides: Partial<Prop> = {}): Prop =>
...overrides,
}) as Prop;
+test("validates only prop replacements selected by the limit", () => {
+ const jsonLd: Instance = {
+ type: "instance",
+ id: "json-ld",
+ component: "JsonLd",
+ children: [],
+ };
+ const result = replacePropText(
+ {
+ instances: new Map([
+ [image.id, image],
+ [jsonLd.id, jsonLd],
+ ]),
+ props: new Map([
+ ["first", prop("title", { id: "first", value: "old" })],
+ [
+ "second",
+ {
+ id: "second",
+ instanceId: jsonLd.id,
+ name: "code",
+ type: "string",
+ value: '{"name":"old"}',
+ } satisfies Prop,
+ ],
+ ]),
+ },
+ {
+ find: "old",
+ replace: '"',
+ match: "substring",
+ limit: 1,
+ }
+ );
+
+ expect(result).toMatchObject({
+ result: {
+ changedCount: 1,
+ matchingPropCount: 2,
+ truncated: true,
+ matches: [{ propId: "first", before: "old", after: '"' }],
+ },
+ });
+});
+
+test("does not invalidate props when text replacement finds no matches", () => {
+ const result = replacePropText(
+ {
+ instances: new Map([[image.id, image]]),
+ props: new Map([
+ ["title", prop("title", { id: "title", value: "Existing" })],
+ ]),
+ },
+ {
+ find: "Not present",
+ replace: "Replacement",
+ match: "substring",
+ limit: 100,
+ }
+ );
+
+ expect(result.payload).toEqual([]);
+ expect(result.invalidatesNamespaces).toEqual([]);
+ expect(result.result).toMatchObject({
+ changedCount: 0,
+ matchingPropCount: 0,
+ });
+});
+
test("rejects client-supplied prop ids on prop upsert inputs", () => {
expect(
propValueInput.safeParse({
@@ -460,6 +530,87 @@ describe("updateProps", () => {
).toThrow("Entered HTML has a validation error.");
});
+ test("validates JsonLd code updates", () => {
+ const jsonLd: Instance = {
+ type: "instance",
+ id: "json-ld-id",
+ component: "JsonLd",
+ children: [],
+ };
+ const state = {
+ instances: new Map([[jsonLd.id, jsonLd]]),
+ props: new Map(),
+ };
+
+ expect(() =>
+ updateProps(
+ state,
+ {
+ updates: [
+ {
+ instanceId: jsonLd.id,
+ name: "code",
+ type: "string",
+ value: "not json",
+ },
+ ],
+ },
+ { createId: () => "code-prop-id" }
+ )
+ ).toThrow("JSON-LD $: JSON-LD must be a valid JSON object or array.");
+
+ expect(() =>
+ updateProps(
+ state,
+ {
+ updates: [
+ {
+ instanceId: jsonLd.id,
+ name: "code",
+ type: "string",
+ value: '{"@context":"https://schema.org","@type":1}',
+ },
+ ],
+ },
+ { createId: () => "code-prop-id" }
+ )
+ ).toThrow('JSON-LD $["@type"]: @type must be a non-empty string');
+
+ expect(() =>
+ updateProps(
+ state,
+ {
+ updates: [
+ {
+ instanceId: jsonLd.id,
+ name: "code",
+ type: "json",
+ value: { "@context": "https://schema.org" },
+ },
+ ],
+ },
+ { createId: () => "code-prop-id" }
+ )
+ ).toThrow('JSON-LD code must use prop type "string".');
+
+ expect(() =>
+ updateProps(
+ state,
+ {
+ updates: [
+ {
+ instanceId: jsonLd.id,
+ name: "code",
+ type: "string",
+ value: '{"@context":"https://schema.org"}',
+ },
+ ],
+ },
+ { createId: () => "code-prop-id" }
+ )
+ ).not.toThrow();
+ });
+
test("allows non-html code props to use plain strings", () => {
const codeText: Instance = {
type: "instance",
diff --git a/packages/project-build/src/runtime/props.ts b/packages/project-build/src/runtime/props.ts
index e61926da22..8c4edc5c0f 100644
--- a/packages/project-build/src/runtime/props.ts
+++ b/packages/project-build/src/runtime/props.ts
@@ -5,8 +5,10 @@ import {
type Prop,
type PropMeta,
} from "@webstudio-is/sdk";
+import { validateJsonLd } from "@webstudio-is/sdk/runtime";
import type { BuilderState } from "../state/builder-state";
import { throwBuilderRuntimeError } from "./errors";
+import { replaceTextValue } from "./text-replacement";
import { getExpressionErrors } from "./expression-validation";
import { runtimeGeneratedIdInput } from "./generated-id-input";
import { validateHtmlEmbedCode } from "./html";
@@ -252,6 +254,36 @@ export const propUpdatesInput = z.object({
),
});
+export const replacePropTextInput = z.object({
+ find: z.string().min(1).describe("Fixed prop text to find."),
+ replace: z.string().describe("Replacement fixed prop text."),
+ match: z
+ .enum(["exact", "substring"])
+ .default("exact")
+ .describe(
+ 'Use "exact" to replace complete prop values, or "substring" to replace every literal occurrence in matching prop values.'
+ ),
+ instanceIds: z
+ .array(z.string())
+ .min(1)
+ .optional()
+ .describe("Optional instance ids to limit the replacement scope."),
+ names: z
+ .array(z.string())
+ .min(1)
+ .optional()
+ .describe(
+ "Optional prop names to limit the replacement scope, such as href or code."
+ ),
+ limit: z
+ .number()
+ .int()
+ .min(1)
+ .max(200)
+ .default(50)
+ .describe("Maximum number of prop values to change."),
+});
+
export type PropValueInput = z.infer<typeof propValueInput>;
export type PropValueUpdate =
| Pick<Extract<Prop, { type: "number" }>, "type" | "value">
@@ -731,6 +763,19 @@ const getHtmlEmbedCodeErrors = (instance: Instance, update: PropValueInput) => {
return error === undefined ? [] : [error.message];
};
+const getJsonLdCodeErrors = (instance: Instance, update: PropValueInput) => {
+ if (instance.component !== "JsonLd" || update.name !== "code") {
+ return [];
+ }
+ if (update.type !== "string") {
+ return ['JSON-LD code must use prop type "string".'];
+ }
+ const result = validateJsonLd(update.value);
+ return result.diagnostics
+ .filter(({ severity }) => severity === "error")
+ .map(({ path, message }) => `JSON-LD ${path}: ${message}`);
+};
+
export const updateProps = (
state: Pick<BuilderState, "instances" | "props">,
input: z.infer<typeof propUpdatesInput>,
@@ -741,8 +786,12 @@ export const updateProps = (
assertRuntimeInstance(instances, update.instanceId);
const instance = instances.get(update.instanceId)!;
const htmlEmbedCodeErrors = getHtmlEmbedCodeErrors(instance, update);
- if (htmlEmbedCodeErrors.length > 0) {
- return throwPropErrors(htmlEmbedCodeErrors);
+ const codeErrors = [
+ ...htmlEmbedCodeErrors,
+ ...getJsonLdCodeErrors(instance, update),
+ ];
+ if (codeErrors.length > 0) {
+ return throwPropErrors(codeErrors);
}
const existing = findProp(props.values(), update.instanceId, update.name);
const nextProp = createValidatedPropValueFromInput(
@@ -765,6 +814,93 @@ export const updateProps = (
});
};
+export const replacePropText = (
+ state: Pick<BuilderState, "instances" | "props">,
+ input: z.infer<typeof replacePropTextInput>
+) => {
+ const { instances, props } = getRequiredPropState(state);
+ const instanceIds =
+ input.instanceIds === undefined ? undefined : new Set(input.instanceIds);
+ const names = input.names === undefined ? undefined : new Set(input.names);
+ const matches: Array<{
+ propId: string;
+ instanceId: string;
+ name: string;
+ before: string;
+ after: string;
+ }> = [];
+ let matchingPropCount = 0;
+ for (const prop of props.values()) {
+ if (
+ prop.type !== "string" ||
+ (instanceIds !== undefined &&
+ instanceIds.has(prop.instanceId) === false) ||
+ (names !== undefined && names.has(prop.name) === false)
+ ) {
+ continue;
+ }
+ const after = replaceTextValue(prop.value, input);
+ if (after === prop.value) {
+ continue;
+ }
+ matchingPropCount += 1;
+ if (matches.length >= input.limit) {
+ continue;
+ }
+ const instance = instances.get(prop.instanceId);
+ if (instance?.component === "HtmlEmbed" && prop.name === "code") {
+ const error = validateHtmlEmbedCode(after);
+ if (error !== undefined) {
+ return throwPropErrors([error.message]);
+ }
+ }
+ if (instance?.component === "JsonLd" && prop.name === "code") {
+ const result = validateJsonLd(after);
+ if (result.success === false) {
+ return throwPropErrors(
+ result.diagnostics
+ .filter(({ severity }) => severity === "error")
+ .map(({ path, message }) => `JSON-LD ${path}: ${message}`)
+ );
+ }
+ }
+ matches.push({
+ propId: prop.id,
+ instanceId: prop.instanceId,
+ name: prop.name,
+ before: prop.value,
+ after,
+ });
+ }
+ const result = {
+ changedCount: matches.length,
+ matchingPropCount,
+ truncated: matchingPropCount > matches.length,
+ matches,
+ };
+ if (matches.length === 0) {
+ return createRuntimeMutation({
+ payload: [],
+ result,
+ invalidatesNamespaces: [],
+ });
+ }
+ return createRuntimeMutation({
+ payload: [
+ {
+ namespace: "props",
+ patches: matches.map(({ propId, after }) => ({
+ op: "replace" as const,
+ path: [propId, "value"],
+ value: after,
+ })),
+ },
+ ],
+ result,
+ invalidatesNamespaces: ["props"],
+ });
+};
+
export const bindProps = (
state: Pick<BuilderState, "instances" | "props">,
input: z.infer<typeof propBindingsInput>,
diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.ts
index f62ec63d3f..595f490bef 100644
--- a/packages/project-build/src/runtime/registry.test.ts
+++ b/packages/project-build/src/runtime/registry.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from "vitest";
import {
getInputJsonSchemaMetadata,
toInputJsonSchemaObject,
+ type Assets,
type InputJsonSchema,
} from "@webstudio-is/sdk";
import { runtimeOperationContracts } from "../contracts/builder-runtime";
@@ -25,13 +26,14 @@ import {
updateTextInstance,
} from "./instances";
import { listDataVariables, listResources } from "./data";
+import { listFonts } from "./fonts";
import { bindProps, deleteProps, updateProps } from "./props";
-import type { BuilderRuntimeContext } from "./context";
import type { BuilderState } from "../state/builder-state";
-
-const context: BuilderRuntimeContext = {
- createId: () => "id",
-};
+import {
+ context,
+ expectRuntimeValidationError,
+ state,
+} from "./runtime.test-fixtures";
const hasDirectInputProperty = (
schema: InputJsonSchema | undefined,
@@ -58,240 +60,6 @@ const hasDirectInputProperty = (
);
};
-const state = {
- pages: {
- homePageId: "home",
- rootFolderId: "root",
- redirects: [{ old: "/old", new: "/new", status: "301" }],
- pages: new Map([
- [
- "home",
- {
- id: "home",
- name: "Home",
- title: "Home",
- path: "",
- rootInstanceId: "body",
- meta: {},
- },
- ],
- [
- "post",
- {
- id: "post",
- name: "Post",
- title: "Post",
- path: "/post",
- rootInstanceId: "post-body",
- meta: {
- description: "Post description",
- excludePageFromSearch: "true",
- },
- },
- ],
- ]),
- folders: new Map([
- [
- "root",
- {
- id: "root",
- name: "Root",
- slug: "",
- children: ["home", "blog"],
- },
- ],
- [
- "blog",
- {
- id: "blog",
- name: "Blog",
- slug: "blog",
- children: ["post"],
- },
- ],
- ]),
- },
- instances: new Map([
- [
- "body",
- {
- type: "instance",
- id: "body",
- component: "Body",
- tag: "body",
- children: [{ type: "id", value: "heading" }],
- },
- ],
- [
- "heading",
- {
- type: "instance",
- id: "heading",
- component: "Text",
- tag: "h1",
- label: "Hero",
- children: [{ type: "text", value: "Hello" }],
- },
- ],
- ]),
- props: new Map([
- [
- "prop",
- {
- id: "prop",
- instanceId: "heading",
- name: "title",
- type: "string",
- value: "Heading",
- },
- ],
- [
- "labelProp",
- {
- id: "labelProp",
- instanceId: "heading",
- name: "aria-label",
- type: "string",
- value: "Heading label",
- },
- ],
- [
- "resourceProp",
- {
- id: "resourceProp",
- instanceId: "heading",
- name: "src",
- type: "resource",
- value: "resource",
- },
- ],
- ]),
- styleSources: new Map([
- ["local", { type: "local", id: "local" }],
- ["token", { type: "token", id: "token", name: "Brand" }],
- ]),
- styleSourceSelections: new Map([
- ["heading", { instanceId: "heading", values: ["token", "local"] }],
- ]),
- styles: new Map([
- [
- "local:base::color",
- {
- styleSourceId: "local",
- breakpointId: "base",
- state: undefined,
- property: "color",
- value: { type: "unparsed", value: "var(--brand-color)" },
- },
- ],
- [
- "local:base::--brand-color",
- {
- styleSourceId: "local",
- breakpointId: "base",
- state: undefined,
- property: "--brand-color",
- value: { type: "keyword", value: "red" },
- },
- ],
- [
- "token:base::color",
- {
- styleSourceId: "token",
- breakpointId: "base",
- state: undefined,
- property: "color",
- value: { type: "keyword", value: "blue" },
- },
- ],
- ]),
- dataSources: new Map([
- [
- "variable",
- {
- id: "variable",
- type: "variable",
- name: "Title",
- scopeInstanceId: "heading",
- value: { type: "string", value: "Hello" },
- },
- ],
- [
- "resourceDataSource",
- {
- id: "resourceDataSource",
- type: "resource",
- name: "Posts",
- scopeInstanceId: "heading",
- resourceId: "resource",
- },
- ],
- ]),
- resources: new Map([
- [
- "resource",
- {
- id: "resource",
- name: "Posts",
- method: "get",
- url: `"/posts"`,
- headers: [],
- searchParams: [],
- },
- ],
- ]),
- assets: new Map([
- [
- "asset",
- {
- id: "asset",
- projectId: "project",
- name: "asset.png",
- type: "image",
- size: 1,
- format: "png",
- createdAt: "2026-01-01T00:00:00.000Z",
- description: null,
- meta: { width: 100, height: 100 },
- },
- ],
- [
- "next",
- {
- id: "next",
- projectId: "project",
- name: "next.png",
- type: "image",
- size: 1,
- format: "png",
- createdAt: "2026-01-01T00:00:00.000Z",
- filename: "Hero",
- description: null,
- meta: { width: 100, height: 100 },
- },
- ],
- ]),
- breakpoints: new Map([
- ["base", { id: "base", label: "Base" }],
- ["desktop", { id: "desktop", label: "Desktop", minWidth: 1024 }],
- ]),
-} satisfies BuilderState;
-
-const expectRuntimeValidationError = (operationId: string, input: unknown) => {
- try {
- executeBuilderRuntimeOperation({
- id: operationId,
- state,
- input,
- context,
- });
- } catch (error) {
- expect(error).toMatchObject({ name: "ZodError" });
- return;
- }
- throw new Error(`Expected ${operationId} to reject invalid input`);
-};
-
const mutationOperationIds = runtimeOperationContracts
.filter((contract) => contract.kind === "mutation")
.map((contract) => contract.id);
@@ -306,6 +74,7 @@ test("keeps generated runtime contracts in sync with the registry", () => {
permit,
kind,
inputJsonSchema,
+ outputJsonSchema,
readNamespaces,
writeNamespaces,
invalidatesNamespaces,
@@ -319,6 +88,9 @@ test("keeps generated runtime contracts in sync with the registry", () => {
permit,
kind,
inputSchema: inputJsonSchema,
+ ...(outputJsonSchema === undefined
+ ? {}
+ : { outputSchema: outputJsonSchema }),
readNamespaces,
writeNamespaces,
invalidatesNamespaces,
@@ -330,6 +102,133 @@ test("keeps generated runtime contracts in sync with the registry", () => {
);
});
+test("tracks public runtime operations without output schemas", () => {
+ expect(
+ builderRuntimeOperations
+ .filter(
+ (operation) =>
+ operation.command !== undefined &&
+ operation.outputSchema === undefined
+ )
+ .map((operation) => operation.id)
+ ).toMatchInlineSnapshot(`
+ [
+ "pages.list",
+ "pages.get",
+ "pages.getByPath",
+ "pages.create",
+ "pages.update",
+ "pages.updateSettings",
+ "pages.updateMarketplace",
+ "pages.savePathInHistory",
+ "pages.setHome",
+ "projectSettings.get",
+ "projectSettings.update",
+ "projectSettings.getMarketplaceProduct",
+ "projectSettings.updateMarketplaceProduct",
+ "redirects.list",
+ "redirects.create",
+ "redirects.update",
+ "redirects.delete",
+ "redirects.setAll",
+ "breakpoints.list",
+ "breakpoints.create",
+ "breakpoints.update",
+ "breakpoints.delete",
+ "pages.delete",
+ "pages.duplicate",
+ "pages.copy",
+ "pageTemplates.list",
+ "pageTemplates.create",
+ "pageTemplates.update",
+ "pageTemplates.delete",
+ "pageTemplates.duplicate",
+ "pageTemplates.reorder",
+ "pageTemplates.createPage",
+ "folders.list",
+ "folders.create",
+ "folders.update",
+ "folders.delete",
+ "folders.duplicate",
+ "pageTransfer.insert",
+ "pageTree.move",
+ "pageTree.reparentOrphans",
+ "instances.list",
+ "instances.inspect",
+ "project.search",
+ "instances.insertComponent",
+ "instances.insertFragment",
+ "instances.move",
+ "instances.reparent",
+ "instances.fillGrid",
+ "instances.wrap",
+ "instances.convert",
+ "instances.unwrap",
+ "instances.clone",
+ "instances.duplicateAfterItself",
+ "instances.delete",
+ "instances.deleteBySelector",
+ "instances.updateProps",
+ "instances.replacePropText",
+ "instances.deleteProps",
+ "instances.bindProps",
+ "instances.listTexts",
+ "instances.updateText",
+ "instances.replaceText",
+ "instances.setTextContent",
+ "instances.updateTextTree",
+ "instances.setTag",
+ "instances.setLabel",
+ "styles.getDeclarations",
+ "styles.updateDeclarations",
+ "styles.deleteDeclarations",
+ "styles.updateSelectedDeclarations",
+ "styles.deleteSelectedDeclarations",
+ "styles.replaceValues",
+ "designTokens.list",
+ "designTokens.create",
+ "designTokens.createAttached",
+ "designTokens.updateStyles",
+ "designTokens.deleteStyles",
+ "designTokens.attach",
+ "designTokens.detach",
+ "designTokens.extract",
+ "styleSources.rename",
+ "styleSources.delete",
+ "styleSources.setLock",
+ "styleSources.reorder",
+ "styleSources.clearStyles",
+ "styleSources.duplicate",
+ "styleSources.convertLocalToToken",
+ "cssVariables.list",
+ "cssVariables.define",
+ "cssVariables.delete",
+ "cssVariables.rewriteRefs",
+ "cssVariables.rename",
+ "variables.list",
+ "variables.create",
+ "variables.update",
+ "variables.delete",
+ "variables.deleteUnused",
+ "resources.list",
+ "resources.create",
+ "resources.update",
+ "resources.replaceText",
+ "resources.upsert",
+ "resources.upsertProp",
+ "resources.delete",
+ "assets.list",
+ "fonts.list",
+ "assets.findUsage",
+ "assets.update",
+ "assets.setImageDescriptions",
+ "assets.add",
+ "assets.replace",
+ "assets.delete",
+ ]
+ `);
+});
+
describe("builder runtime pages", () => {
test("lists pages and folders from shared state", () => {
expect(listPages(state, { includeFolders: true })).toMatchObject({
@@ -436,16 +335,25 @@ describe("builder runtime read families", () => {
).toMatchObject({
instances: [
{ id: "body", depth: 0 },
- { id: "heading", depth: 1, label: "Hero" },
+ {
+ id: "heading",
+ depth: 1,
+ label: "Hero",
+ parentId: "body",
+ indexWithinParent: 0,
+ },
],
});
const inspectedInstance = inspectInstance(state, {
instanceId: "heading",
- include: ["props", "styles", "sources"],
+ include: ["props", "styles", "sources", "ancestors"],
});
expect(inspectedInstance).toMatchObject({
id: "heading",
+ parentId: "body",
+ indexWithinParent: 0,
+ ancestors: [{ id: "body", childIndex: 0 }],
sources: ["token", "local"],
});
expect(inspectedInstance.styles).toEqual(
@@ -500,6 +408,74 @@ describe("builder runtime read families", () => {
});
});
+ test("replaces bounded literal text through the public runtime operation", () => {
+ const replaceState = {
+ ...state,
+ instances: new Map<
+ string,
+ NonNullable<BuilderState["instances"]> extends Map<
+ string,
+ infer Instance
+ >
+ ? Instance
+ : never
+ >([
+ ...state.instances,
+ [
+ "subtitle",
+ {
+ type: "instance" as const,
+ id: "subtitle",
+ component: "Text",
+ tag: "p",
+ children: [{ type: "text" as const, value: "Hello from Acme" }],
+ },
+ ],
+ ]),
+ } satisfies BuilderState;
+
+ expect(
+ executeBuilderRuntimeOperation({
+ id: "instances.replaceText",
+ state: replaceState,
+ input: {
+ find: "Hello",
+ replace: "Welcome",
+ match: "substring",
+ limit: 1,
+ },
+ context,
+ })
+ ).toMatchObject({
+ kind: "mutation",
+ result: {
+ changedCount: 1,
+ matchingChildCount: 2,
+ truncated: true,
+ matches: [
+ {
+ instanceId: "heading",
+ childIndex: 0,
+ before: "Hello",
+ after: "Welcome",
+ },
+ ],
+ },
+ payload: [
+ {
+ namespace: "instances",
+ patches: [
+ {
+ op: "replace",
+ path: ["heading", "children", 0],
+ value: { type: "text", value: "Welcome" },
+ },
+ ],
+ },
+ ],
+ });
+ });
+
test("builds prop mutations", () => {
expect(
updateProps(
@@ -552,6 +528,73 @@ describe("builder runtime read families", () => {
});
});
+ test("replaces bounded static prop text without changing dynamic bindings", () => {
+ const replaceState = {
+ ...state,
+ props: new Map<
+ string,
+ NonNullable<BuilderState["props"]> extends Map<string, infer Prop>
+ ? Prop
+ : never
+ >([
+ ...state.props,
+ [
+ "expression-prop",
+ {
+ id: "expression-prop",
+ instanceId: "heading",
+ name: "title",
+ type: "expression" as const,
+ value: "Heading",
+ },
+ ],
+ ]),
+ } satisfies BuilderState;
+
+ expect(
+ executeBuilderRuntimeOperation({
+ id: "instances.replacePropText",
+ state: replaceState,
+ input: {
+ find: "Heading",
+ replace: "Welcome",
+ match: "exact",
+ names: ["title"],
+ limit: 1,
+ },
+ context,
+ })
+ ).toMatchObject({
+ kind: "mutation",
+ result: {
+ changedCount: 1,
+ matchingPropCount: 1,
+ truncated: false,
+ matches: [
+ {
+ propId: "prop",
+ instanceId: "heading",
+ name: "title",
+ before: "Heading",
+ after: "Welcome",
+ },
+ ],
+ },
+ payload: [
+ {
+ namespace: "props",
+ patches: [
+ {
+ op: "replace",
+ path: ["prop", "value"],
+ value: "Welcome",
+ },
+ ],
+ },
+ ],
+ });
+ });
+
test("deletes multiple props through the public runtime operation", () => {
expect(
executeBuilderRuntimeOperation({
@@ -589,7 +632,12 @@ describe("builder runtime read families", () => {
])
);
expect(listDesignTokens(state, { withUsage: true })).toMatchObject({
- tokens: [{ id: "token", usageCount: 1 }],
+ tokens: [{ id: "token", declarationCount: 1, usageCount: 1 }],
+ });
+ expect(
+ listDesignTokens(state, { withUsage: true, includeStyles: true })
+ ).toMatchObject({
+ tokens: [{ id: "token", styles: { color: expect.any(Object) } }],
});
expect(listCssVariables(state, { withUsage: true })).toMatchObject({
vars: [{ name: "--brand-color", scope: "heading", usageCount: 1 }],
@@ -602,6 +650,58 @@ describe("builder runtime read families", () => {
});
});
+ test("lists uploaded font families separately from system font stacks", () => {
+ const assets: Assets = new Map(state.assets);
+ assets.set("font", {
+ id: "font",
+ projectId: "project",
+ name: "acme-sans.woff2",
+ type: "font",
+ size: 1,
+ format: "woff2",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ description: null,
+ meta: { family: "Acme Sans", style: "normal", weight: 400 },
+ });
+ const fontState = {
+ ...state,
+ assets,
+ } satisfies BuilderState;
+
+ expect(listFonts(fontState, { includeSystem: false })).toEqual({
+ uploaded: [
+ {
+ family: "Acme Sans",
+ source: "uploaded",
+ assets: [
+ {
+ assetId: "font",
+ format: "woff2",
+ style: "normal",
+ weight: 400,
+ variable: false,
+ },
+ ],
+ },
+ ],
+ system: [],
+ });
+
+ expect(
+ executeBuilderRuntimeOperation({
+ id: "fonts.list",
+ state: fontState,
+ input: {},
+ context,
+ })
+ ).toMatchObject({
+ uploaded: [{ family: "Acme Sans" }],
+ system: expect.arrayContaining([
+ expect.objectContaining({ family: "System UI", source: "system" }),
+ ]),
+ });
+ });
+
test("validates data variable mutations through public operations", () => {
expect(
executeBuilderRuntimeOperation({
@@ -821,6 +921,95 @@ describe("builder runtime read families", () => {
})
).toThrow("url: URL is required");
+ const fixedUrlResult = executeBuilderRuntimeOperation({
+ id: "resources.create",
+ state,
+ input: {
+ scopeInstanceId: "heading",
+ resource: {
+ name: "Users",
+ method: "get",
+ url: "https://api.example.com/users",
+ headers: [],
+ },
+ },
+ context: {
+ ...context,
+ createId: (() => {
+ const ids = ["fixed-resource-id", "fixed-data-source-id"];
+ return () => ids.shift() ?? "id";
+ })(),
+ },
+ });
+
+ expect(fixedUrlResult).toMatchObject({
+ payload: expect.arrayContaining([
+ {
+ namespace: "resources",
+ patches: expect.arrayContaining([
+ expect.objectContaining({
+ value: expect.objectContaining({
+ url: `"https://api.example.com/users"`,
+ }),
+ }),
+ ]),
+ },
+ ]),
+ });
+
+ const literalRequestValuesResult = executeBuilderRuntimeOperation({
+ id: "resources.create",
+ state,
+ input: {
+ scopeInstanceId: "heading",
+ resource: {
+ name: "Literal request values",
+ method: "post",
+ url: "https://api.example.com/users",
+ searchParams: [
+ {
+ name: "source",
+ value: { type: "literal", value: "website" },
+ },
+ ],
+ headers: [
+ {
+ name: "Content-Type",
+ value: { type: "literal", value: "application/json" },
+ },
+ ],
+ body: { type: "literal", value: "Plain text body" },
+ },
+ },
+ context: {
+ ...context,
+ createId: (() => {
+ const ids = ["literal-resource-id", "literal-data-source-id"];
+ return () => ids.shift() ?? "id";
+ })(),
+ },
+ });
+
+ expect(literalRequestValuesResult).toMatchObject({
+ payload: expect.arrayContaining([
+ {
+ namespace: "resources",
+ patches: expect.arrayContaining([
+ expect.objectContaining({
+ value: expect.objectContaining({
+ url: '"https://api.example.com/users"',
+ searchParams: [{ name: "source", value: '"website"' }],
+ headers: [
+ { name: "Content-Type", value: '"application/json"' },
+ ],
+ body: '"Plain text body"',
+ }),
+ }),
+ ]),
+ },
+ ]),
+ });
+
const dynamicUrlResult = executeBuilderRuntimeOperation({
id: "resources.upsert",
state,
@@ -848,6 +1037,76 @@ describe("builder runtime read families", () => {
});
});
+ test("replaces bounded fixed resource URLs without changing expressions", () => {
+ const resource = state.resources.get("resource");
+ if (resource === undefined) {
+ throw new Error("Expected test resource");
+ }
+ const replaceState = {
+ ...state,
+ resources: new Map([
+ [
+ "resource",
+ {
+ ...resource,
+ url: '"https://api.old.example.com/posts"',
+ },
+ ],
+ [
+ "dynamic-resource",
+ {
+ ...resource,
+ id: "dynamic-resource",
+ name: "Dynamic posts",
+ url: "apiBase + '/posts'",
+ },
+ ],
+ ]),
+ } satisfies BuilderState;
+
+ expect(
+ executeBuilderRuntimeOperation({
+ id: "resources.replaceText",
+ state: replaceState,
+ input: {
+ find: "/posts",
+ replace: "/articles",
+ match: "substring",
+ fields: ["url"],
+ limit: 1,
+ },
+ context,
+ })
+ ).toMatchObject({
+ kind: "mutation",
+ result: {
+ changedCount: 1,
+ matchingFieldCount: 1,
+ truncated: false,
+ matches: [
+ {
+ resourceId: "resource",
+ field: "url",
+ before: "https://api.old.example.com/posts",
+ after: "https://api.old.example.com/articles",
+ },
+ ],
+ },
+ payload: [
+ {
+ namespace: "resources",
+ patches: [
+ {
+ op: "replace",
+ path: ["resource", "url"],
+ value: '"https://api.old.example.com/articles"',
+ },
+ ],
+ },
+ ],
+ });
+ });
+
test("validates project settings and redirects through public operations", () => {
expect(() =>
executeBuilderRuntimeOperation({
@@ -1141,9 +1400,11 @@ describe("builder runtime registry", () => {
["instances.delete", { instanceIds: "heading" }],
["instances.deleteBySelector", {}],
["instances.updateProps", { updates: {} }],
+ ["instances.replacePropText", {}],
["instances.deleteProps", { deletions: {} }],
["instances.bindProps", { bindings: {} }],
["instances.updateText", {}],
+ ["instances.replaceText", {}],
["instances.setTextContent", { operation: "unknown" }],
["instances.updateTextTree", {}],
["instances.setTag", {}],
@@ -1177,10 +1438,12 @@ describe("builder runtime registry", () => {
["variables.deleteUnused", []],
["resources.create", {}],
["resources.update", {}],
+ ["resources.replaceText", {}],
["resources.upsert", {}],
["resources.upsertProp", {}],
["resources.delete", {}],
["assets.update", {}],
+ ["assets.setImageDescriptions", {}],
["assets.add", {}],
["assets.replace", {}],
["assets.delete", { assetIdsOrPrefixes: "asset" }],
@@ -1208,4 +1471,179 @@ describe("builder runtime registry", () => {
})
).toThrow(/unexpected/);
});
+
+ test("does not mutate caller state across representative public mutation surfaces", () => {
+ const inputs = new Map<string, unknown>([
+ ["pages.create", { projectId: "project-1", name: "Docs", path: "/docs" }],
+ [
+ "pages.duplicate",
+ { projectId: "project-1", pageId: "home", parentFolderId: "root" },
+ ],
+ ["pages.update", { pageId: "home", values: { name: "Renamed Home" } }],
+ ["pages.delete", { pageId: "post" }],
+ [
+ "folders.create",
+ { name: "Docs", slug: "docs", parentFolderId: "root" },
+ ],
+ [
+ "pageTemplates.create",
+ {
+ name: "Article Template",
+ title: '"Article Template"',
+ meta: { description: '"Reusable article"' },
+ },
+ ],
+ ["redirects.create", { old: "/legacy", new: "/new" }],
+ ["breakpoints.create", { label: "Tablet", maxWidth: 768 }],
+ [
+ "instances.updateText",
+ { instanceId: "heading", childIndex: 0, text: "Updated" },
+ ],
+ ["instances.delete", { instanceIds: ["heading"] }],
+ [
+ "instances.move",
+ {
+ moves: [
+ { instanceId: "heading", parentInstanceId: "body", insertIndex: 0 },
+ ],
+ },
+ ],
+ [
+ "instances.clone",
+ { sourceInstanceId: "heading", targetParentInstanceId: "body" },
+ ],
+ [
+ "instances.duplicateAfterItself",
+ { sourceInstanceId: "heading", parentInstanceId: "body" },
+ ],
+ ["instances.setLabel", { instanceId: "heading", label: "Updated hero" }],
+ ["instances.setTag", { instanceId: "heading", tag: "h2" }],
+ [
+ "instances.updateProps",
+ {
+ updates: [
+ {
+ instanceId: "heading",
+ name: "title",
+ type: "string",
+ value: "Updated title",
+ },
+ ],
+ },
+ ],
+ [
+ "instances.deleteProps",
+ { deletions: [{ instanceId: "heading", name: "title" }] },
+ ],
+ [
+ "styles.updateDeclarations",
+ {
+ updates: [
+ {
+ instanceId: "heading",
+ property: "color",
+ value: { type: "keyword", value: "green" },
+ },
+ ],
+ },
+ ],
+ [
+ "styles.deleteDeclarations",
+ { deletions: [{ instanceId: "heading", property: "color" }] },
+ ],
+ [
+ "designTokens.create",
+ {
+ tokens: [
+ {
+ name: "Accent",
+ styles: { color: { type: "keyword", value: "green" } },
+ },
+ ],
+ },
+ ],
+ [
+ "variables.create",
+ {
+ scopeInstanceId: "heading",
+ name: "Subtitle",
+ value: { type: "string", value: "Hello" },
+ },
+ ],
+ [
+ "styleSources.rename",
+ { styleSourceId: "token", name: "Updated Brand" },
+ ],
+ ["styleSources.setLock", { styleSourceId: "token", locked: true }],
+ ["styleSources.clearStyles", { styleSourceId: "local" }],
+ [
+ "styleSources.duplicate",
+ { instanceId: "heading", styleSourceId: "token" },
+ ],
+ [
+ "designTokens.attach",
+ { designTokenId: "token", instanceIds: ["heading"] },
+ ],
+ [
+ "designTokens.detach",
+ { designTokenId: "token", instanceIds: ["heading"] },
+ ],
+ [
+ "cssVariables.define",
+ { vars: { "--accent-color": { type: "keyword", value: "green" } } },
+ ],
+ [
+ "cssVariables.rename",
+ { oldName: "--brand-color", newName: "--main-color" },
+ ],
+ ["cssVariables.delete", { names: ["--brand-color"], force: true }],
+ [
+ "variables.update",
+ {
+ dataSourceId: "variable",
+ values: { value: { type: "string", value: "Updated" } },
+ },
+ ],
+ ["variables.delete", { dataSourceId: "variable" }],
+ [
+ "resources.update",
+ { resourceId: "resource", values: { name: "Updated Posts" } },
+ ],
+ [
+ "resources.create",
+ {
+ scopeInstanceId: "heading",
+ resource: {
+ name: "Users",
+ method: "get",
+ url: "https://api.example.com/users",
+ headers: [],
+ searchParams: [],
+ },
+ },
+ ],
+ ["resources.delete", { resourceId: "resource", force: true }],
+ [
+ "assets.update",
+ {
+ assetId: "asset",
+ values: { filename: "Updated", description: "Updated description" },
+ },
+ ],
+ [
+ "assets.setImageDescriptions",
+ {
+ updates: [{ assetId: "asset", description: "Updated description" }],
+ },
+ ],
+ ["assets.delete", { assetIdsOrPrefixes: ["asset"] }],
+ ["assets.replace", { fromAssetId: "asset", toAssetId: "next" }],
+ ]);
+
+ for (const [id, input] of inputs) {
+ const before = structuredClone(state);
+ executeBuilderRuntimeOperation({ id, state, input, context });
+ expect(state).toEqual(before);
+ }
+ });
});
diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.ts
index c0abe958dc..6407729425 100644
--- a/packages/project-build/src/runtime/registry.ts
+++ b/packages/project-build/src/runtime/registry.ts
@@ -14,6 +14,7 @@ import { z } from "zod";
import * as assets from "./assets";
import * as components from "./components";
import * as data from "./data";
+import * as fonts from "./fonts";
import * as instanceDuplicate from "./instance-duplicate";
import * as instances from "./instances";
import * as migrations from "./migrations";
@@ -21,6 +22,8 @@ import * as pageCopy from "./page-copy";
import * as pages from "./pages";
import * as projectSettings from "./project-settings";
import * as props from "./props";
+import * as search from "./search";
+import * as audit from "./audit";
import * as styles from "./styles";
export type BuilderRuntimeOperation<
@@ -35,6 +38,8 @@ export type BuilderRuntimeOperation<
kind: "read" | "mutation";
inputSchema: z.ZodTypeAny;
inputJsonSchema: InputJsonSchema;
+ outputSchema?: z.ZodTypeAny;
+ outputJsonSchema?: InputJsonSchema;
readNamespaces: readonly BuilderNamespace[];
writeNamespaces: readonly BuilderNamespace[];
invalidatesNamespaces: readonly BuilderNamespace[];
@@ -85,7 +90,8 @@ const runtimeOperation = <
state: BuilderState;
input: z.output<Schema>;
context: BuilderRuntimeContext;
- }) => Result | Promise<Result>
+ }) => Result | Promise<Result>,
+ outputSchema?: z.ZodTypeAny
): BuilderRuntimeOperation<Id, z.input<Schema>, Result> => {
const writeNamespaces =
contract.kind === "mutation" ? contract.writeNamespaces : [];
@@ -97,6 +103,11 @@ const runtimeOperation = <
inputJsonSchema: getInputSchemaMetadata(inputSchema, {
isHiddenField: isHiddenPublicApiInputField,
}).inputJsonSchema,
+ outputSchema,
+ outputJsonSchema:
+ outputSchema === undefined
+ ? undefined
+ : getInputSchemaMetadata(outputSchema).inputJsonSchema,
readNamespaces: contract.readNamespaces,
writeNamespaces,
invalidatesNamespaces:
@@ -115,8 +126,20 @@ const runtimeOperation = <
contract.kind === "mutation"
? (contract.requiresConfirm ?? false)
: false,
- execute: ({ state, input, context }) =>
- execute({ state, input: inputSchema.parse(input ?? {}), context }),
+ execute: ({ state, input, context }) => {
+ const result = execute({
+ state,
+ input: inputSchema.parse(input ?? {}),
+ context,
+ });
+ if (outputSchema === undefined) {
+ return result;
+ }
+ if (result instanceof Promise) {
+ return result.then((value) => outputSchema.parse(value) as Result);
+ }
+ return outputSchema.parse(result) as Result;
+ },
};
};
@@ -162,6 +185,7 @@ const treeMutationNamespaces = [
const assetUsageNamespaces = [
"assets",
"pages",
+ "projectSettings",
"props",
"styles",
"resources",
@@ -196,7 +220,16 @@ const instanceListInput = instanceFilterInput.extend({
const instanceInspectInput = z.object({
instanceId: z.string(),
include: z
- .array(z.enum(["props", "styles", "bindings", "children", "sources"]))
+ .array(
+ z.enum([
+ "props",
+ "styles",
+ "bindings",
+ "children",
+ "sources",
+ "ancestors",
+ ])
+ )
.optional(),
childDepth: z.number().int().optional(),
});
@@ -220,7 +253,14 @@ const styleDeclarationsListInput = z.object({
});
const designTokenListInput = z.object({
filter: z.string().optional(),
- withUsage: z.boolean().optional(),
+ withUsage: z
+ .boolean()
+ .optional()
+ .describe("Include usage counts. Defaults to true."),
+ includeStyles: z
+ .boolean()
+ .optional()
+ .describe("Include full inline style declarations for each token."),
sort: z.enum(["name", "usage"]).optional(),
});
const cssVariableListInput = z.object({
@@ -243,7 +283,7 @@ export const builderRuntimeOperations = [
runtimeOperation(
"pages.list",
api("list-pages", "listPages"),
- readContract(["pages"]),
+ readContract(["pages", "projectSettings"]),
pageListInput,
({ state, input }) => pages.listPages(state, input)
),
@@ -658,6 +698,45 @@ export const builderRuntimeOperations = [
instanceInspectInput,
({ state, input }) => instances.inspectInstance(state, input)
),
+ runtimeOperation(
+ "project.search",
+ api("search-project", "searchProject"),
+ readContract([
+ "pages",
+ "projectSettings",
+ "instances",
+ "props",
+ "styles",
+ "styleSources",
+ "styleSourceSelections",
+ "resources",
+ "dataSources",
+ "assets",
+ "breakpoints",
+ ]),
+ search.projectSearchInput,
+ ({ state, input }) => search.searchProject(state, input)
+ ),
+ runtimeOperation(
+ "project.audit",
+ api("audit", "audit"),
+ readContract([
+ "pages",
+ "projectSettings",
+ "instances",
+ "props",
+ "styles",
+ "styleSources",
+ "styleSourceSelections",
+ "resources",
+ "dataSources",
+ "assets",
+ "breakpoints",
+ ]),
+ audit.auditInput,
+ ({ state, input, context }) => audit.audit(state, input, context),
+ audit.auditResult
+ ),
runtimeOperation(
"instances.insertComponent",
api("insert-component", "insertComponent"),
@@ -854,6 +933,17 @@ export const builderRuntimeOperations = [
props.propUpdatesInput,
({ state, input, context }) => props.updateProps(state, input, context)
),
+ runtimeOperation(
+ "instances.replacePropText",
+ api("replace-prop-text", "replacePropText", "edit"),
+ mutationContract({
+ readNamespaces: ["instances", "props"],
+ writeNamespaces: ["props"],
+ retryOnConflict: true,
+ }),
+ props.replacePropTextInput,
+ ({ state, input }) => props.replacePropText(state, input)
+ ),
runtimeOperation(
"instances.deleteProps",
api("delete-props", "deleteProps", "edit"),
@@ -892,6 +982,17 @@ export const builderRuntimeOperations = [
instances.updateTextInstanceInput,
({ state, input }) => instances.updateTextInstance(state, input)
),
+ runtimeOperation(
+ "instances.replaceText",
+ api("replace-text", "replaceText", "edit"),
+ mutationContract({
+ readNamespaces: ["pages", "instances"],
+ writeNamespaces: ["instances"],
+ retryOnConflict: true,
+ }),
+ instances.replaceTextInput,
+ ({ state, input }) => instances.replaceText(state, input)
+ ),
runtimeOperation(
"instances.setTextContent",
api("set-text-content", "setTextContent", "edit"),
@@ -907,8 +1008,23 @@ export const builderRuntimeOperations = [
"instances.updateTextTree",
api("update-text-tree", "updateTextTree", "edit"),
mutationContract({
- readNamespaces: ["instances"],
- writeNamespaces: ["instances"],
+ readNamespaces: [
+ "instances",
+ "props",
+ "dataSources",
+ "styleSources",
+ "styleSourceSelections",
+ "styles",
+ ],
+ writeNamespaces: [
+ "instances",
+ "props",
+ "dataSources",
+ "resources",
+ "styleSourceSelections",
+ "styleSources",
+ "styles",
+ ],
retryOnConflict: true,
}),
instances.updateTextTreeInput,
@@ -1303,6 +1419,17 @@ export const builderRuntimeOperations = [
data.resourceUpdateInput,
({ state, input }) => data.updateResource(state, input)
),
+ runtimeOperation(
+ "resources.replaceText",
+ api("replace-resource-text", "replaceResourceText"),
+ mutationContract({
+ readNamespaces: ["resources"],
+ writeNamespaces: ["resources"],
+ retryOnConflict: true,
+ }),
+ data.replaceResourceTextInput,
+ ({ state, input }) => data.replaceResourceText(state, input)
+ ),
runtimeOperation(
"resources.upsert",
api("upsert-resource", "upsertResource"),
@@ -1369,6 +1496,13 @@ export const builderRuntimeOperations = [
assetListInput,
({ state, input }) => assets.listAssets(state, input)
),
+ runtimeOperation(
+ "fonts.list",
+ api("list-fonts", "listFonts"),
+ readContract(["assets"]),
+ fonts.fontListInput,
+ ({ state, input }) => fonts.listFonts(state, input)
+ ),
runtimeOperation(
"assets.findUsage",
api("find-asset-usage", "findAssetUsage"),
@@ -1387,6 +1521,17 @@ export const builderRuntimeOperations = [
assets.assetUpdateInput,
({ state, input }) => assets.updateAsset(state, input)
),
+ runtimeOperation(
+ "assets.setImageDescriptions",
+ api("set-image-descriptions", "setImageDescriptions"),
+ mutationContract({
+ readNamespaces: ["assets"],
+ writeNamespaces: ["assets"],
+ requiresAssets: true,
+ }),
+ assets.imageDescriptionsSetInput,
+ ({ state, input }) => assets.setImageDescriptions(state, input)
+ ),
runtimeOperation(
"assets.add",
api("add-asset", "addAsset"),
@@ -1403,7 +1548,13 @@ export const builderRuntimeOperations = [
api("replace-asset", "replaceAsset"),
mutationContract({
readNamespaces: assetUsageNamespaces,
- writeNamespaces: ["pages", "props", "styles", "assets"],
+ writeNamespaces: [
+ "pages",
+ "projectSettings",
+ "props",
+ "styles",
+ "assets",
+ ],
requiresAssets: true,
}),
assets.assetReplaceInput,
diff --git a/packages/project-build/src/runtime/runtime.test-fixtures.ts b/packages/project-build/src/runtime/runtime.test-fixtures.ts
new file mode 100644
index 0000000000..3f1b2566ba
--- /dev/null
+++ b/packages/project-build/src/runtime/runtime.test-fixtures.ts
@@ -0,0 +1,246 @@
+import { expect } from "vitest";
+import type { BuilderRuntimeContext } from "./context";
+import type { BuilderState } from "../state/builder-state";
+import { executeBuilderRuntimeOperation } from "./registry";
+
+export const context: BuilderRuntimeContext = {
+ createId: () => "id",
+};
+
+export const expectRuntimeValidationError = (
+ operationId: string,
+ input: unknown
+) => {
+ try {
+ executeBuilderRuntimeOperation({
+ id: operationId,
+ state,
+ input,
+ context,
+ });
+ } catch (error) {
+ expect(error).toMatchObject({ name: "ZodError" });
+ return;
+ }
+ throw new Error(`Expected ${operationId} to reject invalid input`);
+};
+
+export const state = {
+ pages: {
+ homePageId: "home",
+ rootFolderId: "root",
+ redirects: [{ old: "/old", new: "/new", status: "301" }],
+ pages: new Map([
+ [
+ "home",
+ {
+ id: "home",
+ name: "Home",
+ title: "Home",
+ path: "",
+ rootInstanceId: "body",
+ meta: {},
+ },
+ ],
+ [
+ "post",
+ {
+ id: "post",
+ name: "Post",
+ title: "Post",
+ path: "/post",
+ rootInstanceId: "post-body",
+ meta: {
+ description: "Post description",
+ excludePageFromSearch: "true",
+ },
+ },
+ ],
+ ]),
+ folders: new Map([
+ [
+ "root",
+ {
+ id: "root",
+ name: "Root",
+ slug: "",
+ children: ["home", "blog"],
+ },
+ ],
+ [
+ "blog",
+ {
+ id: "blog",
+ name: "Blog",
+ slug: "blog",
+ children: ["post"],
+ },
+ ],
+ ]),
+ },
+ projectSettings: { meta: {}, compiler: {} },
+ instances: new Map([
+ [
+ "body",
+ {
+ type: "instance",
+ id: "body",
+ component: "Body",
+ tag: "body",
+ children: [{ type: "id", value: "heading" }],
+ },
+ ],
+ [
+ "heading",
+ {
+ type: "instance",
+ id: "heading",
+ component: "Text",
+ tag: "h1",
+ label: "Hero",
+ children: [{ type: "text", value: "Hello" }],
+ },
+ ],
+ ]),
+ props: new Map([
+ [
+ "prop",
+ {
+ id: "prop",
+ instanceId: "heading",
+ name: "title",
+ type: "string",
+ value: "Heading",
+ },
+ ],
+ [
+ "labelProp",
+ {
+ id: "labelProp",
+ instanceId: "heading",
+ name: "aria-label",
+ type: "string",
+ value: "Heading label",
+ },
+ ],
+ [
+ "resourceProp",
+ {
+ id: "resourceProp",
+ instanceId: "heading",
+ name: "src",
+ type: "resource",
+ value: "resource",
+ },
+ ],
+ ]),
+ styleSources: new Map([
+ ["local", { type: "local", id: "local" }],
+ ["token", { type: "token", id: "token", name: "Brand" }],
+ ]),
+ styleSourceSelections: new Map([
+ ["heading", { instanceId: "heading", values: ["token", "local"] }],
+ ]),
+ styles: new Map([
+ [
+ "local:base::color",
+ {
+ styleSourceId: "local",
+ breakpointId: "base",
+ state: undefined,
+ property: "color",
+ value: { type: "unparsed", value: "var(--brand-color)" },
+ },
+ ],
+ [
+ "local:base::--brand-color",
+ {
+ styleSourceId: "local",
+ breakpointId: "base",
+ state: undefined,
+ property: "--brand-color",
+ value: { type: "keyword", value: "red" },
+ },
+ ],
+ [
+ "token:base::color",
+ {
+ styleSourceId: "token",
+ breakpointId: "base",
+ state: undefined,
+ property: "color",
+ value: { type: "keyword", value: "blue" },
+ },
+ ],
+ ]),
+ dataSources: new Map([
+ [
+ "variable",
+ {
+ id: "variable",
+ type: "variable",
+ name: "Title",
+ scopeInstanceId: "heading",
+ value: { type: "string", value: "Hello" },
+ },
+ ],
+ [
+ "resourceDataSource",
+ {
+ id: "resourceDataSource",
+ type: "resource",
+ name: "Posts",
+ scopeInstanceId: "heading",
+ resourceId: "resource",
+ },
+ ],
+ ]),
+ resources: new Map([
+ [
+ "resource",
+ {
+ id: "resource",
+ name: "Posts",
+ method: "get",
+ url: `"/posts"`,
+ headers: [],
+ searchParams: [],
+ },
+ ],
+ ]),
+ assets: new Map([
+ [
+ "asset",
+ {
+ id: "asset",
+ projectId: "project",
+ name: "asset.png",
+ type: "image",
+ size: 1,
+ format: "png",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ description: null,
+ meta: { width: 100, height: 100 },
+ },
+ ],
+ [
+ "next",
+ {
+ id: "next",
+ projectId: "project",
+ name: "next.png",
+ type: "image",
+ size: 1,
+ format: "png",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ filename: "Hero",
+ description: null,
+ meta: { width: 100, height: 100 },
+ },
+ ],
+ ]),
+ breakpoints: new Map([
+ ["base", { id: "base", label: "Base" }],
+ ["desktop", { id: "desktop", label: "Desktop", minWidth: 1024 }],
+ ]),
+} satisfies BuilderState;
diff --git a/packages/project-build/src/runtime/search.ts b/packages/project-build/src/runtime/search.ts
new file mode 100644
index 0000000000..062aa6c5e2
--- /dev/null
+++ b/packages/project-build/src/runtime/search.ts
@@ -0,0 +1,1477 @@
+import { z } from "zod";
+import { isLiteralExpression, type StyleDecl } from "@webstudio-is/sdk";
+import { hasTopLevelJsonLdContext } from "@webstudio-is/sdk/runtime";
+import { validateJsonLdWithSchemaOrg } from "@webstudio-is/sdk/schema-org";
+import { ariaAttributes, ariaRoles } from "@webstudio-is/html-data";
+import * as bcp47 from "bcp-47";
+import type { BuilderState } from "../state/builder-state";
+import { throwBuilderRuntimeError } from "./errors";
+import { computeExpression } from "./data";
+import { listAssets } from "./assets";
+import { listCssVariables, listDesignTokens } from "./styles";
+import { getInstanceDepths } from "./instances";
+import { isBaseBreakpoint } from "./breakpoints";
+import { findSerializedPageByInput, getSerializedPages } from "./pages";
+import { validatePageSelector } from "./page-selector";
+import { hasAccessibleName, isDynamicPropType } from "./accessibility-analysis";
+
+const projectLookupScope = z.enum([
+ "instances",
+ "text",
+ "props",
+ "resources",
+ "assets",
+ "styles",
+]);
+
+const projectAnalysisScope = z.enum([
+ ...projectLookupScope.options,
+ "accessibility",
+ "security",
+ "seo",
+ "performance",
+]);
+
+export const projectSearchInput = z
+ .object({
+ query: z.string().min(1),
+ scopes: z.array(projectLookupScope).min(1).optional(),
+ pageId: z.string().optional(),
+ pagePath: z.string().optional(),
+ limit: z.number().int().min(1).max(200).optional(),
+ })
+ .strict()
+ .superRefine(validatePageSelector);
+
+type ProjectAnalysisInput = {
+ query?: string;
+ scopes?: Array<z.infer<typeof projectAnalysisScope>>;
+ pageId?: string;
+ pagePath?: string;
+ limit?: number;
+};
+
+const defaultScopes = projectLookupScope.options;
+
+const serializeValue = (value: unknown) => {
+ if (typeof value === "string") {
+ return value;
+ }
+ try {
+ return JSON.stringify(value) ?? String(value);
+ } catch {
+ return String(value);
+ }
+};
+
+const matchesQuery = (query: string | undefined, ...values: unknown[]) =>
+ query === undefined ||
+ values.some((value) =>
+ serializeValue(value)
+ .toLocaleLowerCase()
+ .includes(query.toLocaleLowerCase())
+ );
+
+const isStaticAriaNumber = (value: string | number) => {
+ if (typeof value === "number") {
+ return Number.isFinite(value);
+ }
+ return (
+ /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(value.trim()) &&
+ Number.isFinite(Number(value))
+ );
+};
+
+const hasNonEmptyProp = (
+ props: ReadonlyMap<string, unknown> | undefined,
+ name: string
+) => {
+ const value = props?.get(name);
+ return (
+ value !== undefined && (typeof value !== "string" || value.trim() !== "")
+ );
+};
+
+const hasDynamicProp = (
+ propTypes: ReadonlyMap<string, string> | undefined,
+ ...names: string[]
+) => names.some((name) => isDynamicPropType(propTypes?.get(name)));
+
+const ariaLiteralValues = new Map<string, ReadonlySet<string | boolean>>();
+const ariaNumberAttributes = new Set<string>();
+for (const attribute of ariaAttributes) {
+ if (attribute.type === "boolean") {
+ ariaLiteralValues.set(
+ attribute.name,
+ new Set([true, false, "true", "false"])
+ );
+ }
+ if (attribute.type === "select") {
+ ariaLiteralValues.set(attribute.name, new Set(attribute.options));
+ }
+ if (attribute.type === "number") {
+ ariaNumberAttributes.add(attribute.name);
+ }
+}
+
+const ariaIdReferenceAttributes = [
+ "aria-activedescendant",
+ "aria-controls",
+ "aria-describedby",
+ "aria-details",
+ "aria-errormessage",
+ "aria-flowto",
+ "aria-labelledby",
+ "aria-owns",
+] as const;
+
+const getPageInstanceIds = (
+ state: Pick<BuilderState, "pages" | "instances">,
+ input: Pick<ProjectAnalysisInput, "pageId" | "pagePath">
+) => {
+ if (input.pageId === undefined && input.pagePath === undefined) {
+ return;
+ }
+ const page = findSerializedPageByInput(getSerializedPages(state), input);
+ if (page === undefined) {
+ return throwBuilderRuntimeError("NOT_FOUND", "Page not found");
+ }
+ if (state.instances === undefined) {
+ return throwBuilderRuntimeError("BAD_REQUEST", "Instances are required");
+ }
+ return new Set(
+ getInstanceDepths(state.instances, [page.rootInstanceId]).keys()
+ );
+};
+
+const isInteractiveInstance = ({
+ component,
+ tag,
+ props,
+}: {
+ component: string;
+ tag?: string;
+ props: ReadonlyMap<string, unknown> | undefined;
+}) =>
+ component === "Button" ||
+ component === "Link" ||
+ tag === "button" ||
+ tag === "a" ||
+ props?.get("role") === "button" ||
+ props?.get("role") === "link";
+
+const isLabelInstance = ({
+ component,
+ tag,
+}: {
+ component: string;
+ tag?: string;
+}) => component === "Label" || tag === "label";
+
+const isLabelableFormControl = ({
+ component,
+ tag,
+ props,
+}: {
+ component: string;
+ tag?: string;
+ props: ReadonlyMap<string, unknown> | undefined;
+}) => {
+ if (
+ component !== "Input" &&
+ component !== "Select" &&
+ component !== "Textarea" &&
+ tag !== "input" &&
+ tag !== "select" &&
+ tag !== "textarea"
+ ) {
+ return false;
+ }
+ if (component !== "Input" && tag !== "input") {
+ return true;
+ }
+ const type = props?.get("type");
+ if (typeof type !== "string") {
+ return true;
+ }
+ return (
+ ["hidden", "button", "submit", "reset", "image"].includes(
+ type.toLocaleLowerCase()
+ ) === false
+ );
+};
+
+const createParentIdsByInstance = (
+ instances: NonNullable<BuilderState["instances"]>
+) => {
+ const parentIdsByInstance = new Map<string, string[]>();
+ for (const instance of instances.values()) {
+ for (const child of instance.children) {
+ if (child.type !== "id") {
+ continue;
+ }
+ const parentIds = parentIdsByInstance.get(child.value) ?? [];
+ parentIds.push(instance.id);
+ parentIdsByInstance.set(child.value, parentIds);
+ }
+ }
+ return parentIdsByInstance;
+};
+
+const hasAssociatedFormLabel = ({
+ instanceId,
+ instances,
+ propsByInstance,
+ parentIdsByInstance,
+ relatedInstanceIds,
+}: {
+ instanceId: string;
+ instances: NonNullable<BuilderState["instances"]>;
+ propsByInstance: ReadonlyMap<string, ReadonlyMap<string, unknown>>;
+ parentIdsByInstance: ReadonlyMap<string, readonly string[]>;
+ relatedInstanceIds: ReadonlySet<string> | undefined;
+}) => {
+ const id = propsByInstance.get(instanceId)?.get("id");
+ for (const label of instances.values()) {
+ if (
+ isLabelInstance(label) === false ||
+ (relatedInstanceIds !== undefined &&
+ relatedInstanceIds.has(label.id) === false)
+ ) {
+ continue;
+ }
+ if (
+ id !== undefined &&
+ propsByInstance.get(label.id)?.get("for") === id &&
+ hasAccessibleName({
+ instanceId: label.id,
+ instances,
+ propsByInstance,
+ })
+ ) {
+ return true;
+ }
+ }
+ const visited = new Set<string>();
+ const hasLabelAncestor = (currentId: string): boolean => {
+ if (visited.has(currentId)) {
+ return false;
+ }
+ visited.add(currentId);
+ return (parentIdsByInstance.get(currentId) ?? []).some((parentId) => {
+ const parent = instances.get(parentId);
+ if (parent === undefined) {
+ return false;
+ }
+ if (isLabelInstance(parent)) {
+ return hasAccessibleName({
+ instanceId: parentId,
+ instances,
+ propsByInstance,
+ });
+ }
+ return hasLabelAncestor(parentId);
+ });
+ };
+ return hasLabelAncestor(instanceId);
+};
+
+const getHeadingLevel = (tag: string | undefined) => {
+ if (tag === undefined || /^h[1-6]$/.test(tag) === false) {
+ return;
+ }
+ return Number(tag.slice(1));
+};
+
+const getPagesToAudit = (
+ state: Pick<BuilderState, "pages">,
+ input: Pick<ProjectAnalysisInput, "pageId" | "pagePath">
+) => {
+ const pages = getSerializedPages(state);
+ const selectedPages =
+ input.pageId === undefined && input.pagePath === undefined
+ ? pages.pages
+ : [findSerializedPageByInput(pages, input)].filter(
+ (page): page is (typeof pages.pages)[number] => page !== undefined
+ );
+ return selectedPages.filter(
+ (page) =>
+ page.meta.documentType !== "xml" && page.meta.documentType !== "text"
+ );
+};
+
+const getRelatedPageInstanceIds = (
+ instanceId: string,
+ pageInstanceIds: readonly ReadonlySet<string>[]
+) => {
+ const related = new Set<string>();
+ for (const ids of pageInstanceIds) {
+ if (ids.has(instanceId)) {
+ for (const id of ids) {
+ related.add(id);
+ }
+ }
+ }
+ return related.size === 0 ? undefined : related;
+};
+
+const getStaticString = (expression: string) => {
+ if (isLiteralExpression(expression) === false) {
+ return;
+ }
+ const value = computeExpression(expression, new Map());
+ return typeof value === "string" ? value : undefined;
+};
+
+export const analyzeProject = (
+ state: Pick<
+ BuilderState,
+ | "pages"
+ | "projectSettings"
+ | "instances"
+ | "props"
+ | "styles"
+ | "styleSources"
+ | "styleSourceSelections"
+ | "resources"
+ | "dataSources"
+ | "assets"
+ | "breakpoints"
+ >,
+ input: ProjectAnalysisInput
+) => {
+ if (
+ state.instances === undefined ||
+ state.props === undefined ||
+ state.styles === undefined ||
+ state.styleSources === undefined ||
+ state.styleSourceSelections === undefined ||
+ state.resources === undefined ||
+ state.dataSources === undefined ||
+ state.assets === undefined ||
+ state.breakpoints === undefined
+ ) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "Project search requires instances, props, styles, style sources, resources, data sources, assets, and breakpoints"
+ );
+ }
+ const instances = state.instances;
+ const scopes = new Set(input.scopes ?? defaultScopes);
+ const instanceIds = getPageInstanceIds(state, input);
+ const pageInstanceIds = getPagesToAudit(state, {}).map(
+ (page) =>
+ new Set(getInstanceDepths(instances, [page.rootInstanceId]).keys())
+ );
+ const getRelatedInstanceIds = (instanceId: string) =>
+ instanceIds ?? getRelatedPageInstanceIds(instanceId, pageInstanceIds);
+ const isInScope = (instanceId: string) =>
+ instanceIds === undefined || instanceIds.has(instanceId);
+ const matches: Array<Record<string, unknown>> = [];
+
+ if (scopes.has("instances")) {
+ for (const instance of state.instances.values()) {
+ if (
+ isInScope(instance.id) &&
+ matchesQuery(
+ input.query,
+ instance.id,
+ instance.component,
+ instance.tag,
+ instance.label
+ )
+ ) {
+ matches.push({
+ kind: "instance",
+ instanceId: instance.id,
+ component: instance.component,
+ tag: instance.tag,
+ label: instance.label,
+ });
+ }
+ }
+ }
+
+ if (scopes.has("text")) {
+ for (const instance of state.instances.values()) {
+ if (isInScope(instance.id) === false) {
+ continue;
+ }
+ for (const [childIndex, child] of instance.children.entries()) {
+ if (
+ (child.type === "text" || child.type === "expression") &&
+ matchesQuery(input.query, child.value)
+ ) {
+ matches.push({
+ kind: "text",
+ instanceId: instance.id,
+ childIndex,
+ mode: child.type,
+ value: child.value,
+ });
+ }
+ }
+ }
+ }
+
+ if (scopes.has("props")) {
+ for (const prop of state.props.values()) {
+ if (
+ isInScope(prop.instanceId) &&
+ matchesQuery(input.query, prop.id, prop.name, prop.value)
+ ) {
+ matches.push({
+ kind: "prop",
+ propId: prop.id,
+ instanceId: prop.instanceId,
+ name: prop.name,
+ type: prop.type,
+ value: prop.value,
+ });
+ }
+ }
+ }
+
+ if (scopes.has("resources")) {
+ for (const resource of state.resources.values()) {
+ const scopedDataSources = Array.from(state.dataSources.values()).filter(
+ (dataSource) =>
+ dataSource.type === "resource" &&
+ dataSource.resourceId === resource.id
+ );
+ if (
+ instanceIds !== undefined &&
+ scopedDataSources.length > 0 &&
+ scopedDataSources.some(
+ (dataSource) =>
+ dataSource.scopeInstanceId !== undefined &&
+ instanceIds.has(dataSource.scopeInstanceId)
+ ) === false
+ ) {
+ continue;
+ }
+ if (matchesQuery(input.query, resource.id, resource.name, resource.url)) {
+ matches.push({
+ kind: "resource",
+ resourceId: resource.id,
+ name: resource.name,
+ method: resource.method,
+ url: resource.url,
+ });
+ }
+ }
+ }
+
+ if (scopes.has("assets")) {
+ if (input.query === undefined) {
+ for (const asset of listAssets(state, { withUsage: true }).items) {
+ if (asset.usageCount !== 0) {
+ continue;
+ }
+ matches.push({
+ kind: "asset",
+ issue: "unused-asset",
+ assetId: asset.id,
+ type: asset.type,
+ name: asset.name,
+ message: "Asset has no project references.",
+ });
+ }
+ } else {
+ for (const asset of state.assets.values()) {
+ if (
+ matchesQuery(
+ input.query,
+ asset.id,
+ asset.name,
+ asset.filename,
+ asset.description
+ )
+ ) {
+ matches.push({
+ kind: "asset",
+ assetId: asset.id,
+ type: asset.type,
+ name: asset.name,
+ filename: asset.filename,
+ description: asset.description,
+ });
+ }
+ }
+ }
+ }
+
+ if (scopes.has("styles")) {
+ const designTokens = listDesignTokens(state, {
+ withUsage: true,
+ }).tokens;
+ for (const token of designTokens) {
+ if (
+ input.query !== undefined &&
+ matchesQuery(input.query, token.id, token.name) === false
+ ) {
+ continue;
+ }
+ if (input.query === undefined && token.usageCount !== 0) {
+ continue;
+ }
+ matches.push({
+ kind: "design-token",
+ ...(input.query === undefined ? { issue: "unused-design-token" } : {}),
+ designTokenId: token.id,
+ name: token.name,
+ declarationCount: token.declarationCount,
+ usageCount: token.usageCount,
+ ...(input.query === undefined
+ ? { message: "Design token has no element assignments." }
+ : {}),
+ });
+ }
+
+ if (input.query === undefined) {
+ const declarationsByStyleSourceId = new Map<string, StyleDecl[]>();
+ for (const declaration of state.styles.values()) {
+ const declarations =
+ declarationsByStyleSourceId.get(declaration.styleSourceId) ?? [];
+ declarations.push(declaration);
+ declarationsByStyleSourceId.set(
+ declaration.styleSourceId,
+ declarations
+ );
+ }
+ const instancesByStyleSourceId = new Map<string, Set<string>>();
+ for (const selection of state.styleSourceSelections.values()) {
+ for (const styleSourceId of selection.values) {
+ const instanceIds =
+ instancesByStyleSourceId.get(styleSourceId) ?? new Set<string>();
+ instanceIds.add(selection.instanceId);
+ instancesByStyleSourceId.set(styleSourceId, instanceIds);
+ }
+ }
+
+ for (const instance of state.instances.values()) {
+ if (instance.component !== "ws:collection") {
+ continue;
+ }
+ const selection = state.styleSourceSelections.get(instance.id);
+ for (const styleSourceId of selection?.values ?? []) {
+ const declarationCount =
+ declarationsByStyleSourceId.get(styleSourceId)?.length ?? 0;
+ if (declarationCount === 0) {
+ continue;
+ }
+ matches.push({
+ kind: "style-source",
+ issue: "style-on-dom-transparent-component",
+ instanceId: instance.id,
+ styleSourceId,
+ component: instance.component,
+ declarationCount,
+ message:
+ "Collection does not render a DOM wrapper, so styles assigned directly to it have no visual effect.",
+ });
+ }
+ }
+
+ for (const variable of listCssVariables(state, { withUsage: true })
+ .vars) {
+ if (variable.usageCount !== 0) {
+ continue;
+ }
+ matches.push({
+ kind: "css-variable",
+ issue: "unused-css-variable",
+ name: variable.name,
+ scope: variable.scope,
+ usageCount: variable.usageCount,
+ message:
+ "CSS variable has no references. Remove it or use it in a style or embed.",
+ });
+ }
+
+ for (const styleSource of state.styleSources.values()) {
+ if (styleSource.type !== "local") {
+ continue;
+ }
+ const declarationCount =
+ declarationsByStyleSourceId.get(styleSource.id)?.length ?? 0;
+ const usageCount =
+ instancesByStyleSourceId.get(styleSource.id)?.size ?? 0;
+ if (declarationCount === 0 || usageCount > 0) {
+ continue;
+ }
+ matches.push({
+ kind: "style-source",
+ issue: "unused-local-style-source",
+ styleSourceId: styleSource.id,
+ declarationCount,
+ message:
+ "Local style source has declarations but is not assigned to any element.",
+ });
+ }
+
+ const breakpointIdsWithDeclarations = new Set(
+ Array.from(
+ state.styles.values(),
+ (declaration) => declaration.breakpointId
+ )
+ );
+ for (const breakpoint of state.breakpoints.values()) {
+ if (
+ breakpoint.condition === undefined &&
+ isBaseBreakpoint(breakpoint)
+ ) {
+ continue;
+ }
+ if (breakpointIdsWithDeclarations.has(breakpoint.id) === false) {
+ matches.push({
+ kind: "breakpoint",
+ issue: "unused-breakpoint",
+ breakpointId: breakpoint.id,
+ label: breakpoint.label,
+ message:
+ "Breakpoint has no style declarations. Remove it or add responsive styles.",
+ });
+ }
+ }
+
+ const tokensByDeclarationSignature = new Map<
+ string,
+ Array<{ id: string; name: string }>
+ >();
+ for (const token of designTokens) {
+ const declarations = [
+ ...(declarationsByStyleSourceId.get(token.id) ?? []),
+ ].sort((left, right) =>
+ `${left.breakpointId}:${left.state ?? ""}:${left.property}`.localeCompare(
+ `${right.breakpointId}:${right.state ?? ""}:${right.property}`
+ )
+ );
+ if (declarations.length === 0) {
+ continue;
+ }
+ const signature = JSON.stringify(
+ declarations.map(({ breakpointId, state, property, value }) => ({
+ breakpointId,
+ state,
+ property,
+ value,
+ }))
+ );
+ const tokens = tokensByDeclarationSignature.get(signature) ?? [];
+ tokens.push({ id: token.id, name: token.name });
+ tokensByDeclarationSignature.set(signature, tokens);
+ }
+ for (const tokens of tokensByDeclarationSignature.values()) {
+ if (tokens.length < 2) {
+ continue;
+ }
+ matches.push({
+ kind: "design-token",
+ issue: "duplicate-design-token-declarations",
+ designTokenIds: tokens.map((token) => token.id),
+ names: tokens.map((token) => token.name),
+ message:
+ "Design tokens have identical declarations. Review whether they are intentional aliases or can be consolidated.",
+ });
+ }
+ }
+ }
+
+ if (
+ scopes.has("performance") &&
+ input.query === undefined &&
+ state.projectSettings?.compiler.atomicStyles === false
+ ) {
+ matches.push({
+ kind: "performance",
+ issue: "atomic-css-disabled",
+ atomicStyles: false,
+ message:
+ "Atomic CSS generation is disabled. Published CSS may be substantially larger.",
+ });
+ }
+
+ if (scopes.has("accessibility")) {
+ const propsByInstance = new Map<string, Map<string, unknown>>();
+ const propTypesByInstance = new Map<string, Map<string, string>>();
+ const staticIdByInstance = new Map<string, string>();
+ const staticAriaReferencesByName = new Map<string, Map<string, string>>(
+ ariaIdReferenceAttributes.map((name) => [name, new Map<string, string>()])
+ );
+ for (const prop of state.props.values()) {
+ const props = propsByInstance.get(prop.instanceId) ?? new Map();
+ props.set(
+ prop.name,
+ isDynamicPropType(prop.type) ? undefined : prop.value
+ );
+ propsByInstance.set(prop.instanceId, props);
+ const propTypes = propTypesByInstance.get(prop.instanceId) ?? new Map();
+ propTypes.set(prop.name, prop.type);
+ propTypesByInstance.set(prop.instanceId, propTypes);
+ if (
+ prop.name === "id" &&
+ prop.type === "string" &&
+ typeof prop.value === "string" &&
+ prop.value.trim().length > 0
+ ) {
+ staticIdByInstance.set(prop.instanceId, prop.value);
+ }
+ const staticReferences = staticAriaReferencesByName.get(prop.name);
+ if (
+ staticReferences !== undefined &&
+ prop.type === "string" &&
+ typeof prop.value === "string" &&
+ prop.value.trim().length > 0
+ ) {
+ staticReferences.set(prop.instanceId, prop.value);
+ }
+ }
+ const parentIdsByInstance = createParentIdsByInstance(state.instances);
+ for (const instance of state.instances.values()) {
+ if (isInScope(instance.id) === false) {
+ continue;
+ }
+ const props = propsByInstance.get(instance.id);
+ const propTypes = propTypesByInstance.get(instance.id);
+ if (
+ (instance.component === "Image" || instance.tag === "img") &&
+ props?.has("alt") !== true
+ ) {
+ matches.push({
+ kind: "accessibility",
+ issue: "missing-alt",
+ instanceId: instance.id,
+ component: instance.component,
+ message: "Image has no alt prop.",
+ });
+ } else if (instance.component === "Image" || instance.tag === "img") {
+ const altType = propTypes?.get("alt");
+ const altValue = props?.get("alt");
+ const asset =
+ altType === "asset" && typeof altValue === "string"
+ ? state.assets.get(altValue)
+ : undefined;
+ if (
+ altType === "asset" &&
+ (asset === undefined || asset.description == null)
+ ) {
+ matches.push({
+ kind: "accessibility",
+ issue: "missing-image-description",
+ instanceId: instance.id,
+ component: instance.component,
+ ...(asset === undefined ? {} : { assetId: asset.id }),
+ message: "Image asset has no description or decorative marker.",
+ });
+ }
+ }
+ const inputType = props?.get("type");
+ if (
+ instance.tag === "input" &&
+ propTypes?.get("type") === "string" &&
+ typeof inputType === "string" &&
+ inputType.toLocaleLowerCase() === "image" &&
+ hasDynamicProp(propTypes, "alt") === false &&
+ hasNonEmptyProp(props, "alt") === false
+ ) {
+ matches.push({
+ kind: "accessibility",
+ issue: "missing-image-input-alt",
+ instanceId: instance.id,
+ component: instance.component,
+ message: "Image submit input has no accessible alt label.",
+ });
+ }
+ if (
+ instance.tag === "iframe" &&
+ hasDynamicProp(propTypes, "title") === false &&
+ hasNonEmptyProp(props, "title") === false
+ ) {
+ matches.push({
+ kind: "accessibility",
+ issue: "missing-iframe-title",
+ instanceId: instance.id,
+ component: instance.component,
+ message: "Iframe has no title prop.",
+ });
+ }
+ if (
+ isInteractiveInstance({ ...instance, props }) &&
+ hasDynamicProp(propTypes, "aria-label", "aria-labelledby", "title") ===
+ false &&
+ hasAccessibleName({
+ instanceId: instance.id,
+ instances: state.instances,
+ propsByInstance,
+ }) === false
+ ) {
+ matches.push({
+ kind: "accessibility",
+ issue: "missing-accessible-name",
+ instanceId: instance.id,
+ component: instance.component,
+ tag: instance.tag,
+ message:
+ "Interactive element has no visible text or accessible name.",
+ });
+ }
+ if (
+ isLabelableFormControl({
+ component: instance.component,
+ tag: instance.tag,
+ props,
+ }) &&
+ hasDynamicProp(propTypes, "aria-label", "aria-labelledby", "title") ===
+ false &&
+ hasAccessibleName({
+ instanceId: instance.id,
+ instances: state.instances,
+ propsByInstance,
+ }) === false &&
+ hasAssociatedFormLabel({
+ instanceId: instance.id,
+ instances: state.instances,
+ propsByInstance,
+ parentIdsByInstance,
+ relatedInstanceIds: getRelatedInstanceIds(instance.id),
+ }) === false
+ ) {
+ matches.push({
+ kind: "accessibility",
+ issue: "missing-form-label",
+ instanceId: instance.id,
+ component: instance.component,
+ tag: instance.tag,
+ message: "Form control has no accessible name or associated label.",
+ });
+ }
+ const tabIndex = props?.get("tabindex");
+ const hasNonNegativeTabIndex =
+ propTypes?.get("tabindex") === "number" &&
+ typeof tabIndex === "number" &&
+ tabIndex >= 0;
+ const isFocusable =
+ isInteractiveInstance({ ...instance, props }) ||
+ isLabelableFormControl({
+ component: instance.component,
+ tag: instance.tag,
+ props,
+ }) ||
+ hasNonNegativeTabIndex;
+ const role = props?.get("role");
+ if (propTypes?.get("role") === "string" && typeof role === "string") {
+ const roleDefinition = ariaRoles.get(role as never);
+ if (roleDefinition === undefined) {
+ matches.push({
+ kind: "accessibility",
+ issue: "invalid-aria-role",
+ instanceId: instance.id,
+ component: instance.component,
+ tag: instance.tag,
+ role,
+ message: `Role ${JSON.stringify(role)} is not a known ARIA role.`,
+ });
+ } else {
+ const allowedProps = new Set(Object.keys(roleDefinition.props));
+ for (const [name, value] of props ?? []) {
+ if (
+ name.startsWith("aria-") &&
+ propTypes?.get(name) !== "expression" &&
+ allowedProps.has(name) === false
+ ) {
+ matches.push({
+ kind: "accessibility",
+ issue: "unsupported-aria-role-property",
+ instanceId: instance.id,
+ component: instance.component,
+ tag: instance.tag,
+ role,
+ name,
+ value,
+ message: `${name} is not supported by role ${JSON.stringify(role)}.`,
+ });
+ }
+ }
+ for (const name of Object.keys(roleDefinition.requiredProps)) {
+ if (props?.has(name) === true) {
+ continue;
+ }
+ matches.push({
+ kind: "accessibility",
+ issue: "missing-required-aria-role-property",
+ instanceId: instance.id,
+ component: instance.component,
+ tag: instance.tag,
+ role,
+ name,
+ message: `${role} requires ${name}.`,
+ });
+ }
+ }
+ }
+ if (
+ propTypes?.get("role") === "string" &&
+ (role === "button" || role === "link") &&
+ ((role === "button" && instance.tag !== "button") ||
+ (role === "link" && instance.tag !== "a")) &&
+ hasNonNegativeTabIndex === false
+ ) {
+ matches.push({
+ kind: "accessibility",
+ issue: "role-interactive-not-focusable",
+ instanceId: instance.id,
+ component: instance.component,
+ tag: instance.tag,
+ role,
+ message: `Non-native element with role ${JSON.stringify(role)} is not keyboard-focusable.`,
+ });
+ }
+ if (
+ isFocusable &&
+ (props?.get("aria-hidden") === true ||
+ props?.get("aria-hidden") === "true") &&
+ (propTypes?.get("aria-hidden") === "boolean" ||
+ propTypes?.get("aria-hidden") === "string")
+ ) {
+ matches.push({
+ kind: "accessibility",
+ issue: "aria-hidden-focusable",
+ instanceId: instance.id,
+ component: instance.component,
+ tag: instance.tag,
+ message:
+ "Focusable element is hidden from assistive technology with aria-hidden.",
+ });
+ }
+ if (
+ propTypes?.get("tabindex") === "number" &&
+ typeof tabIndex === "number" &&
+ tabIndex > 0
+ ) {
+ matches.push({
+ kind: "accessibility",
+ issue: "positive-tabindex",
+ instanceId: instance.id,
+ component: instance.component,
+ tag: instance.tag,
+ tabindex: tabIndex,
+ message:
+ "Positive tabindex changes the natural keyboard focus order.",
+ });
+ }
+ for (const [name, validValues] of ariaLiteralValues) {
+ const value = props?.get(name);
+ const type = propTypes?.get(name);
+ if (
+ value === undefined ||
+ (typeof value !== "boolean" && typeof value !== "string") ||
+ type === "expression" ||
+ validValues.has(value) ||
+ (type !== "boolean" && type !== "string")
+ ) {
+ continue;
+ }
+ matches.push({
+ kind: "accessibility",
+ issue: "invalid-aria-state",
+ instanceId: instance.id,
+ component: instance.component,
+ tag: instance.tag,
+ name,
+ value,
+ message: `${name} has an unsupported static value ${JSON.stringify(value)}.`,
+ });
+ }
+ for (const name of ariaNumberAttributes) {
+ const value = props?.get(name);
+ const type = propTypes?.get(name);
+ if (
+ value === undefined ||
+ type === "expression" ||
+ (type !== "number" && type !== "string") ||
+ (typeof value !== "number" && typeof value !== "string") ||
+ isStaticAriaNumber(value)
+ ) {
+ continue;
+ }
+ matches.push({
+ kind: "accessibility",
+ issue: "invalid-aria-number",
+ instanceId: instance.id,
+ component: instance.component,
+ tag: instance.tag,
+ name,
+ value,
+ message: `${name} must have a static numeric value.`,
+ });
+ }
+ if (
+ (instance.tag === "audio" || instance.tag === "video") &&
+ propTypes?.get("autoplay") === "boolean" &&
+ props?.get("autoplay") === true &&
+ props?.get("muted") !== true
+ ) {
+ matches.push({
+ kind: "accessibility",
+ issue: "autoplay-media-with-sound",
+ instanceId: instance.id,
+ component: instance.component,
+ tag: instance.tag,
+ message: "Autoplaying media is not muted.",
+ });
+ }
+ }
+
+ for (const instance of state.instances.values()) {
+ if (
+ isInScope(instance.id) === false ||
+ isLabelInstance(instance) === false
+ ) {
+ continue;
+ }
+ const htmlFor = propsByInstance.get(instance.id)?.get("for");
+ if (typeof htmlFor !== "string" || htmlFor.trim().length === 0) {
+ continue;
+ }
+ const relatedInstanceIds = getRelatedInstanceIds(instance.id);
+ const target = Array.from(state.instances.values()).find(
+ (candidate) =>
+ (relatedInstanceIds === undefined ||
+ relatedInstanceIds.has(candidate.id)) &&
+ staticIdByInstance.get(candidate.id) === htmlFor
+ );
+ if (
+ target !== undefined &&
+ isLabelableFormControl({
+ component: target.component,
+ tag: target.tag,
+ props: propsByInstance.get(target.id),
+ })
+ ) {
+ continue;
+ }
+ matches.push({
+ kind: "accessibility",
+ issue: "invalid-label-reference",
+ instanceId: instance.id,
+ htmlFor,
+ message: `Label references missing or non-labelable control ${JSON.stringify(htmlFor)}.`,
+ });
+ }
+
+ for (const page of getPagesToAudit(state, input)) {
+ const instances = state.instances;
+ if (
+ instances === undefined ||
+ instances.has(page.rootInstanceId) === false
+ ) {
+ continue;
+ }
+ const pageInstances = Array.from(
+ getInstanceDepths(instances, [page.rootInstanceId]).keys()
+ ).flatMap((instanceId) => {
+ const instance = instances.get(instanceId);
+ return instance === undefined ? [] : [instance];
+ });
+ const headings = pageInstances.flatMap((instance) => {
+ const level = getHeadingLevel(instance.tag);
+ return level === undefined ? [] : [{ instance, level }];
+ });
+ if (headings.some(({ level }) => level === 1) === false) {
+ matches.push({
+ kind: "accessibility",
+ issue: "missing-page-heading",
+ pageId: page.id,
+ pagePath: page.path,
+ message: "Page has no h1 heading.",
+ });
+ }
+ for (const [index, heading] of headings.entries()) {
+ const previous = headings[index - 1];
+ if (previous !== undefined && heading.level > previous.level + 1) {
+ matches.push({
+ kind: "accessibility",
+ issue: "skipped-heading-level",
+ pageId: page.id,
+ pagePath: page.path,
+ instanceId: heading.instance.id,
+ fromLevel: previous.level,
+ toLevel: heading.level,
+ message: `Heading level jumps from h${previous.level} to h${heading.level}.`,
+ });
+ }
+ }
+ const mainLandmarks = pageInstances.filter(
+ (instance) => instance.tag === "main"
+ );
+ if (mainLandmarks.length === 0) {
+ matches.push({
+ kind: "accessibility",
+ issue: "missing-main-landmark",
+ pageId: page.id,
+ pagePath: page.path,
+ message: "Page has no main landmark.",
+ });
+ }
+ if (mainLandmarks.length > 1) {
+ matches.push({
+ kind: "accessibility",
+ issue: "multiple-main-landmarks",
+ pageId: page.id,
+ pagePath: page.path,
+ instanceIds: mainLandmarks.map((instance) => instance.id),
+ message: "Page has multiple main landmarks.",
+ });
+ }
+ const instancesByIdValue = new Map<string, string[]>();
+ for (const instance of pageInstances) {
+ const id = staticIdByInstance.get(instance.id);
+ if (id === undefined) {
+ continue;
+ }
+ const matchingInstances = instancesByIdValue.get(id) ?? [];
+ matchingInstances.push(instance.id);
+ instancesByIdValue.set(id, matchingInstances);
+ }
+ for (const [id, instanceIds] of instancesByIdValue) {
+ if (instanceIds.length < 2) {
+ continue;
+ }
+ matches.push({
+ kind: "accessibility",
+ issue: "duplicate-id",
+ pageId: page.id,
+ pagePath: page.path,
+ id,
+ instanceIds,
+ message: `Page has multiple elements with id ${JSON.stringify(id)}.`,
+ });
+ }
+ const ids = new Set(instancesByIdValue.keys());
+ for (const [name, referencesByInstance] of staticAriaReferencesByName) {
+ for (const instance of pageInstances) {
+ const references = referencesByInstance.get(instance.id);
+ if (references === undefined) {
+ continue;
+ }
+ for (const id of references.trim().split(/\s+/)) {
+ if (ids.has(id)) {
+ continue;
+ }
+ matches.push({
+ kind: "accessibility",
+ issue: "missing-aria-reference",
+ pageId: page.id,
+ pagePath: page.path,
+ instanceId: instance.id,
+ name,
+ id,
+ message: `${name} references missing id ${JSON.stringify(id)}.`,
+ });
+ }
+ }
+ }
+ }
+ }
+
+ if (scopes.has("security")) {
+ for (const dataSource of state.dataSources.values()) {
+ if (
+ dataSource.type !== "resource" ||
+ (instanceIds !== undefined &&
+ (dataSource.scopeInstanceId === undefined ||
+ instanceIds.has(dataSource.scopeInstanceId) === false))
+ ) {
+ continue;
+ }
+ const resource = state.resources.get(dataSource.resourceId);
+ if (resource === undefined || resource.method === "get") {
+ continue;
+ }
+ matches.push({
+ kind: "security",
+ issue: "non-get-resource-exposed-as-data-source",
+ instanceId: dataSource.scopeInstanceId,
+ dataSourceId: dataSource.id,
+ resourceId: resource.id,
+ method: resource.method,
+ message: `${resource.method.toUpperCase()} resource ${JSON.stringify(resource.name)} is exposed as render-time data.`,
+ });
+ }
+ const propsByInstance = new Map<
+ string,
+ Map<string, { type: string; value: unknown }>
+ >();
+ for (const prop of state.props.values()) {
+ const props = propsByInstance.get(prop.instanceId) ?? new Map();
+ props.set(prop.name, { type: prop.type, value: prop.value });
+ propsByInstance.set(prop.instanceId, props);
+ }
+ for (const instance of state.instances.values()) {
+ if (isInScope(instance.id) === false) {
+ continue;
+ }
+ if (
+ instance.component !== "Link" &&
+ instance.tag !== "a" &&
+ instance.tag !== "area"
+ ) {
+ continue;
+ }
+ const props = propsByInstance.get(instance.id);
+ const target = props?.get("target");
+ if (
+ target?.type !== "string" ||
+ typeof target.value !== "string" ||
+ target.value.trim().toLocaleLowerCase() !== "_blank"
+ ) {
+ continue;
+ }
+ const rel = props?.get("rel");
+ const relTokens =
+ rel?.type === "string" && typeof rel.value === "string"
+ ? new Set(rel.value.toLocaleLowerCase().split(/\s+/))
+ : new Set<string>();
+ if (relTokens.has("noopener") || relTokens.has("noreferrer")) {
+ continue;
+ }
+ matches.push({
+ kind: "security",
+ issue: "target-blank-without-noopener",
+ instanceId: instance.id,
+ component: instance.component,
+ tag: instance.tag,
+ message:
+ 'Link opens a new tab without rel="noopener" or rel="noreferrer".',
+ });
+ }
+ }
+
+ if (scopes.has("seo")) {
+ const codePropsByInstance = new Map(
+ Array.from(state.props.values(), (prop) => [
+ `${prop.instanceId}:${prop.name}`,
+ prop,
+ ])
+ );
+ for (const instance of state.instances.values()) {
+ if (instance.component !== "JsonLd" || isInScope(instance.id) === false) {
+ continue;
+ }
+ const codeProp = codePropsByInstance.get(`${instance.id}:code`);
+ if (codeProp !== undefined && isDynamicPropType(codeProp.type)) {
+ continue;
+ }
+ const validation = validateJsonLdWithSchemaOrg(codeProp?.value);
+ const structuralError = validation.diagnostics.find(
+ ({ severity }) => severity === "error"
+ );
+ if (validation.success === false || structuralError !== undefined) {
+ matches.push({
+ kind: "seo",
+ issue: "invalid-json-ld",
+ instanceId: instance.id,
+ propName: "code",
+ jsonLdPath: structuralError?.path ?? "$",
+ message:
+ structuralError?.message ??
+ "JSON-LD code is not a valid JSON object or array.",
+ });
+ continue;
+ }
+ for (const diagnostic of validation.diagnostics) {
+ matches.push({
+ kind: "seo",
+ issue: diagnostic.code,
+ instanceId: instance.id,
+ propName: "code",
+ jsonLdPath: diagnostic.path,
+ message: diagnostic.message,
+ });
+ }
+ if (hasTopLevelJsonLdContext(validation.value) === false) {
+ matches.push({
+ kind: "seo",
+ issue: "missing-json-ld-context",
+ instanceId: instance.id,
+ propName: "code",
+ message: "JSON-LD has no top-level @context.",
+ });
+ }
+ }
+
+ const pages = getPagesToAudit(state, input);
+ const pagesByTitle = new Map<
+ string,
+ Array<{ id: string; name: string; path: string; title: string }>
+ >();
+ const pagesByDescription = new Map<
+ string,
+ Array<{ id: string; name: string; path: string; description: string }>
+ >();
+ const selectedPageIds = new Set(pages.map((page) => page.id));
+ for (const page of pages) {
+ for (const customMeta of page.meta.custom ?? []) {
+ if (customMeta.property.toLocaleLowerCase().includes("ld+json")) {
+ matches.push({
+ kind: "seo",
+ issue: "json-ld-in-custom-metadata",
+ pageId: page.id,
+ pagePath: page.path,
+ pageName: page.name,
+ property: customMeta.property,
+ message: `${JSON.stringify(customMeta.property)} custom metadata does not create a JSON-LD script.`,
+ });
+ }
+ }
+ if (page.meta.description === undefined) {
+ matches.push({
+ kind: "seo",
+ issue: "missing-page-description",
+ pageId: page.id,
+ pagePath: page.path,
+ pageName: page.name,
+ message: "Page has no meta description.",
+ });
+ }
+ const description =
+ page.meta.description === undefined
+ ? undefined
+ : getStaticString(page.meta.description);
+ if (description !== undefined && description.trim().length === 0) {
+ matches.push({
+ kind: "seo",
+ issue: "empty-page-description",
+ pageId: page.id,
+ pagePath: page.path,
+ pageName: page.name,
+ message: "Page has an empty meta description.",
+ });
+ }
+ const language =
+ page.meta.language === undefined
+ ? undefined
+ : getStaticString(page.meta.language);
+ if (
+ language !== undefined &&
+ language.trim().length > 0 &&
+ bcp47.parse(language).language === null
+ ) {
+ matches.push({
+ kind: "seo",
+ issue: "invalid-page-language",
+ pageId: page.id,
+ pagePath: page.path,
+ pageName: page.name,
+ language,
+ message: `Page language ${JSON.stringify(language)} is not a valid BCP-47 language tag.`,
+ });
+ }
+ const socialImageAssetId = page.meta.socialImageAssetId;
+ if (
+ socialImageAssetId !== undefined &&
+ state.assets.has(socialImageAssetId) === false
+ ) {
+ matches.push({
+ kind: "seo",
+ issue: "missing-social-image-asset",
+ pageId: page.id,
+ pagePath: page.path,
+ pageName: page.name,
+ assetId: socialImageAssetId,
+ message: "Page social image references an asset that does not exist.",
+ });
+ }
+ const title = getStaticString(page.title);
+ if (title !== undefined) {
+ const normalizedTitle = title.trim().toLocaleLowerCase();
+ if (normalizedTitle.length === 0) {
+ matches.push({
+ kind: "seo",
+ issue: "empty-page-title",
+ pageId: page.id,
+ pagePath: page.path,
+ pageName: page.name,
+ message: "Page has an empty title.",
+ });
+ }
+ }
+ }
+ for (const page of getPagesToAudit(state, {})) {
+ const title = getStaticString(page.title);
+ if (title !== undefined && title.trim().length > 0) {
+ const key = title.trim().toLocaleLowerCase();
+ const matchingPages = pagesByTitle.get(key) ?? [];
+ matchingPages.push({
+ id: page.id,
+ name: page.name,
+ path: page.path,
+ title,
+ });
+ pagesByTitle.set(key, matchingPages);
+ }
+ const description =
+ page.meta.description === undefined
+ ? undefined
+ : getStaticString(page.meta.description);
+ if (description !== undefined && description.trim().length > 0) {
+ const key = description.trim().toLocaleLowerCase();
+ const matchingPages = pagesByDescription.get(key) ?? [];
+ matchingPages.push({
+ id: page.id,
+ name: page.name,
+ path: page.path,
+ description,
+ });
+ pagesByDescription.set(key, matchingPages);
+ }
+ }
+ for (const matchingPages of pagesByTitle.values()) {
+ if (
+ matchingPages.length < 2 ||
+ matchingPages.some((page) => selectedPageIds.has(page.id)) === false
+ ) {
+ continue;
+ }
+ matches.push({
+ kind: "seo",
+ issue: "duplicate-page-title",
+ title: matchingPages[0].title,
+ pageIds: matchingPages.map((page) => page.id),
+ pagePaths: matchingPages.map((page) => page.path),
+ message: `Pages share the static title ${JSON.stringify(matchingPages[0].title)}.`,
+ });
+ }
+ for (const matchingPages of pagesByDescription.values()) {
+ if (
+ matchingPages.length < 2 ||
+ matchingPages.some((page) => selectedPageIds.has(page.id)) === false
+ ) {
+ continue;
+ }
+ matches.push({
+ kind: "seo",
+ issue: "duplicate-page-description",
+ description: matchingPages[0].description,
+ pageIds: matchingPages.map((page) => page.id),
+ pagePaths: matchingPages.map((page) => page.path),
+ message: `Pages share the static meta description ${JSON.stringify(matchingPages[0].description)}.`,
+ });
+ }
+ }
+
+ const limit = input.limit ?? 50;
+ return {
+ query: input.query,
+ scopes: [...scopes],
+ total: matches.length,
+ truncated: matches.length > limit,
+ matches: matches.slice(0, limit),
+ };
+};
+
+export const searchProject = (
+ state: Parameters<typeof analyzeProject>[0],
+ input: z.infer<typeof projectSearchInput>
+) => analyzeProject(state, input);
diff --git a/packages/project-build/src/runtime/styles.test.ts b/packages/project-build/src/runtime/styles.test.ts
index 64f69c9ec3..6256ab6678 100644
--- a/packages/project-build/src/runtime/styles.test.ts
+++ b/packages/project-build/src/runtime/styles.test.ts
@@ -1557,7 +1557,7 @@ describe("runtime style operations", () => {
});
describe("serializeDesignTokens", () => {
- test("filters, sorts, includes styles, and counts usage when requested", () => {
+ test("filters, sorts, summarizes styles, and counts usage when requested", () => {
expect(
serializeDesignTokens({
styleSources: sources([
@@ -1589,7 +1589,7 @@ describe("serializeDesignTokens", () => {
{
id: "primary",
name: "Primary",
- styles: { color: { type: "keyword", value: "red" } },
+ declarationCount: 1,
usageCount: 2,
},
],
@@ -1611,6 +1611,45 @@ describe("serializeDesignTokens", () => {
}).tokens.map((item) => item.id)
).toEqual(["secondary", "primary"]);
});
+
+ test("includes full token styles only when requested", () => {
+ expect(
+ serializeDesignTokens({
+ styleSources: sources([token("primary", "Primary")]),
+ styles: createStyleDeclMap([
+ createStyleDecl("primary", "base", "color", {
+ type: "keyword",
+ value: "red",
+ }),
+ ]),
+ styleSourceSelections: [],
+ includeStyles: true,
+ })
+ ).toEqual({
+ tokens: [
+ {
+ id: "primary",
+ name: "Primary",
+ declarationCount: 1,
+ styles: { color: { type: "keyword", value: "red" } },
+ usageCount: 0,
+ },
+ ],
+ });
+ });
+
+ test("includes usage by default and allows omitting it", () => {
+ const input = {
+ styleSources: sources([token("primary", "Primary")]),
+ styles: [],
+ styleSourceSelections: [{ instanceId: "box-1", values: ["primary"] }],
+ };
+ expect(serializeDesignTokens(input).tokens[0]?.usageCount).toBe(1);
+ expect(
+ serializeDesignTokens({ ...input, withUsage: false }).tokens[0]
+ ?.usageCount
+ ).toBeUndefined();
+ });
});
describe("getLocalStyleSourceId", () => {
diff --git a/packages/project-build/src/runtime/styles.ts b/packages/project-build/src/runtime/styles.ts
index 50976c1408..0eb0fa4ac6 100644
--- a/packages/project-build/src/runtime/styles.ts
+++ b/packages/project-build/src/runtime/styles.ts
@@ -40,6 +40,7 @@ export const serializeDesignTokens = ({
styleSourceSelections,
filter,
withUsage,
+ includeStyles,
sort,
}: {
styleSources: Iterable<StyleSource> | Map<string, StyleSource>;
@@ -49,9 +50,10 @@ export const serializeDesignTokens = ({
| Map<string, StyleSourceSelection>;
filter?: string;
withUsage?: boolean;
+ includeStyles?: boolean;
sort?: "name" | "usage";
}) => {
- const shouldCountUsage = withUsage === true || sort === "usage";
+ const shouldCountUsage = withUsage !== false || sort === "usage";
const styleDecls =
styles instanceof Map ? Array.from(styles.values()) : Array.from(styles);
const selections =
@@ -68,10 +70,8 @@ export const serializeDesignTokens = ({
(styleSource) => filter === undefined || styleSource.name.includes(filter)
)
.map((styleSource) => {
- const tokenStyles = Object.fromEntries(
- styleDecls
- .filter((style) => style.styleSourceId === styleSource.id)
- .map((style) => [style.property, style.value])
+ const tokenDecls = styleDecls.filter(
+ (style) => style.styleSourceId === styleSource.id
);
const usageCount = selections.filter((selection) =>
selection.values.includes(styleSource.id)
@@ -79,7 +79,13 @@ export const serializeDesignTokens = ({
return {
id: styleSource.id,
name: styleSource.name,
- styles: tokenStyles,
+ declarationCount: tokenDecls.length,
+ styles:
+ includeStyles === true
+ ? Object.fromEntries(
+ tokenDecls.map((style) => [style.property, style.value])
+ )
+ : undefined,
usageCount: shouldCountUsage ? usageCount : undefined,
};
});
@@ -185,6 +191,7 @@ export const listDesignTokens = (
input: {
filter?: string;
withUsage?: boolean;
+ includeStyles?: boolean;
sort?: "name" | "usage";
} = {}
) => serializeDesignTokens({ ...getRequiredStyleState(state), ...input });
diff --git a/packages/project-build/src/runtime/text-replacement.ts b/packages/project-build/src/runtime/text-replacement.ts
new file mode 100644
index 0000000000..6a7919e74b
--- /dev/null
+++ b/packages/project-build/src/runtime/text-replacement.ts
@@ -0,0 +1,26 @@
+export type TextReplacementInput = {
+ find: string;
+ replace: string;
+ match: "exact" | "substring";
+};
+
+export const replaceTextValue = (value: string, input: TextReplacementInput) =>
+ input.match === "exact"
+ ? value === input.find
+ ? input.replace
+ : value
+ : value.replaceAll(input.find, input.replace);
+
+export const getStaticStringLiteral = (expression: string | undefined) => {
+ if (expression === undefined) {
+ return;
+ }
+ try {
+ const value = JSON.parse(expression);
+ return typeof value === "string" && JSON.stringify(value) === expression
+ ? value
+ : undefined;
+ } catch {
+ return;
+ }
+};
diff --git a/packages/project-build/src/schema.ts b/packages/project-build/src/schema.ts
index 1413751fe1..72952995eb 100644
--- a/packages/project-build/src/schema.ts
+++ b/packages/project-build/src/schema.ts
@@ -15,6 +15,14 @@ import {
} from "@webstudio-is/project-migrations/pages";
import { z } from "zod";
import type { Build } from "./types";
+import {
+ marketplaceProduct,
+ type MarketplaceProduct,
+} from "./shared/marketplace";
+import {
+ projectSettings,
+ type ProjectSettings,
+} from "./shared/project-settings";
const entry = <Value extends z.ZodTypeAny>(value: Value) =>
z.tuple([z.string(), value]);
@@ -23,8 +31,13 @@ type SchemaShape<Value extends object> = {
[Key in keyof Required<Value>]: z.ZodType<Value[Key], unknown>;
};
-export type SerializedBuild = Omit<Build, "marketplaceProduct" | "pages"> & {
+export type SerializedBuild = Omit<
+ Build,
+ "marketplaceProduct" | "pages" | "projectSettings"
+> & {
pages: SerializedPages;
+ marketplaceProduct?: MarketplaceProduct;
+ projectSettings?: ProjectSettings;
};
const serializedBuildShape = {
@@ -42,6 +55,8 @@ const serializedBuildShape = {
instances: z.array(entry(instance)),
dataSources: z.array(entry(dataSource)),
resources: z.array(entry(resource)),
+ marketplaceProduct: marketplaceProduct.optional(),
+ projectSettings: projectSettings.optional(),
deployment: deployment.optional(),
} satisfies SchemaShape<SerializedBuild>;
diff --git a/packages/project-build/src/shared/project-settings.ts b/packages/project-build/src/shared/project-settings.ts
new file mode 100644
index 0000000000..5dc2ec2e9c
--- /dev/null
+++ b/packages/project-build/src/shared/project-settings.ts
@@ -0,0 +1,32 @@
+import { compilerSettings, projectMeta, type Pages } from "@webstudio-is/sdk";
+import { z } from "zod";
+
+export const projectSettings = z.object({
+ meta: projectMeta,
+ compiler: compilerSettings,
+});
+
+export type ProjectSettings = z.infer<typeof projectSettings>;
+
+export const createProjectSettingsFromPages = (
+ pages: Pick<Pages, "meta" | "compiler">
+): ProjectSettings => ({
+ meta: structuredClone(pages.meta ?? {}),
+ compiler: structuredClone(pages.compiler ?? {}),
+});
+
+export const removeLegacyProjectSettingsFromPages = (pages: Pages) => {
+ pages.meta = undefined;
+ pages.compiler = undefined;
+ return pages;
+};
+
+export const removeAgentInstructionsFromProjectSettings = (
+ settings: ProjectSettings
+): ProjectSettings => {
+ const { agentInstructions: _agentInstructions, ...meta } = settings.meta;
+ return {
+ ...settings,
+ meta,
+ };
+};
diff --git a/packages/project-build/src/shared/type-utils.ts b/packages/project-build/src/shared/type-utils.ts
new file mode 100644
index 0000000000..e2a6131b5d
--- /dev/null
+++ b/packages/project-build/src/shared/type-utils.ts
@@ -0,0 +1,7 @@
+export const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null;
+
+export const isPlainRecord = (
+ value: unknown
+): value is Record<string, unknown> =>
+ isRecord(value) && Array.isArray(value) === false;
diff --git a/packages/project-build/src/state/adapters.test.ts b/packages/project-build/src/state/adapters.test.ts
index cb1290b26c..44875a09ff 100644
--- a/packages/project-build/src/state/adapters.test.ts
+++ b/packages/project-build/src/state/adapters.test.ts
@@ -21,6 +21,10 @@ test("adapts snapshots without sharing mutable maps", () => {
expect(state.pages).not.toBe(pages);
expect(state.pages?.pages).not.toBe(pages.pages);
expect(state.pages?.folders).not.toBe(pages.folders);
+ expect(state.projectSettings).toEqual({
+ meta: pages.meta ?? {},
+ compiler: pages.compiler ?? {},
+ });
expect(state.instances).toEqual(new Map(build.instances));
expect(state.instances).not.toBe(build.instances);
expect(state.instances?.get("instance-root")).not.toBe(
@@ -58,6 +62,22 @@ test("adapts serialized snapshots with migrated pages", () => {
expect(state.pages?.pages).toEqual(pages.pages);
expect(state.pages?.folders).toEqual(pages.folders);
expect(state.props).toEqual(new Map(build.props));
+ expect(state.projectSettings?.meta).toEqual(pages.meta ?? {});
+});
+
+test("prefers the first-class project settings namespace over legacy pages metadata", () => {
+ const state = createBuilderStateFromSnapshot({
+ pages,
+ projectSettings: {
+ meta: { agentInstructions: "Use components." },
+ compiler: { atomicStyles: false },
+ },
+ });
+
+ expect(state.projectSettings).toEqual({
+ meta: { agentInstructions: "Use components." },
+ compiler: { atomicStyles: false },
+ });
});
test("adapts array build data snapshots into normalized builder state", () => {
diff --git a/packages/project-build/src/state/adapters.ts b/packages/project-build/src/state/adapters.ts
index 56126ce656..46c39c86a5 100644
--- a/packages/project-build/src/state/adapters.ts
+++ b/packages/project-build/src/state/adapters.ts
@@ -24,6 +24,11 @@ import {
type StyleSourceSelection,
} from "@webstudio-is/sdk";
import type { MarketplaceProduct } from "../shared/marketplace";
+import {
+ createProjectSettingsFromPages,
+ removeLegacyProjectSettingsFromPages,
+ type ProjectSettings,
+} from "../shared/project-settings";
import type { CompactBuild } from "../types";
type SnapshotValue<Namespace extends BuilderNamespace> =
@@ -54,6 +59,7 @@ export type BuilderBuildDataSnapshot = Partial<{
assets: Asset[];
breakpoints: Breakpoint[];
marketplaceProduct: MarketplaceProduct;
+ projectSettings: ProjectSettings;
}>;
export type BuilderCompactBuildDataSnapshot = Pick<
@@ -70,6 +76,7 @@ export type BuilderCompactBuildDataSnapshot = Pick<
| "marketplaceProduct"
> & {
assets?: Asset[];
+ projectSettings?: ProjectSettings;
};
export type BuilderStateStore<Namespace extends BuilderNamespace> = {
@@ -93,6 +100,14 @@ const cloneMap = <Key, Value>(map: Map<Key, Value>) => {
const mapEntriesById = <Item extends { id: string }>(items: Item[]) =>
items.map((item) => [item.id, item] as const);
+const normalizeProjectSettings = (state: BuilderState) => {
+ if (state.pages === undefined) {
+ return;
+ }
+ state.projectSettings ??= createProjectSettingsFromPages(state.pages);
+ removeLegacyProjectSettingsFromPages(state.pages);
+};
+
const setClonedBuilderStateValue = <Namespace extends BuilderNamespace>(
state: BuilderState,
namespace: Namespace,
@@ -102,8 +117,8 @@ const setClonedBuilderStateValue = <Namespace extends BuilderNamespace>(
state.pages = migratePages(serializePages(value as Pages));
return;
}
- if (namespace === "marketplaceProduct") {
- state.marketplaceProduct = structuredClone(value as MarketplaceProduct);
+ if (namespace === "marketplaceProduct" || namespace === "projectSettings") {
+ (state as Record<string, unknown>)[namespace] = structuredClone(value);
return;
}
(state as Record<string, unknown>)[namespace] = cloneMap(
@@ -120,8 +135,8 @@ const setClonedBuilderStateSnapshotValue = <Namespace extends BuilderNamespace>(
state.pages = migratePages(serializePages(value as Pages));
return;
}
- if (namespace === "marketplaceProduct") {
- state.marketplaceProduct = structuredClone(value as MarketplaceProduct);
+ if (namespace === "marketplaceProduct" || namespace === "projectSettings") {
+ (state as Record<string, unknown>)[namespace] = structuredClone(value);
return;
}
(state as Record<string, unknown>)[namespace] = cloneMapEntries(
@@ -142,6 +157,8 @@ export const createBuilderStateFromStores = (
}
}
+ normalizeProjectSettings(state);
+
return state;
};
@@ -161,6 +178,8 @@ export const createBuilderStateFromSnapshot = (
}
}
+ normalizeProjectSettings(state);
+
return state;
};
@@ -173,6 +192,7 @@ export const createBuilderStateFromSerializedSnapshot = (
if (pages !== undefined) {
setClonedBuilderStateValue(state, "pages", migratePages(pages));
}
+ normalizeProjectSettings(state);
return state;
};
@@ -220,6 +240,9 @@ export const createBuilderStateFromBuildData = (
if (build.marketplaceProduct !== undefined) {
snapshot.marketplaceProduct = build.marketplaceProduct;
}
+ if (build.projectSettings !== undefined) {
+ snapshot.projectSettings = build.projectSettings;
+ }
return createBuilderStateFromSnapshot(snapshot);
};
@@ -239,6 +262,8 @@ export const createBuilderStateFromCompactBuild = (
instances: build.instances,
assets: build.assets,
marketplaceProduct: build.marketplaceProduct,
+ projectSettings:
+ build.projectSettings ?? createProjectSettingsFromPages(build.pages),
});
export const createBuilderStateSnapshotFromState = (
@@ -251,7 +276,11 @@ export const createBuilderStateSnapshotFromState = (
if (value === undefined) {
continue;
}
- if (namespace === "pages" || namespace === "marketplaceProduct") {
+ if (
+ namespace === "pages" ||
+ namespace === "projectSettings" ||
+ namespace === "marketplaceProduct"
+ ) {
(snapshot as Record<string, unknown>)[namespace] = structuredClone(value);
continue;
}
diff --git a/packages/project-build/src/state/builder-state.ts b/packages/project-build/src/state/builder-state.ts
index 7636c341bd..c6f3436c9f 100644
--- a/packages/project-build/src/state/builder-state.ts
+++ b/packages/project-build/src/state/builder-state.ts
@@ -15,6 +15,7 @@ import {
type BuilderNamespace,
} from "../contracts/namespaces";
import type { MarketplaceProduct } from "../shared/marketplace";
+import type { ProjectSettings } from "../shared/project-settings";
export type BuilderStateValueByNamespace = {
pages: Pages;
@@ -27,6 +28,7 @@ export type BuilderStateValueByNamespace = {
resources: Resources;
assets: Assets;
breakpoints: Breakpoints;
+ projectSettings: ProjectSettings;
marketplaceProduct: MarketplaceProduct;
};
diff --git a/packages/project-build/src/state/fixtures.test-utils.ts b/packages/project-build/src/state/fixtures.test-utils.ts
index 07abd321dd..448c05e918 100644
--- a/packages/project-build/src/state/fixtures.test-utils.ts
+++ b/packages/project-build/src/state/fixtures.test-utils.ts
@@ -3,6 +3,8 @@ import type { BuilderStateSnapshot } from "./adapters";
export const pages = {
homePageId: "page-home",
rootFolderId: "folder-root",
+ meta: {},
+ compiler: {},
pages: new Map([
[
"page-home",
diff --git a/packages/project-build/src/state/freshness.test.ts b/packages/project-build/src/state/freshness.test.ts
index ad991a37ae..185d7f265e 100644
--- a/packages/project-build/src/state/freshness.test.ts
+++ b/packages/project-build/src/state/freshness.test.ts
@@ -75,3 +75,34 @@ test("does not share mutable missing freshness objects", () => {
const freshness = createBuilderStateFreshness({ state: {} });
expect(freshness.pages).not.toBe(freshness.instances);
});
+
+test("preserves namespace provenance through stale and invalidated states", () => {
+ const freshness = createBuilderStateFreshness({
+ state: { pages },
+ version: 3,
+ source: "remote",
+ loadedAt: "2026-07-10T12:00:00.000Z",
+ });
+
+ expect(freshness.pages).toEqual({
+ status: "fresh",
+ version: 3,
+ source: "remote",
+ loadedAt: "2026-07-10T12:00:00.000Z",
+ });
+ expect(markBuilderStateNamespacesStale(freshness, ["pages"]).pages).toEqual({
+ status: "stale",
+ version: 3,
+ source: "remote",
+ loadedAt: "2026-07-10T12:00:00.000Z",
+ });
+ expect(
+ markBuilderStateNamespacesInvalidated(freshness, ["pages"], "tx-1").pages
+ ).toEqual({
+ status: "invalidated",
+ version: 3,
+ source: "remote",
+ loadedAt: "2026-07-10T12:00:00.000Z",
+ invalidatedBy: "tx-1",
+ });
+});
diff --git a/packages/project-build/src/state/freshness.ts b/packages/project-build/src/state/freshness.ts
index e772766616..e6a59492d2 100644
--- a/packages/project-build/src/state/freshness.ts
+++ b/packages/project-build/src/state/freshness.ts
@@ -10,9 +10,13 @@ export type BuilderStateNamespaceStatus =
| "stale"
| "invalidated";
+export type BuilderStateNamespaceSource = "remote" | "local";
+
export type BuilderStateNamespaceFreshness = {
status: BuilderStateNamespaceStatus;
version?: number;
+ source?: BuilderStateNamespaceSource;
+ loadedAt?: string;
invalidatedBy?: string;
};
@@ -38,15 +42,23 @@ export const createBuilderStateFreshness = ({
staleNamespaces = [],
invalidatedNamespaces = [],
invalidatedBy,
+ source,
+ loadedAt,
}: {
state: BuilderState;
version?: number;
staleNamespaces?: readonly BuilderNamespace[];
invalidatedNamespaces?: readonly BuilderNamespace[];
invalidatedBy?: string;
+ source?: BuilderStateNamespaceSource;
+ loadedAt?: string;
}): BuilderStateFreshness => {
const stale = new Set(staleNamespaces);
const invalidated = new Set(invalidatedNamespaces);
+ const provenance = {
+ ...(source === undefined ? {} : { source }),
+ ...(loadedAt === undefined ? {} : { loadedAt }),
+ };
const freshness: BuilderStateFreshness = {};
for (const namespace of builderNamespaces) {
@@ -57,15 +69,15 @@ export const createBuilderStateFreshness = ({
if (invalidated.has(namespace)) {
freshness[namespace] =
invalidatedBy === undefined
- ? { status: "invalidated", version }
- : { status: "invalidated", version, invalidatedBy };
+ ? { status: "invalidated", version, ...provenance }
+ : { status: "invalidated", version, ...provenance, invalidatedBy };
continue;
}
if (stale.has(namespace)) {
- freshness[namespace] = { status: "stale", version };
+ freshness[namespace] = { status: "stale", version, ...provenance };
continue;
}
- freshness[namespace] = { status: "fresh", version };
+ freshness[namespace] = { status: "fresh", version, ...provenance };
}
return freshness;
@@ -91,7 +103,12 @@ export const markBuilderStateNamespacesStale = (
if (current.status === "missing") {
continue;
}
- next[namespace] = { status: "stale", version: current.version };
+ next[namespace] = {
+ status: "stale",
+ version: current.version,
+ ...(current.source === undefined ? {} : { source: current.source }),
+ ...(current.loadedAt === undefined ? {} : { loadedAt: current.loadedAt }),
+ };
}
return next;
};
@@ -107,14 +124,13 @@ export const markBuilderStateNamespacesInvalidated = (
if (current.status === "missing") {
continue;
}
- next[namespace] =
- invalidatedBy === undefined
- ? { status: "invalidated", version: current.version }
- : {
- status: "invalidated",
- version: current.version,
- invalidatedBy,
- };
+ next[namespace] = {
+ status: "invalidated",
+ version: current.version,
+ ...(current.source === undefined ? {} : { source: current.source }),
+ ...(current.loadedAt === undefined ? {} : { loadedAt: current.loadedAt }),
+ ...(invalidatedBy === undefined ? {} : { invalidatedBy }),
+ };
}
return next;
};
diff --git a/packages/project-build/src/state/immer.ts b/packages/project-build/src/state/immer.ts
new file mode 100644
index 0000000000..74e6bbf254
--- /dev/null
+++ b/packages/project-build/src/state/immer.ts
@@ -0,0 +1,5 @@
+import { enableMapSet, enablePatches } from "immer";
+
+// Project data uses Map-backed namespaces and emits Immer patches.
+enableMapSet();
+enablePatches();
diff --git a/packages/project-build/src/state/patch.ts b/packages/project-build/src/state/patch.ts
index 980a941c20..79af9eaf4f 100644
--- a/packages/project-build/src/state/patch.ts
+++ b/packages/project-build/src/state/patch.ts
@@ -1,4 +1,5 @@
-import { applyPatches, enableMapSet, enablePatches, type Patch } from "immer";
+import { applyPatches, type Patch } from "immer";
+import "./immer";
import type {
BuilderPatch,
BuilderPatchChange,
@@ -8,10 +9,6 @@ import { compactBuilderPatchPayload } from "../contracts/patch";
import type { BuilderState } from "./builder-state";
import type { BuilderNamespace } from "../contracts/namespaces";
-// Runtime patch application uses Immer patches against Map-backed namespaces.
-enableMapSet();
-enablePatches();
-
export class MissingBuilderStateNamespaceError extends Error {
constructor(namespace: BuilderNamespace) {
super(`Builder state namespace "${namespace}" is missing.`);
diff --git a/packages/project-build/src/types.ts b/packages/project-build/src/types.ts
index a5a9a4e1e4..fe538e4413 100644
--- a/packages/project-build/src/types.ts
+++ b/packages/project-build/src/types.ts
@@ -12,6 +12,7 @@ import type {
StyleSourceSelection,
} from "@webstudio-is/sdk";
import type { MarketplaceProduct } from "./shared/marketplace";
+import type { ProjectSettings } from "./shared/project-settings";
export type Build = {
id: string;
@@ -29,7 +30,8 @@ export type Build = {
dataSources: [DataSource["id"], DataSource][];
resources: [Resource["id"], Resource][];
deployment?: Deployment | undefined;
- marketplaceProduct: MarketplaceProduct;
+ marketplaceProduct?: MarketplaceProduct;
+ projectSettings: ProjectSettings;
};
export type CompactBuild = {
@@ -48,5 +50,6 @@ export type CompactBuild = {
resources: Resource[];
instances: Instance[];
deployment?: Deployment;
- marketplaceProduct: MarketplaceProduct;
+ marketplaceProduct?: MarketplaceProduct;
+ projectSettings: ProjectSettings;
};
diff --git a/packages/project-build/src/visual/screenshot-diff.test.ts b/packages/project-build/src/visual/screenshot-diff.test.ts
index a8b6a72786..08cfdf1be2 100644
--- a/packages/project-build/src/visual/screenshot-diff.test.ts
+++ b/packages/project-build/src/visual/screenshot-diff.test.ts
@@ -2,7 +2,11 @@ import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, beforeEach, expect, test } from "vitest";
-import { diffPngFiles } from "./screenshot-diff";
+import {
+ createScreenshotTextAssertions,
+ createScreenshotVisualAssertions,
+ diffPngFiles,
+} from "./screenshot-diff";
import { createPng, paintRect, writePng } from "./screenshot.test-utils";
let tempDir: string;
@@ -15,6 +19,91 @@ afterEach(async () => {
await rm(tempDir, { recursive: true, force: true });
});
+test("reports pass/fail expected text assertions from OCR text", () => {
+ expect(
+ createScreenshotTextAssertions(
+ {
+ status: "ok",
+ provider: "tesseract",
+ changes: [],
+ observedText: ["Pricing plans for teams", "Start free"],
+ },
+ ["pricing plans", "Contact sales"]
+ )
+ ).toEqual({
+ passed: false,
+ status: "ok",
+ found: ["Pricing plans for teams", "Start free"],
+ missing: ["Contact sales"],
+ assertions: [
+ {
+ expected: "pricing plans",
+ passed: true,
+ found: ["Pricing plans for teams"],
+ },
+ {
+ expected: "Contact sales",
+ passed: false,
+ found: [],
+ },
+ ],
+ });
+});
+
+test("reports pass/fail visual assertions from diff metrics", () => {
+ expect(
+ createScreenshotVisualAssertions(
+ {
+ mismatchPercentage: 3.5,
+ changedRegionCount: 2,
+ dimensionMismatch: false,
+ overallColorChange: {
+ delta: { r: 0, g: -10, b: 0 },
+ dominantChange: {
+ channel: "green",
+ direction: "decrease",
+ magnitude: 10,
+ },
+ },
+ },
+ {
+ maxMismatchPercentage: 2,
+ minChangedRegions: 1,
+ maxChangedRegions: 2,
+ dominantColorChange: {
+ channel: "green",
+ direction: "decrease",
+ minMagnitude: 5,
+ },
+ }
+ )
+ ).toEqual({
+ passed: false,
+ assertions: [
+ {
+ expected: "mismatchPercentage <= 2",
+ actual: 3.5,
+ passed: false,
+ },
+ {
+ expected: "changedRegionCount >= 1",
+ actual: 2,
+ passed: true,
+ },
+ {
+ expected: "changedRegionCount <= 2",
+ actual: 2,
+ passed: true,
+ },
+ {
+ expected: "dominantColorChange=green:decrease magnitude>=5",
+ actual: "green:decrease magnitude=10",
+ passed: true,
+ },
+ ],
+ });
+});
+
test("detects pixel differences, regions, color deltas, and writes artifacts", async () => {
const baselinePath = path.join(tempDir, "baseline.png");
const currentPath = path.join(tempDir, "current.png");
@@ -50,6 +139,14 @@ test("detects pixel differences, regions, color deltas, and writes artifacts", a
}),
}),
]);
+ expect(result.overallColorChange).toEqual({
+ delta: { r: -255, g: -255, b: -255 },
+ dominantChange: {
+ channel: "luminance",
+ direction: "decrease",
+ magnitude: 255,
+ },
+ });
expect(result.summary).toContain("status: changed");
expect(result.summary).toContain("pixel_mismatch: 6.00%");
expect(result.summary).toContain("Region 1");
@@ -91,6 +188,8 @@ test("reports dimension mismatch for different aspect ratios", async () => {
baselinePath,
currentPath,
outputDir: path.join(tempDir, "diff"),
+ expectedText: ["Pricing"],
+ expectedVisual: { maxMismatchPercentage: 0 },
});
expect(result.dimensionMismatch).toEqual({
@@ -100,7 +199,14 @@ test("reports dimension mismatch for different aspect ratios", async () => {
expect(result.diffPath).toBeUndefined();
expect(result.regions).toEqual([]);
expect(result.textAnalysis.status).toBe("skipped");
+ expect(result.textAssertions).toMatchObject({
+ passed: false,
+ missing: ["Pricing"],
+ });
expect(result.summary).toContain("status: dimension_mismatch");
+ expect(result.summary).toContain("Text Assertions:");
+ expect(result.visualAssertions).toMatchObject({ passed: false });
+ expect(result.summary).toContain("Visual Assertions:");
});
test("can ignore a normalized top band", async () => {
diff --git a/packages/project-build/src/visual/screenshot-diff.ts b/packages/project-build/src/visual/screenshot-diff.ts
index 4a4380303c..0a2fef85ab 100644
--- a/packages/project-build/src/visual/screenshot-diff.ts
+++ b/packages/project-build/src/visual/screenshot-diff.ts
@@ -50,6 +50,11 @@ export type ScreenshotDiffRegion = {
};
};
+export type ScreenshotDiffOverallColorChange = {
+ delta: ScreenshotDiffRgb;
+ dominantChange: ScreenshotDiffDominantColorChange;
+};
+
export type ScreenshotDiffResult = {
totalPixels: number;
differentPixels: number;
@@ -63,10 +68,49 @@ export type ScreenshotDiffResult = {
actual: ScreenshotDiffSize;
};
regions: ScreenshotDiffRegion[];
+ overallColorChange?: ScreenshotDiffOverallColorChange;
textAnalysis: ScreenshotTextAnalysis;
+ textAssertions?: ScreenshotTextAssertionResult;
+ visualAssertions?: ScreenshotVisualAssertionResult;
warnings: readonly string[];
};
+export type ScreenshotTextAssertion = {
+ expected: string;
+ passed: boolean;
+ found: readonly string[];
+};
+
+export type ScreenshotTextAssertionResult = {
+ passed: boolean;
+ status: ScreenshotTextAnalysis["status"];
+ found: readonly string[];
+ missing: readonly string[];
+ assertions: readonly ScreenshotTextAssertion[];
+};
+
+export type ScreenshotVisualExpectation = {
+ maxMismatchPercentage?: number;
+ minChangedRegions?: number;
+ maxChangedRegions?: number;
+ dominantColorChange?: {
+ channel: Exclude<ScreenshotDiffDominantColorChange["channel"], "none">;
+ direction: Exclude<ScreenshotDiffDominantColorChange["direction"], "none">;
+ minMagnitude?: number;
+ };
+};
+
+export type ScreenshotVisualAssertion = {
+ expected: string;
+ actual: number | string;
+ passed: boolean;
+};
+
+export type ScreenshotVisualAssertionResult = {
+ passed: boolean;
+ assertions: readonly ScreenshotVisualAssertion[];
+};
+
type ChangeRegion = {
minX: number;
minY: number;
@@ -106,12 +150,16 @@ export const diffPngFiles = async ({
outputDir,
threshold = DEFAULT_THRESHOLD,
ignoreTopNormalizedY = DEFAULT_IGNORE_TOP_NORMALIZED_Y,
+ expectedText,
+ expectedVisual,
}: {
baselinePath: string;
currentPath: string;
outputDir: string;
threshold?: number;
ignoreTopNormalizedY?: number;
+ expectedText?: readonly string[];
+ expectedVisual?: ScreenshotVisualExpectation;
}): Promise<ScreenshotDiffResult> => {
const [decodedBaseline, decodedCurrent] = await Promise.all([
decodePngFile(baselinePath),
@@ -140,6 +188,28 @@ export const diffPngFiles = async ({
provider: "tesseract",
changes: [],
},
+ textAssertions:
+ expectedText === undefined
+ ? undefined
+ : createScreenshotTextAssertions(
+ {
+ status: "skipped",
+ provider: "tesseract",
+ changes: [],
+ },
+ expectedText
+ ),
+ visualAssertions:
+ expectedVisual === undefined
+ ? undefined
+ : createScreenshotVisualAssertions(
+ {
+ mismatchPercentage: 0,
+ changedRegionCount: 0,
+ dimensionMismatch: true,
+ },
+ expectedVisual
+ ),
warnings: ["dimension_mismatch"],
});
}
@@ -158,6 +228,11 @@ export const diffPngFiles = async ({
current,
joinGapPixels: DEFAULT_REGION_MERGE_DISTANCE,
});
+ const overallColorChange = getOverallColorChange({
+ mask: pixelDiff.mask,
+ baseline,
+ current,
+ });
const totalPixels = baseline.width * baseline.height;
const artifactPaths = getDiffArtifactPaths({ currentPath, outputDir });
await writeDiffArtifacts({
@@ -179,6 +254,7 @@ export const diffPngFiles = async ({
baselineImage: baseline,
currentImage: current,
ignoreTopPixels: Math.ceil(baseline.height * ignoreTopNormalizedY),
+ includeObservedText: expectedText !== undefined,
})
: createSkippedTextAnalysis();
@@ -191,11 +267,134 @@ export const diffPngFiles = async ({
diffPath: artifactPaths.diffPath,
contextDiffPath: artifactPaths.contextDiffPath,
regions,
+ overallColorChange,
textAnalysis,
+ textAssertions:
+ expectedText === undefined
+ ? undefined
+ : createScreenshotTextAssertions(textAnalysis, expectedText),
+ visualAssertions:
+ expectedVisual === undefined
+ ? undefined
+ : createScreenshotVisualAssertions(
+ {
+ mismatchPercentage:
+ totalPixels === 0
+ ? 0
+ : (pixelDiff.differentPixels / totalPixels) * 100,
+ changedRegionCount: regions.length,
+ dimensionMismatch: false,
+ overallColorChange,
+ },
+ expectedVisual
+ ),
warnings: getTextAnalysisWarnings({ canAnalyzeText, textAnalysis }),
});
};
+const normalizeAssertionText = (value: string) =>
+ value.trim().replace(/\s+/g, " ").toLocaleLowerCase();
+
+export const createScreenshotTextAssertions = (
+ textAnalysis: ScreenshotTextAnalysis,
+ expectedText: readonly string[]
+): ScreenshotTextAssertionResult => {
+ const found = textAnalysis.observedText ?? [];
+ const normalizedObserved = found.map(normalizeAssertionText);
+ const assertions = expectedText.map((expected) => {
+ const normalizedExpected = normalizeAssertionText(expected);
+ const matches = found.filter((_text, index) =>
+ normalizedObserved[index]?.includes(normalizedExpected)
+ );
+ return {
+ expected,
+ passed: textAnalysis.status === "ok" && matches.length > 0,
+ found: matches,
+ };
+ });
+ return {
+ passed: assertions.every((assertion) => assertion.passed),
+ status: textAnalysis.status,
+ found,
+ missing: assertions
+ .filter((assertion) => assertion.passed === false)
+ .map((assertion) => assertion.expected),
+ assertions,
+ };
+};
+
+export const createScreenshotVisualAssertions = (
+ {
+ mismatchPercentage,
+ changedRegionCount,
+ dimensionMismatch,
+ overallColorChange,
+ }: {
+ mismatchPercentage: number;
+ changedRegionCount: number;
+ dimensionMismatch: boolean;
+ overallColorChange?: ScreenshotDiffOverallColorChange;
+ },
+ expectedVisual: ScreenshotVisualExpectation
+): ScreenshotVisualAssertionResult => {
+ const assertions: ScreenshotVisualAssertion[] = [];
+ if (dimensionMismatch) {
+ assertions.push({
+ expected: "matching image dimensions",
+ actual: "dimension_mismatch",
+ passed: false,
+ });
+ }
+ if (expectedVisual.maxMismatchPercentage !== undefined) {
+ assertions.push({
+ expected: `mismatchPercentage <= ${expectedVisual.maxMismatchPercentage}`,
+ actual: mismatchPercentage,
+ passed:
+ dimensionMismatch === false &&
+ mismatchPercentage <= expectedVisual.maxMismatchPercentage,
+ });
+ }
+ if (expectedVisual.minChangedRegions !== undefined) {
+ assertions.push({
+ expected: `changedRegionCount >= ${expectedVisual.minChangedRegions}`,
+ actual: changedRegionCount,
+ passed:
+ dimensionMismatch === false &&
+ changedRegionCount >= expectedVisual.minChangedRegions,
+ });
+ }
+ if (expectedVisual.maxChangedRegions !== undefined) {
+ assertions.push({
+ expected: `changedRegionCount <= ${expectedVisual.maxChangedRegions}`,
+ actual: changedRegionCount,
+ passed:
+ dimensionMismatch === false &&
+ changedRegionCount <= expectedVisual.maxChangedRegions,
+ });
+ }
+ if (expectedVisual.dominantColorChange !== undefined) {
+ const actual = overallColorChange?.dominantChange ?? {
+ channel: "none" as const,
+ direction: "none" as const,
+ magnitude: 0,
+ };
+ const expected = expectedVisual.dominantColorChange;
+ assertions.push({
+ expected: `dominantColorChange=${expected.channel}:${expected.direction}${expected.minMagnitude === undefined ? "" : ` magnitude>=${expected.minMagnitude}`}`,
+ actual: `${actual.channel}:${actual.direction} magnitude=${actual.magnitude}`,
+ passed:
+ dimensionMismatch === false &&
+ actual.channel === expected.channel &&
+ actual.direction === expected.direction &&
+ actual.magnitude >= (expected.minMagnitude ?? 0),
+ });
+ }
+ return {
+ passed: assertions.every((assertion) => assertion.passed),
+ assertions,
+ };
+};
+
const getTextAnalysisWarnings = ({
canAnalyzeText,
textAnalysis,
@@ -594,6 +793,41 @@ const toDiffRegion = (region: ChangeRegion): ScreenshotDiffRegion => {
};
};
+const getOverallColorChange = ({
+ mask,
+ baseline,
+ current,
+}: {
+ mask: Uint8Array;
+ baseline: DecodedRgbaImage;
+ current: DecodedRgbaImage;
+}): ScreenshotDiffOverallColorChange | undefined => {
+ let pixelCount = 0;
+ const deltaSum = { r: 0, g: 0, b: 0 };
+ for (let pixelIndex = 0; pixelIndex < mask.length; pixelIndex++) {
+ if (mask[pixelIndex] === 0) {
+ continue;
+ }
+ const offset = pixelIndex * 4;
+ pixelCount += 1;
+ deltaSum.r += current.data[offset] - baseline.data[offset];
+ deltaSum.g += current.data[offset + 1] - baseline.data[offset + 1];
+ deltaSum.b += current.data[offset + 2] - baseline.data[offset + 2];
+ }
+ if (pixelCount === 0) {
+ return;
+ }
+ const delta = {
+ r: roundToOne(deltaSum.r / pixelCount),
+ g: roundToOne(deltaSum.g / pixelCount),
+ b: roundToOne(deltaSum.b / pixelCount),
+ };
+ return {
+ delta,
+ dominantChange: dominantChange(delta, roundToOne(luminance(delta))),
+ };
+};
+
const getDiffArtifactPaths = ({
currentPath,
outputDir,
@@ -801,6 +1035,23 @@ const formatScreenshotDiffSummary = (
`- Text ${index + 1}: ${change.kind} confidence=${formatNormalized(change.confidence)}${formatTextChange(change)}`
);
}
+ if (result.textAssertions !== undefined) {
+ lines.push("", "Text Assertions:");
+ lines.push(`- passed: ${result.textAssertions.passed}`);
+ lines.push(`- found: ${result.textAssertions.found.join(", ") || "none"}`);
+ lines.push(
+ `- missing: ${result.textAssertions.missing.join(", ") || "none"}`
+ );
+ }
+ if (result.visualAssertions !== undefined) {
+ lines.push("", "Visual Assertions:");
+ lines.push(`- passed: ${result.visualAssertions.passed}`);
+ for (const assertion of result.visualAssertions.assertions) {
+ lines.push(
+ `- ${assertion.passed ? "passed" : "failed"}: ${assertion.expected}; actual=${assertion.actual}`
+ );
+ }
+ }
if (result.warnings.length > 0) {
lines.push("", `Warnings: ${result.warnings.join(", ")}`);
}
diff --git a/packages/project-build/src/visual/screenshot-text-diff.test.ts b/packages/project-build/src/visual/screenshot-text-diff.test.ts
index 31a052c285..1e1545da72 100644
--- a/packages/project-build/src/visual/screenshot-text-diff.test.ts
+++ b/packages/project-build/src/visual/screenshot-text-diff.test.ts
@@ -96,6 +96,20 @@ test("detects appeared, disappeared, and changed text", () => {
]);
});
+test("excludes ignored top-band text from observed text assertions", () => {
+ const result = analyzeTextRegions({
+ baselineRegions: [],
+ currentRegions: [
+ textBlock({ text: "Browser chrome", x: 0, y: 0, height: 10 }),
+ textBlock({ text: "Page heading", x: 0, y: 20, height: 10 }),
+ ],
+ ignoreTopPixels: 10,
+ includeObservedText: true,
+ });
+
+ expect(result.observedText).toEqual(["Page heading"]);
+});
+
test("detects font-style geometry changes for matched text", () => {
const baseline = createPng(120, 60, { r: 255, g: 255, b: 255 });
const current = createPng(120, 60, { r: 255, g: 255, b: 255 });
diff --git a/packages/project-build/src/visual/screenshot-text-diff.ts b/packages/project-build/src/visual/screenshot-text-diff.ts
index 451d185fb1..a2759c143e 100644
--- a/packages/project-build/src/visual/screenshot-text-diff.ts
+++ b/packages/project-build/src/visual/screenshot-text-diff.ts
@@ -67,6 +67,7 @@ export type ScreenshotTextAnalysis = {
status: "ok" | "unavailable" | "skipped";
provider: "tesseract";
changes: readonly ScreenshotTextChange[];
+ observedText?: readonly string[];
};
type NormalizedTextRegion = OcrTextBlock & {
@@ -109,6 +110,7 @@ export const analyzeScreenshotTextChanges = async ({
currentImage,
ignoreTopPixels,
textChangeMinConfidence = DEFAULT_TEXT_CHANGE_MIN_CONFIDENCE,
+ includeObservedText = false,
}: {
baselinePath: string;
currentPath: string;
@@ -117,8 +119,9 @@ export const analyzeScreenshotTextChanges = async ({
currentImage: DecodedRgbaImage;
ignoreTopPixels: number;
textChangeMinConfidence?: number;
+ includeObservedText?: boolean;
}): Promise<ScreenshotTextAnalysis> => {
- if (hasPixelDiff === false) {
+ if (hasPixelDiff === false && includeObservedText === false) {
return {
status: "skipped",
provider: "tesseract",
@@ -138,14 +141,16 @@ export const analyzeScreenshotTextChanges = async ({
};
}
- return analyzeTextRegions({
+ const analysis = analyzeTextRegions({
baselineRegions: baselineOcr.blocks,
currentRegions: currentOcr.blocks,
baselineImage,
currentImage,
ignoreTopPixels,
textChangeMinConfidence,
+ includeObservedText,
});
+ return analysis;
};
export const analyzeTextRegions = ({
@@ -155,6 +160,7 @@ export const analyzeTextRegions = ({
currentImage,
ignoreTopPixels = 0,
textChangeMinConfidence = DEFAULT_TEXT_CHANGE_MIN_CONFIDENCE,
+ includeObservedText = false,
}: {
baselineRegions: readonly OcrTextBlock[];
currentRegions: readonly OcrTextBlock[];
@@ -162,6 +168,7 @@ export const analyzeTextRegions = ({
currentImage?: DecodedRgbaImage;
ignoreTopPixels?: number;
textChangeMinConfidence?: number;
+ includeObservedText?: boolean;
}): ScreenshotTextAnalysis => {
validateTextChangeMinConfidence(textChangeMinConfidence);
@@ -306,6 +313,9 @@ export const analyzeTextRegions = ({
changeLeft(left) - changeLeft(right)
)
.slice(0, MAX_TEXT_CHANGES),
+ ...(includeObservedText
+ ? { observedText: current.map((region) => region.text) }
+ : {}),
};
};
diff --git a/packages/project-build/tsconfig.json b/packages/project-build/tsconfig.json
index 0c8d2e7907..b32e8ee3c9 100644
--- a/packages/project-build/tsconfig.json
+++ b/packages/project-build/tsconfig.json
@@ -1,4 +1,7 @@
{
"extends": "@webstudio-is/tsconfig/base.json",
- "include": ["**/*.ts", "**/*.tsx", "../../@types/**/*.d.ts"]
+ "include": ["**/*.ts", "**/*.tsx", "../../@types/**/*.d.ts"],
+ "compilerOptions": {
+ "rootDir": "../.."
+ }
}
diff --git a/packages/project/src/db/build-patch-core.ts b/packages/project/src/db/build-patch-core.ts
index 825e704369..96b4cc1f12 100644
--- a/packages/project/src/db/build-patch-core.ts
+++ b/packages/project/src/db/build-patch-core.ts
@@ -29,6 +29,7 @@ import {
import {
findCycles,
type MarketplaceProduct,
+ type ProjectSettings,
marketplaceProduct,
parsePages,
serializePages,
@@ -179,6 +180,7 @@ export const createBuildPatchUpdate = async ({
styleSourceSelections?: StyleSourceSelections;
styles?: Styles;
marketplaceProduct?: MarketplaceProduct;
+ projectSettings?: ProjectSettings;
} = {};
let previewImageAssetId: string | null | undefined = undefined;
@@ -212,6 +214,19 @@ export const createBuildPatchUpdate = async ({
continue;
}
+ if (namespace === "projectSettings") {
+ const projectSettings =
+ buildData.projectSettings ??
+ parseConfig<ProjectSettings>(build.projectSettings);
+ const nextProjectSettings = applyBuildNamespacePatches(
+ "projectSettings",
+ projectSettings,
+ patches
+ );
+ buildData.projectSettings = nextProjectSettings;
+ continue;
+ }
+
if (namespace === "instances") {
addTouchedPatchKeys(touchedInstances, patches);
const instances =
@@ -414,6 +429,12 @@ export const createBuildPatchUpdate = async ({
);
}
+ if (buildData.projectSettings) {
+ update.projectSettings = serializeConfig<ProjectSettings>(
+ buildData.projectSettings
+ );
+ }
+
return {
status: "ok",
assetPatches,
diff --git a/packages/project/src/db/build-patch.test.ts b/packages/project/src/db/build-patch.test.ts
index 2e878afcac..8db0712f27 100644
--- a/packages/project/src/db/build-patch.test.ts
+++ b/packages/project/src/db/build-patch.test.ts
@@ -76,6 +76,7 @@ const buildRow = {
]),
deployment: null,
marketplaceProduct: JSON.stringify({}),
+ projectSettings: JSON.stringify({ meta: {}, compiler: {} }),
};
const transaction = (
@@ -297,6 +298,43 @@ describe("patchBuild", () => {
}
});
+ test("persists project settings without modifying pages storage", async () => {
+ const result = await createBuildPatchUpdate({
+ build: buildRow,
+ clientVersion: 3,
+ transactions: [
+ transaction({
+ payload: [
+ {
+ namespace: "projectSettings",
+ patches: [
+ {
+ op: "add",
+ path: ["meta", "agentInstructions"],
+ value: "Use existing components.",
+ },
+ ],
+ },
+ ],
+ }),
+ ],
+ });
+
+ expect(result.status).toBe("ok");
+ if (result.status === "ok") {
+ expect(result.update).toBeDefined();
+ if (result.update === undefined) {
+ throw new Error("Expected project settings update");
+ }
+ expect(result.update.pages).toBeUndefined();
+ expect(
+ JSON.parse(result.update.projectSettings as string).meta
+ ).toMatchObject({
+ agentInstructions: "Use existing components.",
+ });
+ }
+ });
+
test("validates only touched props while preserving untouched props", async () => {
const buildWithInvalidUntouchedProp = {
...buildRow,
diff --git a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
index 1781f00aa1..39f149126d 100644
--- a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
+++ b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
@@ -77,6 +77,7 @@ export const serverOnlyRouterOperationMetadata = {
"resources",
"variables",
"breakpoints",
+ "projectSettings",
"marketplaceProduct",
],
},
@@ -108,6 +109,7 @@ export const serverOnlyRouterOperationMetadata = {
"resources",
"assets",
"breakpoints",
+ "projectSettings",
"marketplaceProduct",
],
inputSchema: {
@@ -146,6 +148,7 @@ export const serverOnlyRouterOperationMetadata = {
"resources",
"assets",
"breakpoints",
+ "projectSettings",
"marketplaceProduct",
],
},
diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.ts
index 8b533a7060..7422a2844b 100644
--- a/packages/protocol/src/builder-api/operation-docs.ts
+++ b/packages/protocol/src/builder-api/operation-docs.ts
@@ -268,15 +268,39 @@ const curatedPublicApiOperationDocumentation = [
},
{
command: "list-instances",
- description: "List element instances in the build tree",
+ description:
+ "List element instances in the build tree, including parent id and index when known",
examples: ["webstudio list-instances --path / --max-depth 2 --json"],
},
{
command: "inspect-instance",
- description: "Show details for one element instance",
+ description:
+ "Show details for one element instance, optionally including ancestors",
requiredOptions: ["instance", "json"],
examples: [
- "webstudio inspect-instance --instance instance-id --include props,styles,children --json",
+ "webstudio inspect-instance --instance instance-id --include props,styles,children,ancestors --json",
+ ],
+ },
+ {
+ command: "search-project",
+ description:
+ "Search instance labels, text, props including href and embeds, resource URLs, assets, and styles",
+ examples: [
+ 'MCP tool: search-project {"query":"pricing"}',
+ 'MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}',
+ ],
+ },
+ {
+ command: "audit",
+ description:
+ "Audit project accessibility, security, SEO, assets, and styles with structured severity, evidence, remediation, skipped checks, and visual follow-ups",
+ examples: [
+ "webstudio audit --json",
+ "webstudio audit --scopes accessibility,seo --json",
+ "webstudio audit --scopes accessibility --verbose --json",
+ "webstudio audit --page-path /pricing --json",
+ 'MCP tool: audit {"severities":["error","warning"]}',
+ 'MCP tool: audit {"scopes":["accessibility"],"verbose":true}',
],
},
{
@@ -352,6 +376,30 @@ const curatedPublicApiOperationDocumentation = [
'webstudio update-text --instance instance-id --child-index 0 --text "user.name" --mode expression --json',
],
},
+ {
+ command: "replace-text",
+ description:
+ "Replace bounded literal text children across a page or project; use a separate command instead of an update-text replace mode",
+ examples: [
+ 'MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}',
+ ],
+ },
+ {
+ command: "replace-prop-text",
+ description:
+ "Replace bounded text inside static string props such as href and HTML embed code without changing dynamic bindings",
+ examples: [
+ 'MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}',
+ ],
+ },
+ {
+ command: "replace-resource-text",
+ description:
+ "Replace bounded resource names and fixed URLs without changing dynamic request expressions",
+ examples: [
+ 'MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}',
+ ],
+ },
{
command: "get-styles",
description: "List style declarations",
@@ -377,8 +425,12 @@ const curatedPublicApiOperationDocumentation = [
},
{
command: "list-design-tokens",
- description: "List reusable style tokens",
- examples: ["webstudio list-design-tokens --with-usage --json"],
+ description:
+ "List compact reusable style token summaries; include full styles only when explicitly requested",
+ examples: [
+ "webstudio list-design-tokens --with-usage --json",
+ "webstudio list-design-tokens --include-styles --json",
+ ],
},
{
command: "create-design-token",
@@ -592,6 +644,12 @@ const curatedPublicApiOperationDocumentation = [
description: "List project assets",
examples: ["webstudio list-assets --type image --with-usage --json"],
},
+ {
+ command: "list-fonts",
+ description:
+ "List uploaded font families and optional built-in system font stacks",
+ examples: ["webstudio list-fonts --json"],
+ },
{
command: "upload-asset",
description: "Upload one local asset file from an asset descriptor",
@@ -614,6 +672,14 @@ const curatedPublicApiOperationDocumentation = [
requiredOptions: ["asset", "json"],
examples: ["webstudio find-asset-usage --asset asset-id --json"],
},
+ {
+ command: "set-image-descriptions",
+ description:
+ "Save agent-generated image descriptions or mark images as decorative",
+ examples: [
+ 'MCP/API: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}',
+ ],
+ },
{
command: "replace-asset",
description: "Replace asset references and delete the old asset",
diff --git a/packages/protocol/src/builder-api/operations.test.ts b/packages/protocol/src/builder-api/operations.test.ts
index c3b8fb43d7..59731f15dc 100644
--- a/packages/protocol/src/builder-api/operations.test.ts
+++ b/packages/protocol/src/builder-api/operations.test.ts
@@ -142,6 +142,35 @@ describe("public api operation catalog", () => {
enum: ["text", "expression"],
description: expect.stringContaining('There is no "replace" mode.'),
});
+ const resourceInputSchema =
+ getPublicApiOperation("create-resource").inputSchema?.properties
+ ?.resource;
+ expect(resourceInputSchema).toEqual(
+ expect.objectContaining({ type: "object" })
+ );
+ if (
+ resourceInputSchema === undefined ||
+ typeof resourceInputSchema !== "object"
+ ) {
+ throw Error("Expected create-resource input schema object");
+ }
+ const headerValueSchema = (
+ resourceInputSchema.properties?.headers as
+ | { items?: { properties?: { value?: unknown } } }
+ | undefined
+ )?.items?.properties?.value;
+ expect(headerValueSchema).toMatchObject({
+ anyOf: [
+ { type: "string" },
+ {
+ type: "object",
+ properties: {
+ type: { const: "literal" },
+ value: { type: "string" },
+ },
+ },
+ ],
+ });
expect(
getPublicApiOperation("update-styles").inputSchema?.properties?.updates
).toMatchObject({
diff --git a/packages/protocol/src/builder-api/operations.ts b/packages/protocol/src/builder-api/operations.ts
index 6ab6803ca6..192b335700 100644
--- a/packages/protocol/src/builder-api/operations.ts
+++ b/packages/protocol/src/builder-api/operations.ts
@@ -41,6 +41,7 @@ export type PublicApiOperation<Command extends string = string> = Omit<
requiredInputFields: readonly string[];
inputFieldTypes: Partial<Record<string, "array">>;
inputSchema: InputJsonSchema;
+ outputSchema?: InputJsonSchema;
requiredOptions?: readonly string[];
examples: readonly string[];
localCapable: boolean;
@@ -96,6 +97,9 @@ const withDefaultPermit = <Operation extends PublicApiOperationInput>(
requiredInputFields,
inputFieldTypes,
inputSchema,
+ ...(runtimeOperation?.outputSchema === undefined
+ ? {}
+ : { outputSchema: runtimeOperation.outputSchema }),
requiredOptions:
"requiredOptions" in documentation
? documentation.requiredOptions
diff --git a/packages/protocol/src/builder-api/runtime-contracts.test.ts b/packages/protocol/src/builder-api/runtime-contracts.test.ts
index f17ed2c8cc..4f45f3d44d 100644
--- a/packages/protocol/src/builder-api/runtime-contracts.test.ts
+++ b/packages/protocol/src/builder-api/runtime-contracts.test.ts
@@ -11,38 +11,37 @@ import {
test("exposes public runtime contracts without private metadata", () => {
expect(publicRuntimeOperationContracts).toEqual(
- runtimeOperationContracts.map(
- ({
- id,
- command,
- client,
- permit,
- kind,
- inputSchema,
- readNamespaces,
- writeNamespaces,
- invalidatesNamespaces,
- retryOnConflict,
- requiresAssets,
- requiresConfirm,
- }) => ({
- id,
- command,
- client,
- permit,
- kind,
- inputSchema,
- readNamespaces,
- writeNamespaces,
- invalidatesNamespaces,
- retryOnConflict,
- requiresAssets,
- requiresConfirm,
- })
- )
+ runtimeOperationContracts.map((contract) => ({
+ id: contract.id,
+ command: contract.command,
+ client: contract.client,
+ permit: contract.permit,
+ kind: contract.kind,
+ inputSchema: contract.inputSchema,
+ ...("outputSchema" in contract
+ ? { outputSchema: contract.outputSchema }
+ : {}),
+ readNamespaces: contract.readNamespaces,
+ writeNamespaces: contract.writeNamespaces,
+ invalidatesNamespaces: contract.invalidatesNamespaces,
+ retryOnConflict: contract.retryOnConflict,
+ requiresAssets: contract.requiresAssets,
+ requiresConfirm: contract.requiresConfirm,
+ }))
);
});
+test("exposes the audit output schema and stable rule ids", () => {
+ const audit = publicRuntimeOperationContracts.find(
+ (contract) => contract.id === "project.audit"
+ );
+ expect(audit?.outputSchema).toBeDefined();
+ const outputSchema = JSON.stringify(audit?.outputSchema);
+ expect(outputSchema).toContain('"missing-aria-reference"');
+ expect(outputSchema).toContain('"contractVersion"');
+ expect(outputSchema).toContain('"const":1');
+});
+
test("exposes public operation namespaces from builder namespaces", () => {
expect(publicApiOperationNamespaces).toBe(builderNamespaces);
});
diff --git a/packages/protocol/src/builder-api/runtime-contracts.ts b/packages/protocol/src/builder-api/runtime-contracts.ts
index bda418f473..8e7d491b6b 100644
--- a/packages/protocol/src/builder-api/runtime-contracts.ts
+++ b/packages/protocol/src/builder-api/runtime-contracts.ts
@@ -23,6 +23,7 @@ export type PublicRuntimeOperationContract = {
permit?: PublicApiOperationPermit;
kind: PublicApiOperationKind;
inputSchema: InputJsonSchema;
+ outputSchema?: InputJsonSchema;
readNamespaces: readonly PublicApiOperationNamespace[];
writeNamespaces: readonly PublicApiOperationNamespace[];
invalidatesNamespaces: readonly PublicApiOperationNamespace[];
@@ -32,8 +33,8 @@ export type PublicRuntimeOperationContract = {
};
export const publicRuntimeOperationContracts: readonly PublicRuntimeOperationContract[] =
- runtimeOperationContracts.map(
- ({
+ runtimeOperationContracts.map((contract): PublicRuntimeOperationContract => {
+ const {
id,
command,
client,
@@ -46,18 +47,22 @@ export const publicRuntimeOperationContracts: readonly PublicRuntimeOperationCon
retryOnConflict,
requiresAssets,
requiresConfirm,
- }): PublicRuntimeOperationContract => ({
+ } = contract;
+ return {
id,
command,
client,
permit,
kind,
inputSchema,
+ ...("outputSchema" in contract
+ ? { outputSchema: contract.outputSchema }
+ : {}),
readNamespaces,
writeNamespaces,
invalidatesNamespaces,
retryOnConflict,
requiresAssets,
requiresConfirm,
- })
- );
+ };
+ });
diff --git a/packages/protocol/src/schema.test.ts b/packages/protocol/src/schema.test.ts
index a4ea2988c1..dd56b7fdbd 100644
--- a/packages/protocol/src/schema.test.ts
+++ b/packages/protocol/src/schema.test.ts
@@ -71,6 +71,27 @@ describe("project bundle contract", () => {
});
});
+ test("preserves build-versioned marketplace metadata", () => {
+ const marketplaceProduct = {
+ category: "pageTemplates" as const,
+ name: "Marketplace template",
+ thumbnailAssetId: "asset-1",
+ author: "Webstudio",
+ email: "[email protected]",
+ website: "https://example.com",
+ issues: "",
+ description: "A reusable marketplace template.",
+ };
+
+ expect(
+ publishedProjectBundle.parse(
+ createPublishedProjectBundleFixture({
+ build: { marketplaceProduct },
+ })
+ ).build.marketplaceProduct
+ ).toEqual(marketplaceProduct);
+ });
+
test("requires published project metadata", () => {
const data = createPublishedProjectBundleFixture();
delete (data as Partial<typeof data>).projectTitle;
diff --git a/packages/sdk-components-react/src/__generated__/create-link.props.ts b/packages/sdk-components-react/src/__generated__/create-link.props.ts
new file mode 100644
index 0000000000..6898f60c0e
--- /dev/null
+++ b/packages/sdk-components-react/src/__generated__/create-link.props.ts
@@ -0,0 +1,3 @@
+import type { PropMeta } from "@webstudio-is/sdk";
+
+export const props: Record<string, PropMeta> = {};
diff --git a/packages/sdk-components-react/src/__generated__/json-ld.props.ts b/packages/sdk-components-react/src/__generated__/json-ld.props.ts
new file mode 100644
index 0000000000..6898f60c0e
--- /dev/null
+++ b/packages/sdk-components-react/src/__generated__/json-ld.props.ts
@@ -0,0 +1,3 @@
+import type { PropMeta } from "@webstudio-is/sdk";
+
+export const props: Record<string, PropMeta> = {};
diff --git a/packages/sdk-components-react/src/__generated__/json-ld.stories.tsx b/packages/sdk-components-react/src/__generated__/json-ld.stories.tsx
new file mode 100644
index 0000000000..dc4633e8dc
--- /dev/null
+++ b/packages/sdk-components-react/src/__generated__/json-ld.stories.tsx
@@ -0,0 +1,39 @@
+import { Box as Box, JsonLd as JsonLd } from "../components";
+
+const Component = () => {
+ return (
+ <Box className={`w-box`}>
+ <JsonLd
+ code={
+ '{"@context":"https://schema.org","@type":"Organization","name":"Organization name"}'
+ }
+ />
+ </Box>
+ );
+};
+
+export default {
+ title: "Components/JsonLd",
+};
+
+const Story = {
+ render() {
+ return (
+ <>
+ <style>
+ {`
+@layer presets {
+ div.w-box {
+ box-sizing: border-box
+ }
+}
+
+ `}
+ </style>
+ <Component />
+ </>
+ );
+ },
+};
+
+export { Story as JsonLd };
diff --git a/packages/sdk-components-react/src/basic.template.tsx b/packages/sdk-components-react/src/basic.template.tsx
index 41e591b949..e7dbc209b4 100644
--- a/packages/sdk-components-react/src/basic.template.tsx
+++ b/packages/sdk-components-react/src/basic.template.tsx
@@ -85,6 +85,20 @@ export const HtmlEmbed: TemplateMeta = {
),
};
+export const JsonLd: TemplateMeta = {
+ category: "general",
+ order: 6,
+ template: (
+ <$.JsonLd
+ code={JSON.stringify({
+ "@context": "https://schema.org",
+ "@type": "Organization",
+ name: "Organization name",
+ })}
+ />
+ ),
+};
+
export const Image: TemplateMeta = {
category: "media",
template: (
diff --git a/packages/sdk-components-react/src/components.ts b/packages/sdk-components-react/src/components.ts
index 33596b54cf..8cad234121 100644
--- a/packages/sdk-components-react/src/components.ts
+++ b/packages/sdk-components-react/src/components.ts
@@ -42,4 +42,5 @@ export { HeadSlot } from "./head-slot";
export { HeadLink } from "./head-link";
export { HeadMeta } from "./head-meta";
export { HeadTitle } from "./head-title";
+export { JsonLd } from "./json-ld";
export { Video } from "./video";
diff --git a/packages/sdk-components-react/src/head-slot.ws.ts b/packages/sdk-components-react/src/head-slot.ws.ts
index f18aaa71c4..2de6e25338 100644
--- a/packages/sdk-components-react/src/head-slot.ws.ts
+++ b/packages/sdk-components-react/src/head-slot.ws.ts
@@ -7,7 +7,7 @@ export const meta: WsComponentMeta = {
description: "Inserts children into the head of the document",
contentModel: {
category: "instance",
- children: ["HeadLink", "HeadMeta", "HeadTitle"],
+ children: ["HeadLink", "HeadMeta", "HeadTitle", "JsonLd"],
},
props,
};
diff --git a/packages/sdk-components-react/src/json-ld.test.tsx b/packages/sdk-components-react/src/json-ld.test.tsx
new file mode 100644
index 0000000000..117d09f5c0
--- /dev/null
+++ b/packages/sdk-components-react/src/json-ld.test.tsx
@@ -0,0 +1,115 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { expect, test } from "vitest";
+import { build } from "esbuild";
+import { fileURLToPath } from "node:url";
+import { ReactSdkContext } from "@webstudio-is/react-sdk/runtime";
+import { JsonLd } from "./json-ld";
+
+test("renders safely serialized JSON-LD without a wrapper", () => {
+ const markup = renderToStaticMarkup(
+ <JsonLd
+ code={JSON.stringify({
+ "@context": "https://schema.org",
+ "@type": "Organization",
+ name: "Acme </script><script>unsafe()</script>",
+ })}
+ />
+ );
+
+ expect(markup).toContain('<script type="application/ld+json">');
+ expect(markup).toContain('"@type":"Organization"');
+ expect(markup).toContain("\\u003c/script>");
+ expect(markup).not.toContain("</script><script>unsafe()");
+ expect(markup.startsWith("<script")).toBe(true);
+});
+
+test("renders structured values produced by expression bindings", () => {
+ expect(
+ renderToStaticMarkup(
+ <JsonLd
+ code={{
+ "@context": "https://schema.org",
+ "@type": "Organization",
+ name: "Acme",
+ }}
+ />
+ )
+ ).toContain(
+ '{"@context":"https://schema.org","@type":"Organization","name":"Acme"}'
+ );
+});
+
+test.each(["", "not json", '"text"', "null", "1"])(
+ "omits invalid JSON-LD value %j from published output",
+ (code) => {
+ expect(renderToStaticMarkup(<JsonLd code={code} />)).toBe("");
+ }
+);
+
+test("omits structurally invalid JSON-LD from published output", () => {
+ expect(
+ renderToStaticMarkup(
+ <JsonLd code='{"@context":"https://schema.org","@type":1}' />
+ )
+ ).toBe("");
+});
+
+test("renders a real script element on canvas", () => {
+ const markup = renderToStaticMarkup(
+ <ReactSdkContext.Provider
+ value={{
+ assetBaseUrl: "",
+ imageLoader: ({ src }) => src,
+ renderer: "canvas",
+ resources: {},
+ breakpoints: [],
+ onError: console.error,
+ }}
+ >
+ <JsonLd code='{"a":1}' />
+ </ReactSdkContext.Provider>
+ );
+
+ expect(markup).toBe('<script type="application/ld+json">{"a":1}</script>');
+});
+
+test("keeps invalid canvas drafts inside the JSON-LD script element", () => {
+ const markup = renderToStaticMarkup(
+ <ReactSdkContext.Provider
+ value={{
+ assetBaseUrl: "",
+ imageLoader: ({ src }) => src,
+ renderer: "canvas",
+ resources: {},
+ breakpoints: [],
+ onError: console.error,
+ }}
+ >
+ <JsonLd code={'</script><script data-unsafe="true">unsafe()</script>'} />
+ </ReactSdkContext.Provider>
+ );
+
+ expect(markup).toContain("\\u003c/script>");
+ expect(markup).not.toContain("<script data-unsafe");
+ expect(markup.match(/<script/g)).toHaveLength(1);
+});
+
+test("keeps Schema.org vocabulary data out of the published component bundle", async () => {
+ const result = await build({
+ entryPoints: [fileURLToPath(new URL("./json-ld.tsx", import.meta.url))],
+ bundle: true,
+ write: false,
+ metafile: true,
+ format: "esm",
+ platform: "browser",
+ conditions: ["webstudio"],
+ external: ["react", "react/jsx-runtime", "@webstudio-is/react-sdk/runtime"],
+ });
+
+ expect(
+ Object.keys(result.metafile?.inputs ?? {}).some(
+ (path) =>
+ path.endsWith("/schema-org.ts") || path.endsWith("/schema-org-data.ts")
+ )
+ ).toBe(false);
+});
diff --git a/packages/sdk-components-react/src/json-ld.tsx b/packages/sdk-components-react/src/json-ld.tsx
new file mode 100644
index 0000000000..7788171a83
--- /dev/null
+++ b/packages/sdk-components-react/src/json-ld.tsx
@@ -0,0 +1,43 @@
+import { ReactSdkContext } from "@webstudio-is/react-sdk/runtime";
+import {
+ escapeJsonLdScriptText,
+ validateJsonLd,
+} from "@webstudio-is/sdk/runtime";
+import { forwardRef, type ElementRef, useContext } from "react";
+
+export const defaultTag = "script";
+
+const serializeJsonLd = (code: unknown) => {
+ const result = validateJsonLd(code);
+ if (result.success === false) {
+ return;
+ }
+ return escapeJsonLdScriptText(JSON.stringify(result.value));
+};
+
+export const JsonLd = forwardRef<ElementRef<"script">, { code?: unknown }>(
+ ({ code = "" }, ref) => {
+ const { renderer } = useContext(ReactSdkContext);
+ const serialized = serializeJsonLd(code);
+ const content =
+ renderer === undefined
+ ? serialized
+ : (serialized ??
+ (typeof code === "string"
+ ? escapeJsonLdScriptText(code)
+ : undefined));
+ if (content === undefined) {
+ return null;
+ }
+
+ return (
+ <script
+ ref={ref}
+ type="application/ld+json"
+ dangerouslySetInnerHTML={{ __html: content }}
+ />
+ );
+ }
+);
+
+JsonLd.displayName = "JsonLd";
diff --git a/packages/sdk-components-react/src/json-ld.ws.ts b/packages/sdk-components-react/src/json-ld.ws.ts
new file mode 100644
index 0000000000..2a26be9645
--- /dev/null
+++ b/packages/sdk-components-react/src/json-ld.ws.ts
@@ -0,0 +1,25 @@
+import { JsonLdIcon } from "@webstudio-is/icons/svg";
+import type { WsComponentMeta } from "@webstudio-is/sdk";
+import { props } from "./__generated__/json-ld.props";
+
+export const meta: WsComponentMeta = {
+ category: "general",
+ label: "JSON-LD",
+ description:
+ "Adds JSON-LD structured data from a JSON object or array. Prefer placing it inside Head Slot.",
+ icon: JsonLdIcon,
+ order: 6,
+ contentModel: {
+ category: "instance",
+ children: [],
+ },
+ initialProps: ["code"],
+ props: {
+ ...props,
+ code: {
+ required: true,
+ control: "json-code",
+ type: "string",
+ },
+ },
+};
diff --git a/packages/sdk-components-react/src/metas.ts b/packages/sdk-components-react/src/metas.ts
index 78ba385abe..be668a1781 100644
--- a/packages/sdk-components-react/src/metas.ts
+++ b/packages/sdk-components-react/src/metas.ts
@@ -42,4 +42,5 @@ export { meta as HeadSlot } from "./head-slot.ws";
export { meta as HeadLink } from "./head-link.ws";
export { meta as HeadMeta } from "./head-meta.ws";
export { meta as HeadTitle } from "./head-title.ws";
+export { meta as JsonLd } from "./json-ld.ws";
export { meta as Video } from "./video.ws";
diff --git a/packages/sdk/package.json b/packages/sdk/package.json
index e67aba8b86..a66b3d8d86 100644
--- a/packages/sdk/package.json
+++ b/packages/sdk/package.json
@@ -18,6 +18,11 @@
"types": "./lib/types/runtime.d.ts",
"import": "./lib/runtime.js"
},
+ "./schema-org": {
+ "webstudio": "./src/schema-org.ts",
+ "types": "./lib/types/schema-org.d.ts",
+ "import": "./lib/schema-org.js"
+ },
"./link-utils": {
"webstudio": "./src/link-utils.ts",
"types": "./lib/types/link-utils.d.ts",
@@ -50,8 +55,9 @@
"scripts": {
"typecheck": "tsc --noEmit -p tsconfig.typecheck.json",
"test": "vitest run",
+ "build:schema-org-data": "tsx scripts/schema-org-data.ts && oxfmt src/__generated__/schema-org-data.ts",
"build:normalize.css": "tsx --conditions=webstudio ./scripts/normalize.css.ts && oxfmt src/__generated__/normalize.css.ts",
- "build": "rm -rf lib && esbuild src/index.ts src/runtime.ts src/link-utils.ts src/schema.ts src/__generated__/normalize.css.ts src/core-templates.tsx --outdir=lib --bundle --format=esm --packages=external",
+ "build": "rm -rf lib && esbuild src/index.ts src/runtime.ts src/schema-org.ts src/link-utils.ts src/schema.ts src/__generated__/normalize.css.ts src/core-templates.tsx --outdir=lib --bundle --format=esm --packages=external",
"dts": "tsc --project tsconfig.dts.json"
},
"dependencies": {
@@ -74,6 +80,8 @@
"@webstudio-is/template": "workspace:*",
"@webstudio-is/tsconfig": "workspace:*",
"html-tags": "^4.0.0",
+ "papaparse": "^5.5.3",
+ "@types/papaparse": "^5.5.2",
"vitest": "^3.1.2"
}
}
diff --git a/packages/sdk/scripts/README.md b/packages/sdk/scripts/README.md
new file mode 100644
index 0000000000..d642f0d529
--- /dev/null
+++ b/packages/sdk/scripts/README.md
@@ -0,0 +1,17 @@
+# SDK generation scripts
+
+## Schema.org vocabulary
+
+Run `pnpm --filter @webstudio-is/sdk build:schema-org-data` to refresh
+`src/__generated__/schema-org-data.ts` from the pinned Schema.org release and
+checksummed HTTPS type and property CSV files. Upgrade the version and both
+checksums together after reviewing the generated vocabulary diff.
+
+The generated data contains vocabulary names, type inheritance, property
+domains and ranges, and superseded terms. Runtime validation deliberately
+treats vocabulary mismatches as warnings: Schema.org extensions and custom
+JSON-LD contexts remain valid. Structural JSON-LD errors are blocking.
+
+This validator does not guarantee eligibility for a search-engine rich result.
+Search engines maintain additional type-specific requirements and quality
+policies that should be checked against rendered or published pages.
diff --git a/packages/sdk/scripts/schema-org-data-lib.test.ts b/packages/sdk/scripts/schema-org-data-lib.test.ts
new file mode 100644
index 0000000000..5da0cf7b62
--- /dev/null
+++ b/packages/sdk/scripts/schema-org-data-lib.test.ts
@@ -0,0 +1,37 @@
+import { expect, test } from "vitest";
+import { createSchemaOrgData } from "./schema-org-data-lib";
+
+test("normalizes and deterministically sorts Schema.org CSV rows", () => {
+ const result = createSchemaOrgData({
+ typesCsv: [
+ "id,subTypeOf,supersededBy",
+ 'https://schema.org/äType,"https://schema.org/zParent, https://schema.org/AParent",',
+ "https://schema.org/AType,,https://schema.org/NewType",
+ ].join("\n"),
+ propertiesCsv: [
+ "id,domainIncludes,rangeIncludes,supersededBy",
+ 'https://schema.org/zProp,"https://schema.org/ZType, https://schema.org/AType",https://schema.org/Text,',
+ "https://schema.org/AProp,https://schema.org/Thing,https://schema.org/URL,https://schema.org/newProp",
+ ].join("\n"),
+ });
+
+ expect(result).toEqual({
+ typeRows: [
+ ["AType", [], "NewType"],
+ ["äType", ["AParent", "zParent"], ""],
+ ],
+ propertyRows: [
+ ["AProp", ["Thing"], ["URL"], "newProp"],
+ ["zProp", ["AType", "ZType"], ["Text"], ""],
+ ],
+ });
+});
+
+test("rejects malformed CSV input", () => {
+ expect(() =>
+ createSchemaOrgData({
+ typesCsv: 'id,subTypeOf\n"unterminated',
+ propertiesCsv: "id,domainIncludes,rangeIncludes,supersededBy",
+ })
+ ).toThrow("Unable to parse Schema.org types");
+});
diff --git a/packages/sdk/scripts/schema-org-data-lib.ts b/packages/sdk/scripts/schema-org-data-lib.ts
new file mode 100644
index 0000000000..2c8a002c0b
--- /dev/null
+++ b/packages/sdk/scripts/schema-org-data-lib.ts
@@ -0,0 +1,77 @@
+import Papa from "papaparse";
+
+const schemaOrgBase = "https://schema.org/";
+
+export type SchemaOrgTypeRow = readonly [
+ name: string,
+ parentTypes: readonly string[],
+ supersededBy: string,
+];
+
+export type SchemaOrgPropertyRow = readonly [
+ name: string,
+ domains: readonly string[],
+ ranges: readonly string[],
+ supersededBy: string,
+];
+
+const compareCodePoints = (left: string, right: string) =>
+ left < right ? -1 : left > right ? 1 : 0;
+
+const parseCsv = (name: string, csv: string) => {
+ const result = Papa.parse<Record<string, string>>(csv, {
+ header: true,
+ skipEmptyLines: true,
+ });
+ if (result.errors.length > 0) {
+ throw Error(
+ `Unable to parse Schema.org ${name}: ${result.errors[0].message}`
+ );
+ }
+ return result.data;
+};
+
+const term = (value: string) =>
+ value.startsWith(schemaOrgBase) ? value.slice(schemaOrgBase.length) : value;
+
+const terms = (value = "") =>
+ value
+ .split(",")
+ .map((item) => term(item.trim()))
+ .filter(Boolean)
+ .sort(compareCodePoints);
+
+export const createSchemaOrgData = ({
+ typesCsv,
+ propertiesCsv,
+}: {
+ typesCsv: string;
+ propertiesCsv: string;
+}) => {
+ const typeRows = parseCsv("types", typesCsv)
+ .map(
+ (row) =>
+ [
+ term(row.id),
+ terms(row.subTypeOf),
+ term(row.supersededBy ?? ""),
+ ] as const
+ )
+ .filter(([name]) => name !== "")
+ .sort(([left], [right]) => compareCodePoints(left, right));
+
+ const propertyRows = parseCsv("properties", propertiesCsv)
+ .map(
+ (row) =>
+ [
+ term(row.id),
+ terms(row.domainIncludes),
+ terms(row.rangeIncludes),
+ term(row.supersededBy ?? ""),
+ ] as const
+ )
+ .filter(([name]) => name !== "")
+ .sort(([left], [right]) => compareCodePoints(left, right));
+
+ return { typeRows, propertyRows };
+};
diff --git a/packages/sdk/scripts/schema-org-data.ts b/packages/sdk/scripts/schema-org-data.ts
new file mode 100644
index 0000000000..b308bfc512
--- /dev/null
+++ b/packages/sdk/scripts/schema-org-data.ts
@@ -0,0 +1,70 @@
+import { writeFile } from "node:fs/promises";
+import { createHash } from "node:crypto";
+import { fileURLToPath } from "node:url";
+import { createSchemaOrgData } from "./schema-org-data-lib";
+
+const schemaOrgBase = "https://schema.org/";
+const schemaOrgVersion = "30.0";
+const sourceBase = `${schemaOrgBase}version/${schemaOrgVersion}/schemaorg-current-https`;
+const sourceSha256 = {
+ types: "1ae97702e7bd9b91a90b78df5133b8897a0f025a6f94669491a55c0bf1867626",
+ properties:
+ "3a6319bd496d2d3dc276e3a8af9b0ff6415993e7d1f6b466072fcbdec1e0d257",
+} as const;
+
+const fetchCsv = async (name: "types" | "properties") => {
+ const response = await fetch(`${sourceBase}-${name}.csv`);
+ if (response.ok === false) {
+ throw Error(`Unable to download Schema.org ${name}: ${response.status}`);
+ }
+ const csv = await response.text();
+ const actualSha256 = createHash("sha256").update(csv).digest("hex");
+ if (actualSha256 !== sourceSha256[name]) {
+ throw Error(
+ `Schema.org ${name} checksum mismatch: expected ${sourceSha256[name]}, received ${actualSha256}`
+ );
+ }
+ return csv;
+};
+
+const [typesCsv, propertiesCsv] = await Promise.all([
+ fetchCsv("types"),
+ fetchCsv("properties"),
+]);
+const { typeRows, propertyRows } = createSchemaOrgData({
+ typesCsv,
+ propertiesCsv,
+});
+
+const output = `// Generated by pnpm --filter @webstudio-is/sdk build:schema-org-data. Do not edit manually.
+// Source: ${sourceBase}-{types,properties}.csv
+// SHA-256: types=${sourceSha256.types} properties=${sourceSha256.properties}
+
+export const schemaOrgDataVersion = ${JSON.stringify(schemaOrgVersion)};
+
+export const schemaOrgDataSourceSha256 = ${JSON.stringify(sourceSha256)} as const;
+
+export type SchemaOrgTypeRow = readonly [
+ name: string,
+ parentTypes: readonly string[],
+ supersededBy: string,
+];
+
+export type SchemaOrgPropertyRow = readonly [
+ name: string,
+ domains: readonly string[],
+ ranges: readonly string[],
+ supersededBy: string,
+];
+
+export const schemaOrgTypeRows: readonly SchemaOrgTypeRow[] = ${JSON.stringify(typeRows)};
+
+export const schemaOrgPropertyRows: readonly SchemaOrgPropertyRow[] = ${JSON.stringify(propertyRows)};
+`;
+
+await writeFile(
+ fileURLToPath(
+ new URL("../src/__generated__/schema-org-data.ts", import.meta.url)
+ ),
+ output
+);
diff --git a/packages/sdk/src/__generated__/schema-org-data.ts b/packages/sdk/src/__generated__/schema-org-data.ts
new file mode 100644
index 0000000000..deeb096136
--- /dev/null
+++ b/packages/sdk/src/__generated__/schema-org-data.ts
@@ -0,0 +1,5211 @@
+// Generated by pnpm --filter @webstudio-is/sdk build:schema-org-data. Do not edit manually.
+// Source: https://schema.org/version/30.0/schemaorg-current-https-{types,properties}.csv
+// SHA-256: types=1ae97702e7bd9b91a90b78df5133b8897a0f025a6f94669491a55c0bf1867626 properties=3a6319bd496d2d3dc276e3a8af9b0ff6415993e7d1f6b466072fcbdec1e0d257
+
+export const schemaOrgDataVersion = "30.0";
+
+export const schemaOrgDataSourceSha256 = {
+ types: "1ae97702e7bd9b91a90b78df5133b8897a0f025a6f94669491a55c0bf1867626",
+ properties:
+ "3a6319bd496d2d3dc276e3a8af9b0ff6415993e7d1f6b466072fcbdec1e0d257",
+} as const;
+
+export type SchemaOrgTypeRow = readonly [
+ name: string,
+ parentTypes: readonly string[],
+ supersededBy: string,
+];
+
+export type SchemaOrgPropertyRow = readonly [
+ name: string,
+ domains: readonly string[],
+ ranges: readonly string[],
+ supersededBy: string,
+];
+
+export const schemaOrgTypeRows: readonly SchemaOrgTypeRow[] = [
+ ["3DModel", ["MediaObject"], ""],
+ ["AMRadioChannel", ["RadioChannel"], ""],
+ ["APIReference", ["TechArticle"], ""],
+ ["Abdomen", [], ""],
+ ["AboutPage", ["WebPage"], ""],
+ ["AcceptAction", ["AllocateAction"], ""],
+ ["Accommodation", ["Place"], ""],
+ ["AccountingService", ["FinancialService"], ""],
+ ["AchieveAction", ["Action"], ""],
+ ["Action", ["Thing"], ""],
+ ["ActionAccessSpecification", ["Intangible"], ""],
+ ["ActionStatusType", ["StatusEnumeration"], ""],
+ ["ActivateAction", ["ControlAction"], ""],
+ ["ActivationFee", [], ""],
+ ["ActiveActionStatus", [], ""],
+ ["ActiveNotRecruiting", [], ""],
+ ["AddAction", ["UpdateAction"], ""],
+ ["AdministrativeArea", ["Place"], ""],
+ ["AdultEntertainment", ["EntertainmentBusiness"], ""],
+ ["AdultOrientedEnumeration", ["Enumeration"], ""],
+ ["AdvertiserContentArticle", ["Article"], ""],
+ ["AerobicActivity", [], ""],
+ ["AggregateOffer", ["Offer"], ""],
+ ["AggregateRating", ["Rating"], ""],
+ ["AgreeAction", ["ReactAction"], ""],
+ ["Airline", ["Organization"], ""],
+ ["Airport", ["CivicStructure"], ""],
+ ["AlbumRelease", [], ""],
+ ["AlcoholConsideration", [], ""],
+ ["AlgorithmicMediaDigitalSource", [], ""],
+ ["AlgorithmicallyEnhancedDigitalSource", [], ""],
+ ["AlignmentObject", ["Intangible"], ""],
+ ["AllWheelDriveConfiguration", [], ""],
+ ["AllergiesHealthAspect", [], ""],
+ ["AllocateAction", ["OrganizeAction"], ""],
+ ["AmpStory", ["CreativeWork", "MediaObject"], ""],
+ ["AmusementPark", ["EntertainmentBusiness"], ""],
+ ["AnaerobicActivity", [], ""],
+ ["AnalysisNewsArticle", ["NewsArticle"], ""],
+ ["AnatomicalStructure", ["MedicalEntity"], ""],
+ ["AnatomicalSystem", ["MedicalEntity"], ""],
+ ["AndroidPlatform", [], ""],
+ ["Anesthesia", [], ""],
+ ["AnimalShelter", ["LocalBusiness"], ""],
+ ["Answer", ["Comment"], ""],
+ ["Apartment", ["Accommodation"], ""],
+ ["ApartmentComplex", ["Residence"], ""],
+ ["Appearance", [], ""],
+ ["AppendAction", ["InsertAction"], ""],
+ ["ApplyAction", ["OrganizeAction"], ""],
+ ["ApprovedIndication", ["MedicalIndication"], ""],
+ ["Aquarium", ["CivicStructure"], ""],
+ ["ArchiveComponent", ["CreativeWork"], ""],
+ ["ArchiveOrganization", ["LocalBusiness"], ""],
+ ["ArriveAction", ["MoveAction"], ""],
+ ["ArtGallery", ["EntertainmentBusiness"], ""],
+ ["Artery", ["Vessel"], ""],
+ ["Article", ["CreativeWork"], ""],
+ ["AskAction", ["CommunicateAction"], ""],
+ ["AskPublicNewsArticle", ["NewsArticle"], ""],
+ ["AssessAction", ["Action"], ""],
+ ["AssignAction", ["AllocateAction"], ""],
+ ["Atlas", ["CreativeWork"], ""],
+ ["Attorney", ["LegalService"], ""],
+ ["Audience", ["Intangible"], ""],
+ ["AudioObject", ["MediaObject"], ""],
+ ["AudioObjectSnapshot", ["AudioObject"], ""],
+ ["Audiobook", ["AudioObject", "Book"], ""],
+ ["AudiobookFormat", [], ""],
+ ["AuthenticateAction", ["ControlAction"], ""],
+ ["AuthoritativeLegalValue", [], ""],
+ ["AuthorizeAction", ["AllocateAction"], ""],
+ ["AutoBodyShop", ["AutomotiveBusiness"], ""],
+ ["AutoDealer", ["AutomotiveBusiness"], ""],
+ ["AutoPartsStore", ["AutomotiveBusiness", "Store"], ""],
+ ["AutoRental", ["AutomotiveBusiness"], ""],
+ ["AutoRepair", ["AutomotiveBusiness"], ""],
+ ["AutoWash", ["AutomotiveBusiness"], ""],
+ ["AutomatedTeller", ["FinancialService"], ""],
+ ["AutomotiveBusiness", ["LocalBusiness"], ""],
+ ["Ayurvedic", [], ""],
+ ["BackOrder", [], ""],
+ ["BackgroundNewsArticle", ["NewsArticle"], ""],
+ ["Bacteria", [], ""],
+ ["Bakery", ["FoodEstablishment"], ""],
+ ["Balance", [], ""],
+ ["BankAccount", ["FinancialProduct"], ""],
+ ["BankOrCreditUnion", ["FinancialService"], ""],
+ ["BarOrPub", ["FoodEstablishment"], ""],
+ ["Barcode", ["ImageObject"], ""],
+ ["BasicIncome", [], ""],
+ ["Beach", ["CivicStructure"], ""],
+ ["BeautySalon", ["HealthAndBeautyBusiness"], ""],
+ ["BedAndBreakfast", ["LodgingBusiness"], ""],
+ ["BedDetails", ["Intangible"], ""],
+ ["BedType", ["QualitativeValue"], ""],
+ ["BefriendAction", ["InteractAction"], ""],
+ ["BenefitsHealthAspect", [], ""],
+ ["BikeStore", ["Store"], ""],
+ ["BioChemEntity", ["Thing"], ""],
+ ["Blog", ["CreativeWork"], ""],
+ ["BlogPosting", ["SocialMediaPosting"], ""],
+ ["BloodTest", ["MedicalTest"], ""],
+ ["BoardingPolicyType", ["Enumeration"], ""],
+ ["BoatReservation", ["Reservation"], ""],
+ ["BoatTerminal", ["CivicStructure"], ""],
+ ["BoatTrip", ["Trip"], ""],
+ ["BodyMeasurementArm", [], ""],
+ ["BodyMeasurementBust", [], ""],
+ ["BodyMeasurementChest", [], ""],
+ ["BodyMeasurementFoot", [], ""],
+ ["BodyMeasurementHand", [], ""],
+ ["BodyMeasurementHead", [], ""],
+ ["BodyMeasurementHeight", [], ""],
+ ["BodyMeasurementHips", [], ""],
+ ["BodyMeasurementInsideLeg", [], ""],
+ ["BodyMeasurementNeck", [], ""],
+ ["BodyMeasurementTypeEnumeration", ["MeasurementTypeEnumeration"], ""],
+ ["BodyMeasurementUnderbust", [], ""],
+ ["BodyMeasurementWaist", [], ""],
+ ["BodyMeasurementWeight", [], ""],
+ ["BodyOfWater", ["Landform"], ""],
+ ["Bone", ["AnatomicalStructure"], ""],
+ ["Book", ["CreativeWork"], ""],
+ ["BookFormatType", ["Enumeration"], ""],
+ ["BookSeries", ["CreativeWorkSeries"], ""],
+ ["BookStore", ["Store"], ""],
+ ["BookmarkAction", ["OrganizeAction"], ""],
+ ["Boolean", [], ""],
+ ["BorrowAction", ["TransferAction"], ""],
+ ["BowlingAlley", ["SportsActivityLocation"], ""],
+ ["BrainStructure", ["AnatomicalStructure"], ""],
+ [
+ "Brand",
+ ["Intangible", "https://www.omg.org/spec/Commons/Classifiers/Classifier"],
+ "",
+ ],
+ ["BreadcrumbList", ["ItemList"], ""],
+ ["Brewery", ["FoodEstablishment"], ""],
+ ["Bridge", ["CivicStructure"], ""],
+ ["BroadcastChannel", ["Intangible"], ""],
+ ["BroadcastEvent", ["PublicationEvent"], ""],
+ ["BroadcastFrequencySpecification", ["Intangible"], ""],
+ ["BroadcastRelease", [], ""],
+ ["BroadcastService", ["Service"], ""],
+ ["BrokerageAccount", ["InvestmentOrDeposit"], ""],
+ ["BuddhistTemple", ["PlaceOfWorship"], ""],
+ ["BusOrCoach", ["Vehicle"], ""],
+ ["BusReservation", ["Reservation"], ""],
+ ["BusStation", ["CivicStructure"], ""],
+ ["BusStop", ["CivicStructure"], ""],
+ ["BusTrip", ["Trip"], ""],
+ ["BusinessAudience", ["Audience"], ""],
+ ["BusinessEntityType", ["Enumeration"], ""],
+ ["BusinessEvent", ["Event"], ""],
+ ["BusinessFunction", ["Enumeration"], ""],
+ ["BusinessSupport", [], ""],
+ ["BuyAction", ["TradeAction"], ""],
+ ["ByBankTransferInAdvance", [], ""],
+ ["ByInvoice", [], ""],
+ ["CDCPMDRecord", ["StructuredValue"], ""],
+ ["CDFormat", [], ""],
+ ["COD", [], ""],
+ ["CT", [], ""],
+ ["CableOrSatelliteService", ["Service"], ""],
+ ["CafeOrCoffeeShop", ["FoodEstablishment"], ""],
+ ["Campground", ["CivicStructure", "LodgingBusiness"], ""],
+ ["CampingPitch", ["Accommodation"], ""],
+ ["Canal", ["BodyOfWater"], ""],
+ ["CancelAction", ["PlanAction"], ""],
+ ["Car", ["Vehicle"], ""],
+ ["CarUsageType", ["Enumeration"], ""],
+ ["Cardiovascular", [], ""],
+ ["CardiovascularExam", [], ""],
+ ["CaseSeries", [], ""],
+ ["Cash", [], ""],
+ ["Casino", ["EntertainmentBusiness"], ""],
+ ["CassetteFormat", [], ""],
+ ["CategoryCode", ["DefinedTerm"], ""],
+ ["CategoryCodeSet", ["DefinedTermSet"], ""],
+ ["CatholicChurch", ["Church"], ""],
+ ["CausesHealthAspect", [], ""],
+ ["Cemetery", ["CivicStructure"], ""],
+ [
+ "Certification",
+ [
+ "CreativeWork",
+ "https://spec.edmcouncil.org/fibo/ontology/FND/Arrangements/Documents/Certificate",
+ ],
+ "",
+ ],
+ ["CertificationActive", [], ""],
+ ["CertificationInactive", [], ""],
+ ["CertificationStatusEnumeration", ["Enumeration"], ""],
+ ["Chapter", ["CreativeWork"], ""],
+ ["CharitableIncorporatedOrganization", [], ""],
+ ["CheckAction", ["FindAction"], ""],
+ ["CheckInAction", ["CommunicateAction"], ""],
+ ["CheckInAdvance", [], ""],
+ ["CheckOutAction", ["CommunicateAction"], ""],
+ ["CheckoutPage", ["WebPage"], ""],
+ ["ChemicalSubstance", ["BioChemEntity"], ""],
+ ["ChildCare", ["LocalBusiness"], ""],
+ ["ChildrensEvent", ["Event"], ""],
+ ["Chiropractic", [], ""],
+ ["ChooseAction", ["AssessAction"], ""],
+ ["Church", ["PlaceOfWorship"], ""],
+ ["City", ["AdministrativeArea"], ""],
+ ["CityHall", ["GovernmentBuilding"], ""],
+ ["CivicStructure", ["Place"], ""],
+ ["Claim", ["CreativeWork"], ""],
+ ["ClaimReview", ["Review"], ""],
+ ["Class", ["Intangible"], ""],
+ ["CleaningFee", [], ""],
+ ["Clinician", [], ""],
+ ["Clip", ["CreativeWork"], ""],
+ ["ClothingStore", ["Store"], ""],
+ ["CoOp", [], ""],
+ ["Code", ["CreativeWork"], "SoftwareSourceCode"],
+ ["CohortStudy", [], ""],
+ ["Collection", ["CreativeWork"], ""],
+ ["CollectionPage", ["WebPage"], ""],
+ ["CollegeOrUniversity", ["EducationalOrganization"], ""],
+ ["ComedyClub", ["EntertainmentBusiness"], ""],
+ ["ComedyEvent", ["Event"], ""],
+ ["ComicCoverArt", ["ComicStory", "CoverArt"], ""],
+ ["ComicIssue", ["PublicationIssue"], ""],
+ ["ComicSeries", ["Periodical"], ""],
+ ["ComicStory", ["CreativeWork"], ""],
+ ["Comment", ["CreativeWork"], ""],
+ ["CommentAction", ["CommunicateAction"], ""],
+ ["CommentPermission", [], ""],
+ ["CommunicateAction", ["InteractAction"], ""],
+ ["CommunityHealth", ["MedicalBusiness"], ""],
+ ["CompilationAlbum", [], ""],
+ ["CompleteDataFeed", ["DataFeed"], ""],
+ ["Completed", [], ""],
+ ["CompletedActionStatus", [], ""],
+ ["CompositeCaptureDigitalSource", [], ""],
+ ["CompositeDigitalSource", [], ""],
+ ["CompositeSyntheticDigitalSource", [], ""],
+ ["CompositeWithTrainedAlgorithmicMediaDigitalSource", [], ""],
+ ["CompoundPriceSpecification", ["PriceSpecification"], ""],
+ ["ComputerLanguage", ["Intangible"], ""],
+ ["ComputerStore", ["Store"], ""],
+ ["ConferenceEvent", ["Event"], ""],
+ ["ConfirmAction", ["InformAction"], ""],
+ ["Consortium", ["Organization"], ""],
+ ["ConstraintNode", ["Intangible"], ""],
+ ["ConsumeAction", ["Action"], ""],
+ ["ContactPage", ["WebPage"], ""],
+ ["ContactPoint", ["StructuredValue"], ""],
+ ["ContactPointOption", ["Enumeration"], ""],
+ ["ContagiousnessHealthAspect", [], ""],
+ ["Continent", ["Landform"], ""],
+ ["ControlAction", ["Action"], ""],
+ ["ConvenienceStore", ["Store"], ""],
+ ["Conversation", ["CreativeWork"], ""],
+ ["CookAction", ["CreateAction"], ""],
+ ["Cooperative", ["Organization"], ""],
+ ["Corporation", ["Organization"], ""],
+ ["CorrectionComment", ["Comment"], ""],
+ [
+ "Country",
+ [
+ "AdministrativeArea",
+ "https://www.omg.org/spec/Commons/GeopoliticalEntities/GeopoliticalEntity",
+ ],
+ "",
+ ],
+ ["Course", ["CreativeWork", "LearningResource"], ""],
+ ["CourseInstance", ["Event"], ""],
+ ["Courthouse", ["GovernmentBuilding"], ""],
+ ["CoverArt", ["VisualArtwork"], ""],
+ ["CovidTestingFacility", ["MedicalClinic"], ""],
+ ["CreateAction", ["Action"], ""],
+ ["CreativeWork", ["Thing"], ""],
+ ["CreativeWorkSeason", ["CreativeWork"], ""],
+ ["CreativeWorkSeries", ["CreativeWork", "Series"], ""],
+ ["Credential", ["CreativeWork"], ""],
+ ["CreditCard", ["LoanOrCredit", "PaymentCard"], ""],
+ ["Crematorium", ["CivicStructure"], ""],
+ ["CriticReview", ["Review"], ""],
+ ["CrossSectional", [], ""],
+ ["CssSelectorType", ["Text"], ""],
+ ["CurrencyConversionService", ["FinancialProduct"], ""],
+ ["DDxElement", ["MedicalIntangible"], ""],
+ ["DECooperativeCharity", [], ""],
+ ["DEFoundationCharity", [], ""],
+ ["DEJointStockCompanyCharity", [], ""],
+ ["DELimitedLiabilityCharity", [], ""],
+ ["DENonprofitType", ["NonprofitType"], ""],
+ ["DENotRegisteredAssociationCharity", [], ""],
+ ["DEPublicCharity", [], ""],
+ ["DERegisteredAssociationCharity", [], ""],
+ ["DJMixAlbum", [], ""],
+ ["DVDFormat", [], ""],
+ ["DamagedCondition", [], ""],
+ ["DanceEvent", ["Event"], ""],
+ ["DanceGroup", ["PerformingGroup"], ""],
+ ["DangerousGoodConsideration", [], ""],
+ ["DataCatalog", ["CreativeWork"], ""],
+ ["DataDownload", ["MediaObject"], ""],
+ ["DataDrivenMediaDigitalSource", [], ""],
+ ["DataFeed", ["Dataset"], ""],
+ ["DataFeedItem", ["Intangible"], ""],
+ ["DataType", ["http://www.w3.org/2000/01/rdf-schema#Class"], ""],
+ ["Dataset", ["CreativeWork"], ""],
+ ["Date", [], ""],
+ ["DateTime", [], ""],
+ ["DatedMoneySpecification", ["StructuredValue"], "MonetaryAmount"],
+ ["DayOfWeek", ["Enumeration"], ""],
+ ["DaySpa", ["HealthAndBeautyBusiness"], ""],
+ ["DeactivateAction", ["ControlAction"], ""],
+ ["DecontextualizedContent", [], ""],
+ ["DefenceEstablishment", ["GovernmentBuilding"], ""],
+ ["DefinedRegion", ["Place", "StructuredValue"], ""],
+ ["DefinedTerm", ["Intangible"], ""],
+ ["DefinedTermSet", ["CreativeWork"], ""],
+ ["DefinitiveLegalValue", [], ""],
+ ["DeleteAction", ["UpdateAction"], ""],
+ ["DeliveryChargeSpecification", ["PriceSpecification"], ""],
+ ["DeliveryEvent", ["Event"], ""],
+ ["DeliveryMethod", ["Enumeration"], ""],
+ ["Demand", ["Intangible"], ""],
+ ["DemoAlbum", [], ""],
+ ["DemoGameAvailability", [], ""],
+ ["Dentist", ["LocalBusiness", "MedicalBusiness", "MedicalOrganization"], ""],
+ ["Dentistry", [], ""],
+ ["DepartAction", ["MoveAction"], ""],
+ ["DepartmentStore", ["Store"], ""],
+ ["DepositAccount", ["BankAccount", "InvestmentOrDeposit"], ""],
+ ["Dermatologic", [], "Dermatology"],
+ ["Dermatology", ["MedicalBusiness"], ""],
+ ["DesktopWebPlatform", [], ""],
+ ["DiabeticDiet", [], ""],
+ ["Diagnostic", [], ""],
+ ["DiagnosticLab", ["MedicalOrganization"], ""],
+ ["DiagnosticProcedure", ["MedicalProcedure"], ""],
+ ["Diet", ["CreativeWork", "LifestyleModification"], ""],
+ ["DietNutrition", ["MedicalBusiness"], ""],
+ ["DietarySupplement", ["Product", "Substance"], ""],
+ ["DigitalArtDigitalSource", [], ""],
+ ["DigitalAudioTapeFormat", [], ""],
+ ["DigitalCaptureDigitalSource", [], ""],
+ [
+ "DigitalDocument",
+ [
+ "CreativeWork",
+ "https://spec.edmcouncil.org/fibo/ontology/FND/Arrangements/Documents/Document",
+ ],
+ "",
+ ],
+ ["DigitalDocumentPermission", ["Intangible"], ""],
+ ["DigitalDocumentPermissionType", ["Enumeration"], ""],
+ ["DigitalFormat", [], ""],
+ ["DigitalPlatformEnumeration", ["Enumeration"], ""],
+ ["DirectDebit", [], ""],
+ ["DisabilitySupport", [], ""],
+ ["DisagreeAction", ["ReactAction"], ""],
+ ["Discontinued", [], ""],
+ ["DiscoverAction", ["FindAction"], ""],
+ ["DiscussionForumPosting", ["SocialMediaPosting"], ""],
+ ["DislikeAction", ["ReactAction"], ""],
+ ["Distance", ["Quantity"], ""],
+ ["DistanceFee", [], ""],
+ ["Distillery", ["FoodEstablishment"], ""],
+ ["DonateAction", ["TransferAction"], ""],
+ ["DoseSchedule", ["MedicalIntangible"], ""],
+ ["DoubleBlindedTrial", [], ""],
+ ["DownloadAction", ["TransferAction"], ""],
+ ["Downpayment", [], ""],
+ ["DrawAction", ["CreateAction"], ""],
+ ["Drawing", ["CreativeWork"], ""],
+ ["DrinkAction", ["ConsumeAction"], ""],
+ ["DriveWheelConfigurationValue", ["QualitativeValue"], ""],
+ ["DrivingSchoolVehicleUsage", [], ""],
+ ["Drug", ["Product", "Substance"], ""],
+ ["DrugClass", ["MedicalEntity"], ""],
+ ["DrugCost", ["MedicalEntity"], ""],
+ ["DrugCostCategory", ["MedicalEnumeration"], ""],
+ ["DrugLegalStatus", ["MedicalIntangible"], ""],
+ ["DrugPregnancyCategory", ["MedicalEnumeration"], ""],
+ ["DrugPrescriptionStatus", ["MedicalEnumeration"], ""],
+ ["DrugStrength", ["MedicalIntangible"], ""],
+ ["DryCleaningOrLaundry", ["LocalBusiness"], ""],
+ ["Duration", ["Quantity"], ""],
+ ["EBook", [], ""],
+ ["EPRelease", [], ""],
+ ["EUEnergyEfficiencyCategoryA", [], ""],
+ ["EUEnergyEfficiencyCategoryA1Plus", [], ""],
+ ["EUEnergyEfficiencyCategoryA2Plus", [], ""],
+ ["EUEnergyEfficiencyCategoryA3Plus", [], ""],
+ ["EUEnergyEfficiencyCategoryB", [], ""],
+ ["EUEnergyEfficiencyCategoryC", [], ""],
+ ["EUEnergyEfficiencyCategoryD", [], ""],
+ ["EUEnergyEfficiencyCategoryE", [], ""],
+ ["EUEnergyEfficiencyCategoryF", [], ""],
+ ["EUEnergyEfficiencyCategoryG", [], ""],
+ ["EUEnergyEfficiencyEnumeration", ["EnergyEfficiencyEnumeration"], ""],
+ ["Ear", [], ""],
+ ["EatAction", ["ConsumeAction"], ""],
+ ["EditedOrCroppedContent", [], ""],
+ ["EducationEvent", ["Event"], ""],
+ ["EducationalAudience", ["Audience"], ""],
+ ["EducationalOccupationalCredential", ["Credential"], ""],
+ ["EducationalOccupationalProgram", ["Intangible"], ""],
+ ["EducationalOrganization", ["CivicStructure", "Organization"], ""],
+ ["EffectivenessHealthAspect", [], ""],
+ ["Electrician", ["HomeAndConstructionBusiness"], ""],
+ ["ElectronicsStore", ["Store"], ""],
+ ["ElementarySchool", ["EducationalOrganization"], ""],
+ ["EmailMessage", ["Message"], ""],
+ ["Embassy", ["GovernmentBuilding"], ""],
+ ["Emergency", ["MedicalBusiness"], ""],
+ ["EmergencyService", ["LocalBusiness"], ""],
+ ["EmployeeRole", ["OrganizationRole"], ""],
+ ["EmployerAggregateRating", ["AggregateRating"], ""],
+ ["EmployerReview", ["Review"], ""],
+ ["EmploymentAgency", ["LocalBusiness"], ""],
+ ["Endocrine", [], ""],
+ ["EndorseAction", ["ReactAction"], ""],
+ ["EndorsementRating", ["Rating"], ""],
+ ["Energy", ["Quantity"], ""],
+ ["EnergyConsumptionDetails", ["Intangible"], ""],
+ ["EnergyEfficiencyEnumeration", ["Enumeration"], ""],
+ ["EnergyStarCertified", [], ""],
+ [
+ "EnergyStarEnergyEfficiencyEnumeration",
+ ["EnergyEfficiencyEnumeration"],
+ "",
+ ],
+ ["EngineSpecification", ["StructuredValue"], ""],
+ ["EnrollingByInvitation", [], ""],
+ ["EntertainmentBusiness", ["LocalBusiness"], ""],
+ ["EntryPoint", ["Intangible"], ""],
+ ["Enumeration", ["Intangible"], ""],
+ ["Episode", ["CreativeWork"], ""],
+ ["Error", ["InstantaneousEvent", "http://sarif.info/Result"], ""],
+ ["Event", ["Thing"], ""],
+ ["EventAttendanceModeEnumeration", ["Enumeration"], ""],
+ ["EventCancelled", [], ""],
+ ["EventMovedOnline", [], ""],
+ ["EventPostponed", [], ""],
+ ["EventRescheduled", [], ""],
+ ["EventReservation", ["Reservation"], ""],
+ ["EventScheduled", [], ""],
+ ["EventSeries", ["Event", "Series"], ""],
+ ["EventStatusType", ["StatusEnumeration"], ""],
+ ["EventVenue", ["CivicStructure"], ""],
+ ["EvidenceLevelA", [], ""],
+ ["EvidenceLevelB", [], ""],
+ ["EvidenceLevelC", [], ""],
+ ["ExampleMeasurementMethodEnum", [], ""],
+ ["ExchangeRateSpecification", ["StructuredValue"], ""],
+ ["ExchangeRefund", [], ""],
+ ["ExerciseAction", ["PlayAction"], ""],
+ ["ExerciseGym", ["SportsActivityLocation"], ""],
+ ["ExercisePlan", ["CreativeWork", "PhysicalActivity"], ""],
+ ["ExhibitionEvent", ["Event"], ""],
+ ["Eye", [], ""],
+ ["FAQPage", ["WebPage"], ""],
+ ["FDAcategoryA", [], ""],
+ ["FDAcategoryB", [], ""],
+ ["FDAcategoryC", [], ""],
+ ["FDAcategoryD", [], ""],
+ ["FDAcategoryX", [], ""],
+ ["FDAnotEvaluated", [], ""],
+ ["FMRadioChannel", ["RadioChannel"], ""],
+ ["FailedActionStatus", [], ""],
+ ["False", [], ""],
+ ["FastFoodRestaurant", ["FoodEstablishment"], ""],
+ ["Female", [], ""],
+ ["Festival", ["Event"], ""],
+ ["FilmAction", ["CreateAction"], ""],
+ ["FinancialIncentive", ["Intangible"], ""],
+ ["FinancialProduct", ["Service"], ""],
+ ["FinancialService", ["LocalBusiness"], ""],
+ ["FindAction", ["Action"], ""],
+ ["FireStation", ["CivicStructure", "EmergencyService"], ""],
+ ["Flexibility", [], ""],
+ ["Flight", ["Trip"], ""],
+ ["FlightReservation", ["Reservation"], ""],
+ ["Float", ["Number"], ""],
+ ["FloorPlan", ["Intangible"], ""],
+ ["Florist", ["Store"], ""],
+ ["FollowAction", ["InteractAction"], ""],
+ ["FoodEstablishment", ["LocalBusiness"], ""],
+ ["FoodEstablishmentReservation", ["Reservation"], ""],
+ ["FoodEvent", ["Event"], ""],
+ ["FoodService", ["Service"], ""],
+ ["FourWheelDriveConfiguration", [], ""],
+ ["FreeReturn", [], ""],
+ ["Friday", [], ""],
+ ["FrontWheelDriveConfiguration", [], ""],
+ ["FulfillmentTypeCollectionPoint", [], ""],
+ ["FulfillmentTypeDelivery", [], ""],
+ ["FulfillmentTypeEnumeration", ["Enumeration"], ""],
+ ["FulfillmentTypePickupDropoff", [], ""],
+ ["FulfillmentTypePickupInStore", [], ""],
+ ["FulfillmentTypeScheduledDelivery", [], ""],
+ ["FullGameAvailability", [], ""],
+ ["FullRefund", [], ""],
+ ["FundingAgency", ["Project"], ""],
+ ["FundingScheme", ["Organization"], ""],
+ ["Fungus", [], ""],
+ ["FurnitureStore", ["Store"], ""],
+ ["Game", ["CreativeWork"], ""],
+ ["GameAvailabilityEnumeration", ["Enumeration"], ""],
+ ["GamePlayMode", ["Enumeration"], ""],
+ ["GameServer", ["Intangible"], ""],
+ ["GameServerStatus", ["StatusEnumeration"], ""],
+ ["GardenStore", ["Store"], ""],
+ ["GasStation", ["AutomotiveBusiness"], ""],
+ ["Gastroenterologic", [], ""],
+ ["GatedResidenceCommunity", ["Residence"], ""],
+ ["GenderType", ["Enumeration"], ""],
+ ["Gene", ["BioChemEntity"], ""],
+ ["GeneralContractor", ["HomeAndConstructionBusiness"], ""],
+ ["GenericWebPlatform", [], ""],
+ ["Genetic", [], ""],
+ ["Genitourinary", [], ""],
+ ["GeoCircle", ["GeoShape"], ""],
+ ["GeoCoordinates", ["StructuredValue"], ""],
+ ["GeoShape", ["StructuredValue"], ""],
+ ["GeospatialGeometry", ["Intangible"], ""],
+ ["Geriatric", ["MedicalBusiness"], ""],
+ ["GettingAccessHealthAspect", [], ""],
+ ["GiveAction", ["TransferAction"], ""],
+ ["GlutenFreeDiet", [], ""],
+ ["GolfCourse", ["SportsActivityLocation"], ""],
+ ["GovernmentBenefitsType", ["Enumeration"], ""],
+ ["GovernmentBuilding", ["CivicStructure"], ""],
+ ["GovernmentOffice", ["LocalBusiness"], ""],
+ ["GovernmentOrganization", ["Organization"], ""],
+ ["GovernmentPermit", ["Permit"], ""],
+ ["GovernmentService", ["Service"], ""],
+ ["Grant", ["Intangible"], ""],
+ ["GraphicNovel", [], ""],
+ ["GroceryStore", ["Store"], ""],
+ ["GroupBoardingPolicy", [], ""],
+ ["Guide", ["CreativeWork"], ""],
+ ["Gynecologic", ["MedicalBusiness"], ""],
+ ["HVACBusiness", ["HomeAndConstructionBusiness"], ""],
+ ["Hackathon", ["Event"], ""],
+ ["HairSalon", ["HealthAndBeautyBusiness"], ""],
+ ["HalalDiet", [], ""],
+ ["Hardcover", [], ""],
+ ["HardwareStore", ["Store"], ""],
+ ["Head", [], ""],
+ ["HealthAndBeautyBusiness", ["LocalBusiness"], ""],
+ ["HealthAspectEnumeration", ["Enumeration"], ""],
+ ["HealthCare", [], ""],
+ ["HealthClub", ["HealthAndBeautyBusiness", "SportsActivityLocation"], ""],
+ ["HealthInsurancePlan", ["Intangible"], ""],
+ ["HealthPlanCostSharingSpecification", ["Intangible"], ""],
+ ["HealthPlanFormulary", ["Intangible"], ""],
+ ["HealthPlanNetwork", ["Intangible"], ""],
+ ["HealthTopicContent", ["WebContent"], ""],
+ ["HealthcareConsideration", [], ""],
+ ["HearingImpairedSupported", [], ""],
+ ["Hematologic", [], ""],
+ ["HighSchool", ["EducationalOrganization"], ""],
+ ["HinduDiet", [], ""],
+ ["HinduTemple", ["PlaceOfWorship"], ""],
+ ["HobbyShop", ["Store"], ""],
+ ["HomeAndConstructionBusiness", ["LocalBusiness"], ""],
+ ["HomeGoodsStore", ["Store"], ""],
+ ["Homeopathic", [], ""],
+ [
+ "Hospital",
+ ["CivicStructure", "EmergencyService", "MedicalOrganization"],
+ "",
+ ],
+ ["Hostel", ["LodgingBusiness"], ""],
+ ["Hotel", ["LodgingBusiness"], ""],
+ ["HotelRoom", ["Room"], ""],
+ ["House", ["Accommodation"], ""],
+ ["HousePainter", ["HomeAndConstructionBusiness"], ""],
+ ["HowItWorksHealthAspect", [], ""],
+ ["HowOrWhereHealthAspect", [], ""],
+ ["HowTo", ["CreativeWork"], ""],
+ ["HowToDirection", ["CreativeWork", "ListItem"], ""],
+ ["HowToItem", ["ListItem"], ""],
+ ["HowToSection", ["CreativeWork", "ItemList", "ListItem"], ""],
+ ["HowToStep", ["CreativeWork", "ItemList", "ListItem"], ""],
+ ["HowToSupply", ["HowToItem"], ""],
+ ["HowToTip", ["CreativeWork", "ListItem"], ""],
+ ["HowToTool", ["HowToItem"], ""],
+ ["HyperToc", ["CreativeWork"], ""],
+ ["HyperTocEntry", ["CreativeWork"], ""],
+ ["IOSPlatform", [], ""],
+ ["IPTCDigitalSourceEnumeration", ["MediaEnumeration"], ""],
+ ["ITCooperativeCharity", [], ""],
+ ["ITMutualAidCharity", [], ""],
+ ["ITNonprofitType", ["NonprofitType"], ""],
+ ["ITSocialCompanyCharity", [], ""],
+ ["ITSocialPromotionCharity", [], ""],
+ ["ITSportCompanyCharity", [], ""],
+ ["ITVolunteerAssociationCharity", [], ""],
+ ["IceCreamShop", ["FoodEstablishment"], ""],
+ ["IgnoreAction", ["AssessAction"], ""],
+ ["ImageGallery", ["MediaGallery"], ""],
+ ["ImageObject", ["MediaObject"], ""],
+ ["ImageObjectSnapshot", ["ImageObject"], ""],
+ ["ImagingTest", ["MedicalTest"], ""],
+ ["InForce", [], ""],
+ ["InStock", [], ""],
+ ["InStoreOnly", [], ""],
+ ["InStorePrepay", [], ""],
+ ["IncentiveQualifiedExpenseType", ["Enumeration"], ""],
+ ["IncentiveQualifiedExpenseTypeGoodsOnly", [], ""],
+ ["IncentiveQualifiedExpenseTypeGoodsOrServices", [], ""],
+ ["IncentiveQualifiedExpenseTypeServicesOnly", [], ""],
+ ["IncentiveQualifiedExpenseTypeUtilityBill", [], ""],
+ ["IncentiveStatus", ["Enumeration"], ""],
+ ["IncentiveStatusActive", [], ""],
+ ["IncentiveStatusInDevelopment", [], ""],
+ ["IncentiveStatusOnHold", [], ""],
+ ["IncentiveStatusRetired", [], ""],
+ ["IncentiveType", ["Enumeration"], ""],
+ ["IncentiveTypeLoan", [], ""],
+ ["IncentiveTypeRebateOrSubsidy", [], ""],
+ ["IncentiveTypeTaxCredit", [], ""],
+ ["IncentiveTypeTaxDeduction", [], ""],
+ ["IncentiveTypeTaxWaiver", [], ""],
+ ["IndividualPhysician", ["Physician"], ""],
+ ["IndividualProduct", ["Product"], ""],
+ ["Infectious", [], ""],
+ ["InfectiousAgentClass", ["MedicalEnumeration"], ""],
+ ["InfectiousDisease", ["MedicalCondition"], ""],
+ ["InformAction", ["CommunicateAction"], ""],
+ ["IngredientsHealthAspect", [], ""],
+ ["InsertAction", ["AddAction"], ""],
+ ["InstallAction", ["ConsumeAction"], ""],
+ ["Installment", [], ""],
+ ["InstantaneousEvent", ["StructuredValue"], ""],
+ ["InsuranceAgency", ["FinancialService"], ""],
+ ["Intangible", ["Thing"], ""],
+ ["Integer", ["Number"], ""],
+ ["InteractAction", ["Action"], ""],
+ ["InteractionCounter", ["StructuredValue"], ""],
+ ["InternationalTrial", [], ""],
+ ["InternetCafe", ["LocalBusiness"], ""],
+ ["InvestmentFund", ["InvestmentOrDeposit"], ""],
+ ["InvestmentOrDeposit", ["FinancialProduct"], ""],
+ ["InviteAction", ["CommunicateAction"], ""],
+ [
+ "Invoice",
+ [
+ "Intangible",
+ "https://spec.edmcouncil.org/fibo/ontology/FND/Arrangements/Documents/LegalDocument",
+ ],
+ "",
+ ],
+ ["InvoicePrice", [], ""],
+ ["ItemAvailability", ["Enumeration"], ""],
+ ["ItemList", ["Intangible"], ""],
+ ["ItemListOrderAscending", [], ""],
+ ["ItemListOrderDescending", [], ""],
+ ["ItemListOrderType", ["Enumeration"], ""],
+ ["ItemListUnordered", [], ""],
+ ["ItemPage", ["WebPage"], ""],
+ ["JewelryStore", ["Store"], ""],
+ ["JobPosting", ["Intangible"], ""],
+ ["JoinAction", ["InteractAction"], ""],
+ ["Joint", ["AnatomicalStructure"], ""],
+ ["KeepProduct", [], ""],
+ ["KosherDiet", [], ""],
+ ["LaboratoryScience", [], ""],
+ ["LakeBodyOfWater", ["BodyOfWater"], ""],
+ ["Landform", ["Place"], ""],
+ ["LandmarksOrHistoricalBuildings", ["Place"], ""],
+ ["Language", ["Intangible"], ""],
+ ["LaserDiscFormat", [], ""],
+ ["LearningResource", ["CreativeWork"], ""],
+ ["LeaveAction", ["InteractAction"], ""],
+ ["LeftHandDriving", [], ""],
+ ["LegalForceStatus", ["StatusEnumeration"], ""],
+ ["LegalService", ["LocalBusiness"], ""],
+ ["LegalValueLevel", ["Enumeration"], ""],
+ ["Legislation", ["CreativeWork"], ""],
+ ["LegislationObject", ["Legislation", "MediaObject"], ""],
+ ["LegislativeBuilding", ["GovernmentBuilding"], ""],
+ ["LeisureTimeActivity", [], ""],
+ ["LendAction", ["TransferAction"], ""],
+ ["Library", ["LocalBusiness"], ""],
+ ["LibrarySystem", ["Organization"], ""],
+ ["LifestyleModification", ["MedicalEntity"], ""],
+ ["Ligament", ["AnatomicalStructure"], ""],
+ ["LikeAction", ["ReactAction"], ""],
+ ["LimitedAvailability", [], ""],
+ ["LimitedByGuaranteeCharity", [], ""],
+ ["LinkRole", ["Role"], ""],
+ ["LiquorStore", ["Store"], ""],
+ ["ListItem", ["Intangible"], ""],
+ ["ListPrice", [], ""],
+ ["ListenAction", ["ConsumeAction"], ""],
+ ["LiteraryEvent", ["Event"], ""],
+ ["LiveAlbum", [], ""],
+ ["LiveBlogPosting", ["BlogPosting"], ""],
+ ["LivingWithHealthAspect", [], ""],
+ ["LoanOrCredit", ["FinancialProduct"], ""],
+ ["LocalBusiness", ["Organization", "Place"], ""],
+ ["LocationFeatureSpecification", ["PropertyValue"], ""],
+ ["LockerDelivery", [], ""],
+ ["Locksmith", ["HomeAndConstructionBusiness"], ""],
+ ["LodgingBusiness", ["LocalBusiness"], ""],
+ ["LodgingReservation", ["Reservation"], ""],
+ ["LoginAction", ["ControlAction"], ""],
+ ["Longitudinal", [], ""],
+ ["LoseAction", ["AchieveAction"], ""],
+ ["LowCalorieDiet", [], ""],
+ ["LowFatDiet", [], ""],
+ ["LowLactoseDiet", [], ""],
+ ["LowSaltDiet", [], ""],
+ ["Lung", [], ""],
+ ["LymphaticVessel", ["Vessel"], ""],
+ ["MRI", [], ""],
+ ["MSRP", [], ""],
+ ["MadeToOrder", [], ""],
+ ["Male", [], ""],
+ ["Manuscript", ["CreativeWork"], ""],
+ ["Map", ["CreativeWork"], ""],
+ ["MapCategoryType", ["Enumeration"], ""],
+ ["MarryAction", ["InteractAction"], ""],
+ ["Mass", ["Quantity"], ""],
+ ["MathSolver", ["CreativeWork"], ""],
+ ["MaximumDoseSchedule", ["DoseSchedule"], ""],
+ ["MayTreatHealthAspect", [], ""],
+ ["MeasurementMethodEnum", ["Enumeration"], ""],
+ ["MeasurementTypeEnumeration", ["Enumeration"], ""],
+ ["MediaEnumeration", ["Enumeration"], ""],
+ ["MediaGallery", ["CollectionPage"], ""],
+ ["MediaManipulationRatingEnumeration", ["Enumeration"], ""],
+ ["MediaObject", ["CreativeWork"], ""],
+ ["MediaReview", ["Review"], ""],
+ ["MediaReviewItem", ["CreativeWork"], ""],
+ ["MediaSubscription", ["Intangible"], ""],
+ ["MedicalAudience", ["Audience", "PeopleAudience"], ""],
+ ["MedicalAudienceType", ["MedicalEnumeration"], ""],
+ ["MedicalBusiness", ["LocalBusiness"], ""],
+ ["MedicalCause", ["MedicalEntity"], ""],
+ ["MedicalClinic", ["MedicalBusiness", "MedicalOrganization"], ""],
+ ["MedicalCode", ["CategoryCode", "MedicalIntangible"], ""],
+ ["MedicalCondition", ["MedicalEntity"], ""],
+ ["MedicalConditionStage", ["MedicalIntangible"], ""],
+ ["MedicalContraindication", ["MedicalEntity"], ""],
+ ["MedicalDevice", ["MedicalEntity"], ""],
+ ["MedicalDevicePurpose", ["MedicalEnumeration"], ""],
+ ["MedicalEntity", ["Thing"], ""],
+ ["MedicalEnumeration", ["Enumeration"], ""],
+ ["MedicalEvidenceLevel", ["MedicalEnumeration"], ""],
+ ["MedicalGuideline", ["MedicalEntity"], ""],
+ ["MedicalGuidelineContraindication", ["MedicalGuideline"], ""],
+ ["MedicalGuidelineRecommendation", ["MedicalGuideline"], ""],
+ ["MedicalImagingTechnique", ["MedicalEnumeration"], ""],
+ ["MedicalIndication", ["MedicalEntity"], ""],
+ ["MedicalIntangible", ["MedicalEntity"], ""],
+ ["MedicalObservationalStudy", ["MedicalStudy"], ""],
+ ["MedicalObservationalStudyDesign", ["MedicalEnumeration"], ""],
+ ["MedicalOrganization", ["Organization"], ""],
+ ["MedicalProcedure", ["MedicalEntity"], ""],
+ ["MedicalProcedureType", ["MedicalEnumeration"], ""],
+ ["MedicalResearcher", [], ""],
+ ["MedicalRiskCalculator", ["MedicalRiskEstimator"], ""],
+ ["MedicalRiskEstimator", ["MedicalEntity"], ""],
+ ["MedicalRiskFactor", ["MedicalEntity"], ""],
+ ["MedicalRiskScore", ["MedicalRiskEstimator"], ""],
+ ["MedicalScholarlyArticle", ["ScholarlyArticle"], ""],
+ ["MedicalSign", ["MedicalSignOrSymptom"], ""],
+ ["MedicalSignOrSymptom", ["MedicalCondition"], ""],
+ ["MedicalSpecialty", ["MedicalEnumeration", "Specialty"], ""],
+ ["MedicalStudy", ["MedicalEntity"], ""],
+ ["MedicalStudyStatus", ["MedicalEnumeration"], ""],
+ ["MedicalSymptom", ["MedicalSignOrSymptom"], ""],
+ ["MedicalTest", ["MedicalEntity"], ""],
+ ["MedicalTestPanel", ["MedicalTest"], ""],
+ ["MedicalTherapy", ["TherapeuticProcedure"], ""],
+ ["MedicalTrial", ["MedicalStudy"], ""],
+ ["MedicalTrialDesign", ["MedicalEnumeration"], ""],
+ ["MedicalWebPage", ["WebPage"], ""],
+ ["MedicineSystem", ["MedicalEnumeration"], ""],
+ ["MeetingRoom", ["Room"], ""],
+ ["MemberProgram", ["Intangible"], ""],
+ ["MemberProgramTier", ["Intangible"], ""],
+ ["MensClothingStore", ["Store"], ""],
+ ["Menu", ["CreativeWork"], ""],
+ ["MenuItem", ["Intangible"], ""],
+ ["MenuSection", ["CreativeWork"], ""],
+ ["MerchantReturnEnumeration", ["Enumeration"], ""],
+ ["MerchantReturnFiniteReturnWindow", [], ""],
+ ["MerchantReturnNotPermitted", [], ""],
+ ["MerchantReturnPolicy", ["Intangible"], ""],
+ ["MerchantReturnPolicySeasonalOverride", ["Intangible"], ""],
+ ["MerchantReturnUnlimitedWindow", [], ""],
+ ["MerchantReturnUnspecified", [], ""],
+ ["Message", ["CreativeWork"], ""],
+ ["MiddleSchool", ["EducationalOrganization"], ""],
+ ["Midwifery", ["MedicalBusiness"], ""],
+ ["MinimumAdvertisedPrice", [], ""],
+ ["MinorHumanEditsDigitalSource", [], ""],
+ ["MisconceptionsHealthAspect", [], ""],
+ ["MixedEventAttendanceMode", [], ""],
+ ["MixtapeAlbum", [], ""],
+ ["MobileApplication", ["SoftwareApplication"], ""],
+ ["MobilePhoneStore", ["Store"], ""],
+ ["MobileWebPlatform", [], ""],
+ ["MolecularEntity", ["BioChemEntity"], ""],
+ ["Monday", [], ""],
+ ["MonetaryAmount", ["StructuredValue"], ""],
+ ["MonetaryAmountDistribution", ["QuantitativeValueDistribution"], ""],
+ ["MonetaryGrant", ["Grant"], ""],
+ ["MoneyTransfer", ["TransferAction"], ""],
+ ["MortgageLoan", ["LoanOrCredit"], ""],
+ ["Mosque", ["PlaceOfWorship"], ""],
+ ["Motel", ["LodgingBusiness"], ""],
+ ["Motorcycle", ["Vehicle"], ""],
+ ["MotorcycleDealer", ["AutomotiveBusiness"], ""],
+ ["MotorcycleRepair", ["AutomotiveBusiness"], ""],
+ ["MotorizedBicycle", ["Vehicle"], ""],
+ ["Mountain", ["Landform"], ""],
+ ["MoveAction", ["Action"], ""],
+ ["Movie", ["CreativeWork"], ""],
+ ["MovieClip", ["Clip"], ""],
+ ["MovieRentalStore", ["Store"], ""],
+ ["MovieSeries", ["CreativeWorkSeries"], ""],
+ ["MovieTheater", ["CivicStructure", "EntertainmentBusiness"], ""],
+ ["MovingCompany", ["HomeAndConstructionBusiness"], ""],
+ ["MultiCenterTrial", [], ""],
+ ["MultiFrameComputationalCaptureDigitalSource", [], ""],
+ ["MultiPlayer", [], ""],
+ ["MulticellularParasite", [], ""],
+ ["Muscle", ["AnatomicalStructure"], ""],
+ ["Musculoskeletal", [], ""],
+ ["MusculoskeletalExam", [], ""],
+ ["Museum", ["CivicStructure"], ""],
+ ["MusicAlbum", ["MusicPlaylist"], ""],
+ ["MusicAlbumProductionType", ["Enumeration"], ""],
+ ["MusicAlbumReleaseType", ["Enumeration"], ""],
+ ["MusicComposition", ["CreativeWork"], ""],
+ ["MusicEvent", ["Event"], ""],
+ ["MusicGroup", ["PerformingGroup"], ""],
+ ["MusicPlaylist", ["CreativeWork"], ""],
+ ["MusicRecording", ["CreativeWork"], ""],
+ ["MusicRelease", ["MusicPlaylist"], ""],
+ ["MusicReleaseFormatType", ["Enumeration"], ""],
+ ["MusicStore", ["Store"], ""],
+ ["MusicVenue", ["CivicStructure"], ""],
+ ["MusicVideoObject", ["MediaObject"], ""],
+ ["NGO", ["Organization"], ""],
+ ["NLNonprofitType", ["NonprofitType"], ""],
+ ["NailSalon", ["HealthAndBeautyBusiness"], ""],
+ ["NarcoticConsideration", [], ""],
+ ["Neck", [], ""],
+ ["NegativeFilmDigitalSource", [], ""],
+ ["Nerve", ["AnatomicalStructure"], ""],
+ ["Neuro", [], ""],
+ ["Neurologic", [], ""],
+ ["NewCondition", [], ""],
+ ["NewsArticle", ["Article"], ""],
+ ["NewsMediaOrganization", ["Organization"], ""],
+ ["Newspaper", ["Periodical"], ""],
+ ["NightClub", ["EntertainmentBusiness"], ""],
+ ["NoninvasiveProcedure", [], ""],
+ ["Nonprofit501a", [], ""],
+ ["Nonprofit501c1", [], ""],
+ ["Nonprofit501c10", [], ""],
+ ["Nonprofit501c11", [], ""],
+ ["Nonprofit501c12", [], ""],
+ ["Nonprofit501c13", [], ""],
+ ["Nonprofit501c14", [], ""],
+ ["Nonprofit501c15", [], ""],
+ ["Nonprofit501c16", [], ""],
+ ["Nonprofit501c17", [], ""],
+ ["Nonprofit501c18", [], ""],
+ ["Nonprofit501c19", [], ""],
+ ["Nonprofit501c2", [], ""],
+ ["Nonprofit501c20", [], ""],
+ ["Nonprofit501c21", [], ""],
+ ["Nonprofit501c22", [], ""],
+ ["Nonprofit501c23", [], ""],
+ ["Nonprofit501c24", [], ""],
+ ["Nonprofit501c25", [], ""],
+ ["Nonprofit501c26", [], ""],
+ ["Nonprofit501c27", [], ""],
+ ["Nonprofit501c28", [], ""],
+ ["Nonprofit501c3", [], ""],
+ ["Nonprofit501c4", [], ""],
+ ["Nonprofit501c5", [], ""],
+ ["Nonprofit501c6", [], ""],
+ ["Nonprofit501c7", [], ""],
+ ["Nonprofit501c8", [], ""],
+ ["Nonprofit501c9", [], ""],
+ ["Nonprofit501d", [], ""],
+ ["Nonprofit501e", [], ""],
+ ["Nonprofit501f", [], ""],
+ ["Nonprofit501k", [], ""],
+ ["Nonprofit501n", [], ""],
+ ["Nonprofit501q", [], ""],
+ ["Nonprofit527", [], ""],
+ ["NonprofitANBI", [], ""],
+ ["NonprofitSBBI", [], ""],
+ ["NonprofitType", ["Enumeration"], ""],
+ ["Nose", [], ""],
+ ["NotInForce", [], ""],
+ ["NotYetRecruiting", [], ""],
+ ["Notary", ["LegalService"], ""],
+ ["NoteDigitalDocument", ["DigitalDocument"], ""],
+ ["Number", [], ""],
+ ["Nursing", ["MedicalBusiness"], ""],
+ ["NutritionInformation", ["StructuredValue"], ""],
+ ["OTC", [], ""],
+ ["Observation", ["Intangible", "QuantitativeValue"], ""],
+ ["Observational", [], ""],
+ ["Obstetric", ["MedicalBusiness"], ""],
+ ["Occupation", ["Intangible"], ""],
+ ["OccupationalActivity", [], ""],
+ ["OccupationalExperienceRequirements", ["Intangible"], ""],
+ ["OccupationalTherapy", ["MedicalTherapy"], ""],
+ ["OceanBodyOfWater", ["BodyOfWater"], ""],
+ ["Offer", ["Intangible"], ""],
+ ["OfferCatalog", ["ItemList"], ""],
+ ["OfferForLease", ["Offer"], ""],
+ ["OfferForPurchase", ["Offer"], ""],
+ ["OfferItemCondition", ["Enumeration"], ""],
+ ["OfferShippingDetails", ["StructuredValue"], ""],
+ ["OfficeEquipmentStore", ["Store"], ""],
+ ["OfficialLegalValue", [], ""],
+ ["OfflineEventAttendanceMode", [], ""],
+ ["OfflinePermanently", [], ""],
+ ["OfflineTemporarily", [], ""],
+ ["OnDemandEvent", ["PublicationEvent"], ""],
+ ["OnSitePickup", [], ""],
+ ["Oncologic", ["MedicalBusiness"], ""],
+ ["OneTimePayments", [], ""],
+ ["Online", [], ""],
+ ["OnlineBusiness", ["Organization"], ""],
+ ["OnlineEventAttendanceMode", [], ""],
+ ["OnlineFull", [], ""],
+ ["OnlineMarketplace", ["OnlineStore"], ""],
+ ["OnlineOnly", [], ""],
+ ["OnlineStore", ["OnlineBusiness"], ""],
+ ["OpenTrial", [], ""],
+ ["OpeningHoursSpecification", ["StructuredValue"], ""],
+ ["OperatingSystem", ["SoftwareApplication"], ""],
+ ["OpinionNewsArticle", ["NewsArticle"], ""],
+ ["Optician", ["MedicalBusiness"], ""],
+ ["Optometric", ["MedicalBusiness"], ""],
+ [
+ "Order",
+ [
+ "Intangible",
+ "https://spec.edmcouncil.org/fibo/ontology/FND/Arrangements/Documents/LegalDocument",
+ ],
+ "",
+ ],
+ ["OrderAction", ["TradeAction"], ""],
+ ["OrderCancelled", [], ""],
+ ["OrderDelivered", [], ""],
+ ["OrderInTransit", [], ""],
+ ["OrderItem", ["StructuredValue"], ""],
+ ["OrderPaymentDue", [], ""],
+ ["OrderPickupAvailable", [], ""],
+ ["OrderProblem", [], ""],
+ ["OrderProcessing", [], ""],
+ ["OrderReturned", [], ""],
+ ["OrderStatus", ["StatusEnumeration"], ""],
+ ["Organization", ["Thing"], ""],
+ ["OrganizationRole", ["Role"], ""],
+ ["OrganizeAction", ["Action"], ""],
+ ["OriginalMediaContent", [], ""],
+ ["OriginalShippingFees", [], ""],
+ ["Osteopathic", [], ""],
+ ["Otolaryngologic", ["MedicalBusiness"], ""],
+ ["OutOfStock", [], ""],
+ ["OutletStore", ["Store"], ""],
+ ["OverviewHealthAspect", [], ""],
+ ["OwnershipInfo", ["StructuredValue"], ""],
+ ["PET", [], ""],
+ ["PaidLeave", [], ""],
+ ["PaintAction", ["CreateAction"], ""],
+ ["Painting", ["CreativeWork"], ""],
+ ["PalliativeProcedure", ["MedicalProcedure", "MedicalTherapy"], ""],
+ ["Pamphlet", [], ""],
+ ["Paperback", [], ""],
+ ["ParcelDelivery", ["Intangible"], ""],
+ ["ParcelService", [], ""],
+ ["ParentAudience", ["PeopleAudience"], ""],
+ ["ParentalSupport", [], ""],
+ ["Park", ["CivicStructure"], ""],
+ ["ParkingFacility", ["CivicStructure"], ""],
+ ["ParkingMap", [], ""],
+ ["PartiallyInForce", [], ""],
+ ["Pathology", [], ""],
+ ["PathologyTest", ["MedicalTest"], ""],
+ ["Patient", ["MedicalAudience", "Person"], ""],
+ ["PatientExperienceHealthAspect", [], ""],
+ ["PawnShop", ["Store"], ""],
+ ["PayAction", ["TradeAction"], ""],
+ ["PaymentAutomaticallyApplied", [], ""],
+ ["PaymentCard", ["FinancialProduct", "PaymentMethod"], ""],
+ ["PaymentChargeSpecification", ["PriceSpecification"], ""],
+ ["PaymentComplete", [], ""],
+ ["PaymentDeclined", [], ""],
+ ["PaymentDue", [], ""],
+ ["PaymentMethod", ["Intangible"], ""],
+ ["PaymentMethodType", ["Enumeration"], ""],
+ ["PaymentPastDue", [], ""],
+ ["PaymentService", ["FinancialProduct", "PaymentMethod"], ""],
+ ["PaymentStatusType", ["StatusEnumeration"], ""],
+ ["Pediatric", ["MedicalBusiness"], ""],
+ ["PeopleAudience", ["Audience"], ""],
+ ["PercutaneousProcedure", [], ""],
+ ["PerformAction", ["PlayAction"], ""],
+ ["PerformanceRole", ["Role"], ""],
+ ["PerformingArtsEvent", ["Event"], ""],
+ ["PerformingArtsTheater", ["CivicStructure"], ""],
+ ["PerformingGroup", ["Organization"], ""],
+ ["Periodical", ["CreativeWorkSeries"], ""],
+ ["Permit", ["Intangible"], ""],
+ ["Person", ["Thing"], ""],
+ ["PetStore", ["Store"], ""],
+ ["Pharmacy", ["MedicalBusiness", "MedicalOrganization"], ""],
+ ["PharmacySpecialty", [], ""],
+ ["PhoneCarrierPayment", [], ""],
+ ["Photograph", ["CreativeWork"], ""],
+ ["PhotographAction", ["CreateAction"], ""],
+ ["PhysicalActivity", ["LifestyleModification"], ""],
+ ["PhysicalActivityCategory", ["Enumeration"], ""],
+ ["PhysicalExam", ["MedicalEnumeration", "MedicalProcedure"], ""],
+ ["PhysicalTherapy", ["MedicalTherapy"], ""],
+ ["Physician", ["MedicalBusiness", "MedicalOrganization"], ""],
+ ["PhysiciansOffice", ["Physician"], ""],
+ ["Physiotherapy", ["MedicalBusiness"], ""],
+ ["Place", ["Thing"], ""],
+ ["PlaceOfWorship", ["CivicStructure"], ""],
+ ["PlaceboControlledTrial", [], ""],
+ ["PlanAction", ["OrganizeAction"], ""],
+ ["PlasticSurgery", ["MedicalBusiness"], ""],
+ ["Play", ["CreativeWork"], ""],
+ ["PlayAction", ["Action"], ""],
+ ["PlayGameAction", ["ConsumeAction"], ""],
+ ["Playground", ["CivicStructure"], ""],
+ ["Plumber", ["HomeAndConstructionBusiness"], ""],
+ ["PodcastEpisode", ["Episode"], ""],
+ ["PodcastSeason", ["CreativeWorkSeason"], ""],
+ ["PodcastSeries", ["CreativeWorkSeries"], ""],
+ ["Podiatric", ["MedicalBusiness"], ""],
+ ["PoliceStation", ["CivicStructure", "EmergencyService"], ""],
+ ["PoliticalParty", ["Organization"], ""],
+ ["Pond", ["BodyOfWater"], ""],
+ ["PositiveFilmDigitalSource", [], ""],
+ ["PostOffice", ["GovernmentOffice"], ""],
+ ["PostalAddress", ["ContactPoint"], ""],
+ ["PostalCodeRangeSpecification", ["StructuredValue"], ""],
+ ["Poster", ["CreativeWork"], ""],
+ ["PotentialActionStatus", [], ""],
+ ["PreOrder", [], ""],
+ ["PreOrderAction", ["TradeAction"], ""],
+ ["PreSale", [], ""],
+ ["PregnancyHealthAspect", [], ""],
+ ["PrependAction", ["InsertAction"], ""],
+ ["Preschool", ["EducationalOrganization"], ""],
+ ["PrescriptionOnly", [], ""],
+ ["PresentationDigitalDocument", ["DigitalDocument"], ""],
+ ["PreventionHealthAspect", [], ""],
+ ["PreventionIndication", ["MedicalIndication"], ""],
+ ["PriceComponentTypeEnumeration", ["Enumeration"], ""],
+ ["PriceSpecification", ["StructuredValue"], ""],
+ ["PriceTypeEnumeration", ["Enumeration"], ""],
+ ["PrimaryCare", ["MedicalBusiness"], ""],
+ ["PrintDigitalSource", [], ""],
+ ["Prion", [], ""],
+ ["Product", ["Thing"], ""],
+ ["ProductCollection", ["Collection", "Product"], ""],
+ [
+ "ProductGroup",
+ [
+ "Product",
+ "https://www.omg.org/spec/Commons/Classifiers/Classifier",
+ "https://www.omg.org/spec/Commons/Collections/Collection",
+ ],
+ "",
+ ],
+ ["ProductModel", ["Product"], ""],
+ ["ProfessionalService", ["LocalBusiness"], ""],
+ ["ProfilePage", ["WebPage"], ""],
+ ["PrognosisHealthAspect", [], ""],
+ ["ProgramMembership", ["Intangible"], ""],
+ ["Project", ["Organization"], ""],
+ ["PronounceableText", ["Text"], ""],
+ ["Property", ["Intangible"], ""],
+ ["PropertyValue", ["StructuredValue"], ""],
+ ["PropertyValueSpecification", ["Intangible"], ""],
+ ["Protein", ["BioChemEntity"], ""],
+ ["Protozoa", [], ""],
+ ["Psychiatric", ["MedicalBusiness"], ""],
+ ["PsychologicalTreatment", ["TherapeuticProcedure"], ""],
+ ["PublicHealth", ["MedicalBusiness"], ""],
+ ["PublicHolidays", [], ""],
+ ["PublicSwimmingPool", ["SportsActivityLocation"], ""],
+ ["PublicToilet", ["CivicStructure"], ""],
+ ["PublicationEvent", ["Event"], ""],
+ ["PublicationIssue", ["CreativeWork"], ""],
+ ["PublicationVolume", ["CreativeWork"], ""],
+ ["Pulmonary", [], ""],
+ ["PurchaseType", ["Enumeration"], ""],
+ ["PurchaseTypeLease", [], ""],
+ ["PurchaseTypeNewPurchase", [], ""],
+ ["PurchaseTypeTradeIn", [], ""],
+ ["PurchaseTypeUsedPurchase", [], ""],
+ ["QAPage", ["WebPage"], ""],
+ ["QualitativeValue", ["Enumeration"], ""],
+ ["QuantitativeValue", ["StructuredValue"], ""],
+ ["QuantitativeValueDistribution", ["StructuredValue"], ""],
+ ["Quantity", [], ""],
+ ["Question", ["Comment"], ""],
+ ["Quiz", ["LearningResource"], ""],
+ ["Quotation", ["CreativeWork"], ""],
+ ["QuoteAction", ["TradeAction"], ""],
+ ["RVPark", ["CivicStructure"], ""],
+ ["RadiationTherapy", ["MedicalTherapy"], ""],
+ ["RadioBroadcastService", ["BroadcastService"], ""],
+ ["RadioChannel", ["BroadcastChannel"], ""],
+ ["RadioClip", ["Clip"], ""],
+ ["RadioEpisode", ["Episode"], ""],
+ ["RadioSeason", ["CreativeWorkSeason"], ""],
+ ["RadioSeries", ["CreativeWorkSeries"], ""],
+ ["RadioStation", ["LocalBusiness"], ""],
+ ["Radiography", [], ""],
+ ["RandomizedTrial", [], ""],
+ ["Rating", ["Intangible"], ""],
+ ["ReactAction", ["AssessAction"], ""],
+ ["ReadAction", ["ConsumeAction"], ""],
+ ["ReadPermission", [], ""],
+ ["RealEstateAgent", ["LocalBusiness"], ""],
+ ["RealEstateListing", ["WebPage"], ""],
+ ["RearWheelDriveConfiguration", [], ""],
+ ["ReceiveAction", ["TransferAction"], ""],
+ ["Recipe", ["HowTo"], ""],
+ ["Recommendation", ["Review"], ""],
+ ["RecommendedDoseSchedule", ["DoseSchedule"], ""],
+ ["Recruiting", [], ""],
+ ["RecyclingCenter", ["LocalBusiness"], ""],
+ ["ReducedRelevanceForChildrenConsideration", [], ""],
+ ["RefundTypeEnumeration", ["Enumeration"], ""],
+ ["RefurbishedCondition", [], ""],
+ ["RegisterAction", ["InteractAction"], ""],
+ ["Registry", [], ""],
+ ["RegularPrice", [], ""],
+ ["ReimbursementCap", [], ""],
+ ["RejectAction", ["AllocateAction"], ""],
+ ["RelatedTopicsHealthAspect", [], ""],
+ ["RemixAlbum", [], ""],
+ ["Renal", [], ""],
+ ["RentAction", ["TradeAction"], ""],
+ ["RentalCarReservation", ["Reservation"], ""],
+ ["RentalVehicleUsage", [], ""],
+ ["RepaymentSpecification", ["StructuredValue"], ""],
+ ["ReplaceAction", ["UpdateAction"], ""],
+ ["ReplyAction", ["CommunicateAction"], ""],
+ ["Report", ["Article"], ""],
+ ["ReportageNewsArticle", ["NewsArticle"], ""],
+ ["ReportedDoseSchedule", ["DoseSchedule"], ""],
+ ["ResearchOrganization", ["Organization"], ""],
+ ["ResearchProject", ["Project"], ""],
+ ["Researcher", ["Audience"], ""],
+ ["Reservation", ["Intangible"], ""],
+ ["ReservationCancelled", [], ""],
+ ["ReservationConfirmed", [], ""],
+ ["ReservationHold", [], ""],
+ ["ReservationPackage", ["Reservation"], ""],
+ ["ReservationPending", [], ""],
+ ["ReservationStatusType", ["StatusEnumeration"], ""],
+ ["ReserveAction", ["PlanAction"], ""],
+ ["Reserved", [], ""],
+ ["Reservoir", ["BodyOfWater"], ""],
+ ["ResetPasswordAction", ["ControlAction"], ""],
+ ["Residence", ["Place"], ""],
+ ["Resort", ["LodgingBusiness"], ""],
+ ["RespiratoryTherapy", ["MedicalTherapy"], ""],
+ ["Restaurant", ["FoodEstablishment"], ""],
+ ["RestockingFees", [], ""],
+ ["RestrictedDiet", ["Enumeration"], ""],
+ ["ResultsAvailable", [], ""],
+ ["ResultsNotAvailable", [], ""],
+ ["ResumeAction", ["ControlAction"], ""],
+ ["Retail", [], ""],
+ ["ReturnAction", ["TransferAction"], ""],
+ ["ReturnAtKiosk", [], ""],
+ ["ReturnByMail", [], ""],
+ ["ReturnFeesCustomerResponsibility", [], ""],
+ ["ReturnFeesEnumeration", ["Enumeration"], ""],
+ ["ReturnInStore", [], ""],
+ ["ReturnLabelCustomerResponsibility", [], ""],
+ ["ReturnLabelDownloadAndPrint", [], ""],
+ ["ReturnLabelInBox", [], ""],
+ ["ReturnLabelSourceEnumeration", ["Enumeration"], ""],
+ ["ReturnMethodEnumeration", ["Enumeration"], ""],
+ ["ReturnShippingFees", [], ""],
+ ["Review", ["CreativeWork"], ""],
+ ["ReviewAction", ["AssessAction"], ""],
+ ["ReviewNewsArticle", ["CriticReview", "NewsArticle"], ""],
+ ["Rheumatologic", [], ""],
+ ["RightHandDriving", [], ""],
+ ["RisksOrComplicationsHealthAspect", [], ""],
+ ["RiverBodyOfWater", ["BodyOfWater"], ""],
+ ["Role", ["Intangible"], ""],
+ ["RoofingContractor", ["HomeAndConstructionBusiness"], ""],
+ ["Room", ["Accommodation"], ""],
+ ["RsvpAction", ["InformAction"], ""],
+ ["RsvpResponseMaybe", [], ""],
+ ["RsvpResponseNo", [], ""],
+ ["RsvpResponseType", ["Enumeration"], ""],
+ ["RsvpResponseYes", [], ""],
+ ["RuntimePlatform", ["SoftwareApplication"], ""],
+ ["SRP", [], ""],
+ ["SafetyHealthAspect", [], ""],
+ ["SaleEvent", ["Event"], ""],
+ ["SalePrice", [], ""],
+ ["SatireOrParodyContent", [], ""],
+ ["SatiricalArticle", ["Article"], ""],
+ ["Saturday", [], ""],
+ ["Schedule", ["Intangible"], ""],
+ ["ScheduleAction", ["PlanAction"], ""],
+ ["ScholarlyArticle", ["Article"], ""],
+ ["School", ["EducationalOrganization"], ""],
+ ["SchoolDistrict", ["AdministrativeArea"], ""],
+ ["ScreenCaptureDigitalSource", [], ""],
+ ["ScreeningEvent", ["Event"], ""],
+ ["ScreeningHealthAspect", [], ""],
+ ["Sculpture", ["CreativeWork"], ""],
+ ["SeaBodyOfWater", ["BodyOfWater"], ""],
+ ["SearchAction", ["Action"], ""],
+ ["SearchRescueOrganization", ["Organization"], ""],
+ ["SearchResultsPage", ["WebPage"], ""],
+ ["Season", ["CreativeWork"], "CreativeWorkSeason"],
+ ["Seat", ["Intangible"], ""],
+ ["SeatingMap", [], ""],
+ ["SeeDoctorHealthAspect", [], ""],
+ ["SeekToAction", ["Action"], ""],
+ ["SelfCareHealthAspect", [], ""],
+ ["SelfStorage", ["LocalBusiness"], ""],
+ ["SellAction", ["TradeAction"], ""],
+ ["SendAction", ["TransferAction"], ""],
+ ["SequentialArt", ["Book", "VisualArtwork"], ""],
+ ["Series", ["Intangible"], ""],
+ ["Service", ["Intangible"], ""],
+ ["ServiceChannel", ["Intangible"], ""],
+ ["ServicePeriod", ["StructuredValue"], ""],
+ ["SexualContentConsideration", [], ""],
+ ["ShareAction", ["CommunicateAction"], ""],
+ ["SheetMusic", ["CreativeWork"], ""],
+ ["ShippingConditions", ["StructuredValue"], ""],
+ ["ShippingDeliveryTime", ["StructuredValue"], ""],
+ ["ShippingRateSettings", ["StructuredValue"], ""],
+ ["ShippingService", ["StructuredValue"], ""],
+ ["ShoeStore", ["Store"], ""],
+ ["ShoppingCenter", ["LocalBusiness"], ""],
+ ["ShortStory", ["CreativeWork"], ""],
+ ["SideEffectsHealthAspect", [], ""],
+ ["SingleBlindedTrial", [], ""],
+ ["SingleCenterTrial", [], ""],
+ ["SingleFamilyResidence", ["House"], ""],
+ ["SinglePlayer", [], ""],
+ ["SingleRelease", [], ""],
+ ["SiteNavigationElement", ["WebPageElement"], ""],
+ ["SizeGroupEnumeration", ["Enumeration"], ""],
+ ["SizeSpecification", ["QualitativeValue"], ""],
+ ["SizeSystemEnumeration", ["Enumeration"], ""],
+ ["SizeSystemImperial", [], ""],
+ ["SizeSystemMetric", [], ""],
+ ["SkiResort", ["Resort", "SportsActivityLocation"], ""],
+ ["Skin", [], ""],
+ ["SocialEvent", ["Event"], ""],
+ ["SocialMediaPosting", ["Article"], ""],
+ ["SoftwareApplication", ["CreativeWork"], ""],
+ ["SoftwareSourceCode", ["CreativeWork"], ""],
+ ["SoldOut", [], ""],
+ ["SolveMathAction", ["Action"], ""],
+ ["SomeProducts", ["Product"], ""],
+ ["SoundtrackAlbum", [], ""],
+ ["SpeakableSpecification", ["Intangible"], ""],
+ ["SpecialAnnouncement", ["CreativeWork"], ""],
+ ["Specialty", ["Enumeration"], ""],
+ ["SpeechPathology", [], ""],
+ ["SpokenWordAlbum", [], ""],
+ ["SportingGoodsStore", ["Store"], ""],
+ ["SportsActivityLocation", ["LocalBusiness"], ""],
+ ["SportsClub", ["SportsActivityLocation"], ""],
+ ["SportsEvent", ["Event"], ""],
+ ["SportsOrganization", ["Organization"], ""],
+ ["SportsTeam", ["SportsOrganization"], ""],
+ ["SpreadsheetDigitalDocument", ["DigitalDocument"], ""],
+ ["StadiumOrArena", ["CivicStructure", "SportsActivityLocation"], ""],
+ ["StagedContent", [], ""],
+ ["StagesHealthAspect", [], ""],
+ ["State", ["AdministrativeArea"], ""],
+ ["Statement", ["CreativeWork"], ""],
+ ["StatisticalPopulation", ["Intangible"], ""],
+ ["StatisticalVariable", ["ConstraintNode"], ""],
+ ["StatusEnumeration", ["Enumeration"], ""],
+ ["SteeringPositionValue", ["QualitativeValue"], ""],
+ ["Store", ["LocalBusiness"], ""],
+ ["StoreCreditRefund", [], ""],
+ ["StrengthTraining", [], ""],
+ ["StrikethroughPrice", [], ""],
+ ["StructuredValue", ["Intangible"], ""],
+ ["StudioAlbum", [], ""],
+ ["SubscribeAction", ["InteractAction"], ""],
+ ["Subscription", [], ""],
+ ["Substance", ["MedicalEntity"], ""],
+ ["SubwayStation", ["CivicStructure"], ""],
+ ["Suite", ["Accommodation"], ""],
+ ["Sunday", [], ""],
+ ["SuperficialAnatomy", ["MedicalEntity"], ""],
+ ["Surgical", [], ""],
+ ["SurgicalProcedure", ["MedicalProcedure"], ""],
+ ["SuspendAction", ["ControlAction"], ""],
+ ["Suspended", [], ""],
+ ["Syllabus", ["LearningResource"], ""],
+ ["SymptomsHealthAspect", [], ""],
+ ["Synagogue", ["PlaceOfWorship"], ""],
+ ["TVClip", ["Clip"], ""],
+ ["TVEpisode", ["Episode"], ""],
+ ["TVSeason", ["CreativeWork", "CreativeWorkSeason"], ""],
+ ["TVSeries", ["CreativeWork", "CreativeWorkSeries"], ""],
+ ["Table", ["WebPageElement"], ""],
+ ["TakeAction", ["TransferAction"], ""],
+ ["TattooParlor", ["HealthAndBeautyBusiness"], ""],
+ ["Taxi", ["Service"], "TaxiService"],
+ ["TaxiReservation", ["Reservation"], ""],
+ ["TaxiService", ["Service"], ""],
+ ["TaxiStand", ["CivicStructure"], ""],
+ ["TaxiVehicleUsage", [], ""],
+ ["Taxon", ["Thing"], ""],
+ ["TechArticle", ["Article"], ""],
+ ["TelevisionChannel", ["BroadcastChannel"], ""],
+ ["TelevisionStation", ["LocalBusiness"], ""],
+ ["TennisComplex", ["SportsActivityLocation"], ""],
+ ["Terminated", [], ""],
+ ["Text", [], ""],
+ ["TextDigitalDocument", ["DigitalDocument"], ""],
+ ["TextObject", ["MediaObject"], ""],
+ ["TheaterEvent", ["Event"], ""],
+ ["TheaterGroup", ["PerformingGroup"], ""],
+ ["Therapeutic", [], ""],
+ ["TherapeuticProcedure", ["MedicalProcedure"], ""],
+ ["Thesis", ["CreativeWork"], ""],
+ ["Thing", [], ""],
+ ["Throat", [], ""],
+ ["Thursday", [], ""],
+ ["Ticket", ["Intangible"], ""],
+ ["TieAction", ["AchieveAction"], ""],
+ ["TierBenefitEnumeration", ["Enumeration"], ""],
+ ["TierBenefitLoyaltyPoints", [], ""],
+ ["TierBenefitLoyaltyPrice", [], ""],
+ ["TierBenefitLoyaltyReturns", [], ""],
+ ["TierBenefitLoyaltyShipping", [], ""],
+ ["Time", [], ""],
+ ["TipAction", ["TradeAction"], ""],
+ ["TireShop", ["Store"], ""],
+ ["TobaccoNicotineConsideration", [], ""],
+ ["TollFree", [], ""],
+ ["TouristAttraction", ["Place"], ""],
+ ["TouristDestination", ["Place"], ""],
+ ["TouristInformationCenter", ["LocalBusiness"], ""],
+ ["TouristTrip", ["Trip"], ""],
+ ["Toxicologic", [], ""],
+ ["ToyStore", ["Store"], ""],
+ ["TrackAction", ["FindAction"], ""],
+ ["TradeAction", ["Action"], ""],
+ ["TraditionalChinese", [], ""],
+ ["TrainReservation", ["Reservation"], ""],
+ ["TrainStation", ["CivicStructure"], ""],
+ ["TrainTrip", ["Trip"], ""],
+ ["TrainedAlgorithmicMediaDigitalSource", [], ""],
+ ["TransferAction", ["Action"], ""],
+ ["TransformedContent", [], ""],
+ ["TransitMap", [], ""],
+ ["TravelAction", ["MoveAction"], ""],
+ ["TravelAgency", ["LocalBusiness"], ""],
+ ["TreatmentIndication", ["MedicalIndication"], ""],
+ ["TreatmentsHealthAspect", [], ""],
+ ["Trip", ["Intangible"], ""],
+ ["TripleBlindedTrial", [], ""],
+ ["True", [], ""],
+ ["Tuesday", [], ""],
+ ["TypeAndQuantityNode", ["StructuredValue"], ""],
+ ["TypesHealthAspect", [], ""],
+ ["UKNonprofitType", ["NonprofitType"], ""],
+ ["UKTrust", [], ""],
+ ["URL", ["Text"], ""],
+ ["USNonprofitType", ["NonprofitType"], ""],
+ ["Ultrasound", [], ""],
+ ["UnRegisterAction", ["InteractAction"], ""],
+ ["UnclassifiedAdultConsideration", [], ""],
+ ["UnemploymentSupport", [], ""],
+ ["UnincorporatedAssociationCharity", [], ""],
+ ["UnitPriceSpecification", ["PriceSpecification"], ""],
+ ["UnofficialLegalValue", [], ""],
+ ["UpdateAction", ["Action"], ""],
+ ["Urologic", [], ""],
+ ["UsageOrScheduleHealthAspect", [], ""],
+ ["UseAction", ["ConsumeAction"], ""],
+ ["UsedCondition", [], ""],
+ ["UserBlocks", ["UserInteraction"], "InteractionCounter"],
+ ["UserCheckins", ["UserInteraction"], "InteractionCounter"],
+ ["UserComments", ["UserInteraction"], "InteractionCounter"],
+ ["UserDownloads", ["UserInteraction"], "InteractionCounter"],
+ ["UserInteraction", ["Event"], "InteractionCounter"],
+ ["UserLikes", ["UserInteraction"], "InteractionCounter"],
+ ["UserPageVisits", ["UserInteraction"], "InteractionCounter"],
+ ["UserPlays", ["UserInteraction"], "InteractionCounter"],
+ ["UserPlusOnes", ["UserInteraction"], "InteractionCounter"],
+ ["UserReview", ["Review"], ""],
+ ["UserTweets", ["UserInteraction"], "InteractionCounter"],
+ ["VacationRental", ["LodgingBusiness"], ""],
+ ["VeganDiet", [], ""],
+ ["VegetarianDiet", [], ""],
+ ["Vehicle", ["Product"], ""],
+ ["Vein", ["Vessel"], ""],
+ ["VenueMap", [], ""],
+ ["Vessel", ["AnatomicalStructure"], ""],
+ ["VeterinaryCare", ["MedicalOrganization"], ""],
+ ["VideoGallery", ["MediaGallery"], ""],
+ ["VideoGame", ["Game", "SoftwareApplication"], ""],
+ ["VideoGameClip", ["Clip"], ""],
+ ["VideoGameSeries", ["CreativeWorkSeries"], ""],
+ ["VideoObject", ["MediaObject"], ""],
+ ["VideoObjectSnapshot", ["VideoObject"], ""],
+ ["ViewAction", ["ConsumeAction"], ""],
+ ["VinylFormat", [], ""],
+ ["ViolenceConsideration", [], ""],
+ ["VirtualLocation", ["Intangible"], ""],
+ ["VirtualRecordingDigitalSource", [], ""],
+ ["Virus", [], ""],
+ ["VisualArtsEvent", ["Event"], ""],
+ ["VisualArtwork", ["CreativeWork"], ""],
+ ["VitalSign", ["MedicalSign"], ""],
+ ["Volcano", ["Landform"], ""],
+ ["VoteAction", ["ChooseAction"], ""],
+ ["WPAdBlock", ["WebPageElement"], ""],
+ ["WPFooter", ["WebPageElement"], ""],
+ ["WPHeader", ["WebPageElement"], ""],
+ ["WPSideBar", ["WebPageElement"], ""],
+ ["WantAction", ["ReactAction"], ""],
+ [
+ "WarrantyPromise",
+ [
+ "StructuredValue",
+ "https://spec.edmcouncil.org/fibo/ontology/FND/Agreements/Contracts/MutualContractualAgreement",
+ ],
+ "",
+ ],
+ ["WarrantyScope", ["Enumeration"], ""],
+ ["WatchAction", ["ConsumeAction"], ""],
+ ["Waterfall", ["BodyOfWater"], ""],
+ ["WeaponConsideration", [], ""],
+ ["WearAction", ["UseAction"], ""],
+ ["WearableMeasurementBack", [], ""],
+ ["WearableMeasurementChestOrBust", [], ""],
+ ["WearableMeasurementCollar", [], ""],
+ ["WearableMeasurementCup", [], ""],
+ ["WearableMeasurementHeight", [], ""],
+ ["WearableMeasurementHips", [], ""],
+ ["WearableMeasurementInseam", [], ""],
+ ["WearableMeasurementLength", [], ""],
+ ["WearableMeasurementOutsideLeg", [], ""],
+ ["WearableMeasurementSleeve", [], ""],
+ ["WearableMeasurementTypeEnumeration", ["MeasurementTypeEnumeration"], ""],
+ ["WearableMeasurementWaist", [], ""],
+ ["WearableMeasurementWidth", [], ""],
+ ["WearableSizeGroupBig", [], ""],
+ ["WearableSizeGroupBoys", [], ""],
+ ["WearableSizeGroupEnumeration", ["SizeGroupEnumeration"], ""],
+ ["WearableSizeGroupExtraShort", [], ""],
+ ["WearableSizeGroupExtraTall", [], ""],
+ ["WearableSizeGroupGirls", [], ""],
+ ["WearableSizeGroupHusky", [], ""],
+ ["WearableSizeGroupInfants", [], ""],
+ ["WearableSizeGroupJuniors", [], ""],
+ ["WearableSizeGroupMaternity", [], ""],
+ ["WearableSizeGroupMens", [], ""],
+ ["WearableSizeGroupMisses", [], ""],
+ ["WearableSizeGroupPetite", [], ""],
+ ["WearableSizeGroupPlus", [], ""],
+ ["WearableSizeGroupRegular", [], ""],
+ ["WearableSizeGroupShort", [], ""],
+ ["WearableSizeGroupTall", [], ""],
+ ["WearableSizeGroupWomens", [], ""],
+ ["WearableSizeSystemAU", [], ""],
+ ["WearableSizeSystemBR", [], ""],
+ ["WearableSizeSystemCN", [], ""],
+ ["WearableSizeSystemContinental", [], ""],
+ ["WearableSizeSystemDE", [], ""],
+ ["WearableSizeSystemEN13402", [], ""],
+ ["WearableSizeSystemEnumeration", ["SizeSystemEnumeration"], ""],
+ ["WearableSizeSystemEurope", [], ""],
+ ["WearableSizeSystemFR", [], ""],
+ ["WearableSizeSystemGS1", [], ""],
+ ["WearableSizeSystemIT", [], ""],
+ ["WearableSizeSystemJP", [], ""],
+ ["WearableSizeSystemMX", [], ""],
+ ["WearableSizeSystemUK", [], ""],
+ ["WearableSizeSystemUS", [], ""],
+ ["WebAPI", ["Service"], ""],
+ ["WebApplication", ["SoftwareApplication"], ""],
+ ["WebContent", ["CreativeWork"], ""],
+ ["WebPage", ["CreativeWork"], ""],
+ ["WebPageElement", ["CreativeWork"], ""],
+ ["WebSite", ["CreativeWork"], ""],
+ ["Wednesday", [], ""],
+ ["WesternConventional", [], ""],
+ ["Wholesale", [], ""],
+ ["WholesaleStore", ["Store"], ""],
+ ["WinAction", ["AchieveAction"], ""],
+ ["Winery", ["FoodEstablishment"], ""],
+ ["Withdrawn", [], ""],
+ ["WorkBasedProgram", ["EducationalOccupationalProgram"], ""],
+ ["WorkersUnion", ["Organization"], ""],
+ ["WriteAction", ["CreateAction"], ""],
+ ["WritePermission", [], ""],
+ ["XPathType", ["Text"], ""],
+ ["XRay", [], ""],
+ ["ZoneBoardingPolicy", [], ""],
+ ["Zoo", ["CivicStructure"], ""],
+];
+
+export const schemaOrgPropertyRows: readonly SchemaOrgPropertyRow[] = [
+ [
+ "about",
+ [
+ "Certification",
+ "CommunicateAction",
+ "CreativeWork",
+ "DefinedTerm",
+ "DefinedTermSet",
+ "Event",
+ ],
+ ["Thing"],
+ "",
+ ],
+ ["abridged", ["Book"], ["Boolean"], ""],
+ ["abstract", ["CreativeWork"], ["Text"], ""],
+ ["accelerationTime", ["Vehicle"], ["QuantitativeValue"], ""],
+ ["acceptedAnswer", ["Question"], ["Answer", "ItemList"], ""],
+ ["acceptedOffer", ["Order"], ["Offer"], ""],
+ [
+ "acceptedPaymentMethod",
+ ["Demand", "Offer", "Organization"],
+ ["LoanOrCredit", "PaymentMethod", "Text"],
+ "",
+ ],
+ [
+ "acceptsReservations",
+ ["FoodEstablishment"],
+ ["Boolean", "Text", "URL"],
+ "",
+ ],
+ ["accessCode", ["DeliveryEvent"], ["Text"], ""],
+ ["accessMode", ["CreativeWork"], ["Text"], ""],
+ ["accessModeSufficient", ["CreativeWork"], ["ItemList"], ""],
+ ["accessibilityAPI", ["CreativeWork"], ["Text"], ""],
+ ["accessibilityControl", ["CreativeWork"], ["Text"], ""],
+ ["accessibilityFeature", ["CreativeWork"], ["Text"], ""],
+ ["accessibilityHazard", ["CreativeWork"], ["Text"], ""],
+ ["accessibilitySummary", ["CreativeWork"], ["Text"], ""],
+ ["accommodationCategory", ["Accommodation"], ["Text"], ""],
+ ["accommodationFloorPlan", ["Accommodation", "Residence"], ["FloorPlan"], ""],
+ ["accountId", ["Invoice"], ["Text"], ""],
+ ["accountMinimumInflow", ["BankAccount"], ["MonetaryAmount"], ""],
+ ["accountOverdraftLimit", ["BankAccount"], ["MonetaryAmount"], ""],
+ ["accountablePerson", ["CreativeWork"], ["Person"], ""],
+ ["acquireLicensePage", ["CreativeWork"], ["CreativeWork", "URL"], ""],
+ ["acquiredFrom", ["OwnershipInfo"], ["Organization", "Person"], ""],
+ ["acrissCode", ["BusOrCoach", "Car"], ["Text"], ""],
+ [
+ "actionAccessibilityRequirement",
+ ["ConsumeAction"],
+ ["ActionAccessSpecification"],
+ "",
+ ],
+ ["actionApplication", ["EntryPoint"], ["SoftwareApplication"], ""],
+ ["actionOption", ["ChooseAction"], ["Text", "Thing"], ""],
+ [
+ "actionPlatform",
+ ["EntryPoint"],
+ ["DigitalPlatformEnumeration", "Text", "URL"],
+ "",
+ ],
+ ["actionProcess", ["Action"], ["HowTo"], ""],
+ ["actionStatus", ["Action"], ["ActionStatusType"], ""],
+ [
+ "actionableFeedbackPolicy",
+ ["NewsMediaOrganization", "Organization"],
+ ["CreativeWork", "URL"],
+ "",
+ ],
+ [
+ "activeIngredient",
+ ["DietarySupplement", "Drug", "DrugStrength", "Substance"],
+ ["Text"],
+ "",
+ ],
+ ["activityDuration", ["ExercisePlan"], ["Duration", "QuantitativeValue"], ""],
+ ["activityFrequency", ["ExercisePlan"], ["QuantitativeValue", "Text"], ""],
+ [
+ "actor",
+ [
+ "Clip",
+ "CreativeWorkSeason",
+ "Episode",
+ "Event",
+ "Movie",
+ "MovieSeries",
+ "PodcastSeries",
+ "RadioSeries",
+ "TVSeries",
+ "VideoGame",
+ "VideoGameSeries",
+ "VideoObject",
+ ],
+ ["PerformingGroup", "Person"],
+ "",
+ ],
+ [
+ "actors",
+ [
+ "Clip",
+ "Episode",
+ "Movie",
+ "MovieSeries",
+ "RadioSeries",
+ "TVSeries",
+ "VideoGame",
+ "VideoGameSeries",
+ "VideoObject",
+ ],
+ ["Person"],
+ "actor",
+ ],
+ ["addOn", ["Offer"], ["Offer"], ""],
+ ["additionalName", ["Person"], ["Text"], ""],
+ ["additionalNumberOfGuests", ["RsvpAction"], ["Number"], ""],
+ [
+ "additionalProperty",
+ [
+ "MerchantReturnPolicy",
+ "Offer",
+ "Place",
+ "Product",
+ "QualitativeValue",
+ "QuantitativeValue",
+ ],
+ ["PropertyValue"],
+ "",
+ ],
+ ["additionalType", ["Thing"], ["Text", "URL"], ""],
+ ["additionalVariable", ["ExercisePlan"], ["Text"], ""],
+ [
+ "address",
+ ["GeoCoordinates", "GeoShape", "Organization", "Person", "Place"],
+ ["PostalAddress", "Text"],
+ "",
+ ],
+ [
+ "addressCountry",
+ ["DefinedRegion", "GeoCoordinates", "GeoShape", "PostalAddress"],
+ ["Country", "Text"],
+ "",
+ ],
+ ["addressLocality", ["PostalAddress"], ["Text"], ""],
+ [
+ "addressRegion",
+ ["DefinedRegion", "PostalAddress"],
+ ["AdministrativeArea", "Text"],
+ "",
+ ],
+ ["administrationRoute", ["Drug"], ["Text"], ""],
+ ["advanceBookingRequirement", ["Demand", "Offer"], ["QuantitativeValue"], ""],
+ [
+ "adverseOutcome",
+ ["MedicalDevice", "TherapeuticProcedure"],
+ ["MedicalEntity"],
+ "",
+ ],
+ ["affectedBy", ["MedicalTest"], ["Drug"], ""],
+ ["affiliation", ["Person"], ["Organization"], ""],
+ ["afterMedia", ["HowToDirection"], ["MediaObject", "URL"], ""],
+ ["agent", ["Action"], ["Organization", "Person"], ""],
+ [
+ "agentInteractionStatistic",
+ ["Organization", "Person"],
+ ["InteractionCounter"],
+ "",
+ ],
+ ["aggregateElement", ["ItemList"], ["Thing"], ""],
+ [
+ "aggregateRating",
+ [
+ "Brand",
+ "CreativeWork",
+ "Event",
+ "Offer",
+ "Organization",
+ "Place",
+ "Product",
+ "Service",
+ ],
+ ["AggregateRating"],
+ "",
+ ],
+ ["aircraft", ["Flight"], ["Text", "Vehicle"], ""],
+ ["album", ["MusicGroup"], ["MusicAlbum"], ""],
+ ["albumProductionType", ["MusicAlbum"], ["MusicAlbumProductionType"], ""],
+ ["albumRelease", ["MusicAlbum"], ["MusicRelease"], ""],
+ ["albumReleaseType", ["MusicAlbum"], ["MusicAlbumReleaseType"], ""],
+ ["albums", ["MusicGroup"], ["MusicAlbum"], "album"],
+ ["alcoholWarning", ["Drug"], ["Text"], ""],
+ ["algorithm", ["MedicalRiskScore"], ["Text"], ""],
+ ["alignmentType", ["AlignmentObject"], ["Text"], ""],
+ ["alternateName", ["Thing"], ["Text"], ""],
+ ["alternativeHeadline", ["CreativeWork"], ["Text"], ""],
+ ["alternativeOf", ["Gene"], ["Gene"], ""],
+ ["alumni", ["EducationalOrganization", "Organization"], ["Person"], ""],
+ ["alumniOf", ["Person"], ["EducationalOrganization", "Organization"], ""],
+ [
+ "amenityFeature",
+ ["Accommodation", "FloorPlan", "LodgingBusiness", "Place"],
+ ["LocationFeatureSpecification"],
+ "",
+ ],
+ [
+ "amount",
+ [
+ "DatedMoneySpecification",
+ "InvestmentOrDeposit",
+ "LoanOrCredit",
+ "MonetaryGrant",
+ "MoneyTransfer",
+ ],
+ ["MonetaryAmount", "Number"],
+ "",
+ ],
+ ["amountOfThisGood", ["TypeAndQuantityNode"], ["Number"], ""],
+ [
+ "announcementLocation",
+ ["SpecialAnnouncement"],
+ ["CivicStructure", "LocalBusiness"],
+ "",
+ ],
+ [
+ "annualPercentageRate",
+ ["FinancialProduct"],
+ ["Number", "QuantitativeValue"],
+ "",
+ ],
+ ["answerCount", ["Question"], ["Integer"], ""],
+ ["answerExplanation", ["Answer"], ["Comment", "WebContent"], ""],
+ ["antagonist", ["Muscle"], ["Muscle"], ""],
+ ["appearance", ["Claim"], ["CreativeWork"], ""],
+ ["applicableCountry", ["MerchantReturnPolicy"], ["Country", "Text"], ""],
+ [
+ "applicableLocation",
+ ["DrugCost", "DrugLegalStatus"],
+ ["AdministrativeArea"],
+ "",
+ ],
+ ["applicantLocationRequirements", ["JobPosting"], ["AdministrativeArea"], ""],
+ ["application", ["EntryPoint"], ["SoftwareApplication"], "actionApplication"],
+ ["applicationCategory", ["SoftwareApplication"], ["Text", "URL"], ""],
+ ["applicationContact", ["JobPosting"], ["ContactPoint"], ""],
+ [
+ "applicationDeadline",
+ ["EducationalOccupationalProgram"],
+ ["Date", "Text"],
+ "",
+ ],
+ ["applicationStartDate", ["EducationalOccupationalProgram"], ["Date"], ""],
+ ["applicationSubCategory", ["SoftwareApplication"], ["Text", "URL"], ""],
+ ["applicationSuite", ["SoftwareApplication"], ["Text"], ""],
+ [
+ "appliesToDeliveryMethod",
+ ["DeliveryChargeSpecification", "PaymentChargeSpecification"],
+ ["DeliveryMethod"],
+ "",
+ ],
+ [
+ "appliesToPaymentMethod",
+ ["PaymentChargeSpecification"],
+ ["PaymentMethod"],
+ "",
+ ],
+ ["archiveHeld", ["ArchiveOrganization"], ["ArchiveComponent"], ""],
+ ["archivedAt", ["CreativeWork"], ["URL", "WebPage"], ""],
+ ["area", ["BroadcastService"], ["Place"], "serviceArea"],
+ [
+ "areaServed",
+ [
+ "ContactPoint",
+ "DeliveryChargeSpecification",
+ "Demand",
+ "FinancialIncentive",
+ "Offer",
+ "Organization",
+ "Service",
+ ],
+ ["AdministrativeArea", "GeoShape", "Place", "Text"],
+ "",
+ ],
+ ["arrivalAirport", ["Flight"], ["Airport"], ""],
+ ["arrivalBoatTerminal", ["BoatTrip"], ["BoatTerminal"], ""],
+ ["arrivalBusStop", ["BusTrip"], ["BusStation", "BusStop"], ""],
+ ["arrivalGate", ["Flight"], ["Text"], ""],
+ ["arrivalPlatform", ["TrainTrip"], ["Text"], ""],
+ ["arrivalStation", ["TrainTrip"], ["TrainStation"], ""],
+ ["arrivalTerminal", ["Flight"], ["Text"], ""],
+ ["arrivalTime", ["Trip"], ["DateTime", "Time"], ""],
+ ["artEdition", ["VisualArtwork"], ["Integer", "Text"], ""],
+ ["artMedium", ["VisualArtwork"], ["Text", "URL"], ""],
+ ["arterialBranch", ["Artery"], ["AnatomicalStructure"], ""],
+ ["artform", ["VisualArtwork"], ["Text", "URL"], ""],
+ ["articleBody", ["Article"], ["Text"], ""],
+ ["articleSection", ["Article"], ["Text"], ""],
+ ["artist", ["ComicIssue", "ComicStory", "VisualArtwork"], ["Person"], ""],
+ ["artworkSurface", ["VisualArtwork"], ["Text", "URL"], ""],
+ ["asin", ["Demand", "Offer", "Product"], ["Text", "URL"], ""],
+ ["aspect", ["MedicalWebPage"], ["Text"], "mainContentOfPage"],
+ ["assembly", ["APIReference"], ["Text"], "executableLibraryName"],
+ ["assemblyVersion", ["APIReference"], ["Text"], ""],
+ [
+ "assesses",
+ ["CreativeWork", "EducationEvent", "LearningResource"],
+ ["DefinedTerm", "Text"],
+ "",
+ ],
+ [
+ "associatedAnatomy",
+ ["MedicalCondition", "PhysicalActivity"],
+ ["AnatomicalStructure", "AnatomicalSystem", "SuperficialAnatomy"],
+ "",
+ ],
+ ["associatedArticle", ["MediaObject"], ["NewsArticle"], ""],
+ ["associatedClaimReview", ["Review"], ["Review"], ""],
+ [
+ "associatedDisease",
+ ["BioChemEntity"],
+ ["MedicalCondition", "PropertyValue", "URL"],
+ "",
+ ],
+ [
+ "associatedMedia",
+ ["CreativeWork", "HyperToc", "HyperTocEntry"],
+ ["MediaObject"],
+ "",
+ ],
+ ["associatedMediaReview", ["Review"], ["Review"], ""],
+ [
+ "associatedPathophysiology",
+ ["AnatomicalStructure", "AnatomicalSystem", "SuperficialAnatomy"],
+ ["Text"],
+ "",
+ ],
+ ["associatedReview", ["Review"], ["Review"], ""],
+ ["athlete", ["SportsTeam"], ["Person"], ""],
+ ["attendee", ["Event"], ["Organization", "Person"], ""],
+ ["attendees", ["Event"], ["Organization", "Person"], "attendee"],
+ [
+ "audience",
+ [
+ "CreativeWork",
+ "Event",
+ "LodgingBusiness",
+ "PlayAction",
+ "Product",
+ "Service",
+ ],
+ ["Audience"],
+ "",
+ ],
+ ["audienceType", ["Audience"], ["Text"], ""],
+ ["audio", ["CreativeWork"], ["AudioObject", "Clip", "MusicRecording"], ""],
+ ["auditDate", ["Certification"], ["Date", "DateTime"], ""],
+ ["authenticator", ["MediaSubscription"], ["Organization"], ""],
+ ["author", ["CreativeWork", "Rating"], ["Organization", "Person"], ""],
+ ["availability", ["Demand", "Offer"], ["ItemAvailability"], ""],
+ [
+ "availabilityEnds",
+ ["ActionAccessSpecification", "Demand", "Offer"],
+ ["Date", "DateTime", "Time"],
+ "",
+ ],
+ [
+ "availabilityStarts",
+ ["ActionAccessSpecification", "Demand", "Offer"],
+ ["Date", "DateTime", "Time"],
+ "",
+ ],
+ ["availableAtOrFrom", ["Demand", "Offer"], ["Place"], ""],
+ ["availableChannel", ["Service"], ["ServiceChannel"], ""],
+ ["availableDeliveryMethod", ["Demand", "Offer"], ["DeliveryMethod"], ""],
+ ["availableFrom", ["DeliveryEvent"], ["DateTime"], ""],
+ ["availableIn", ["DrugStrength"], ["AdministrativeArea"], ""],
+ [
+ "availableLanguage",
+ [
+ "ContactPoint",
+ "Course",
+ "LodgingBusiness",
+ "ServiceChannel",
+ "TouristAttraction",
+ ],
+ ["Language", "Text"],
+ "",
+ ],
+ ["availableOnDevice", ["SoftwareApplication"], ["Text"], ""],
+ [
+ "availableService",
+ ["Hospital", "MedicalClinic", "Physician"],
+ ["MedicalProcedure", "MedicalTest", "MedicalTherapy"],
+ "",
+ ],
+ ["availableStrength", ["Drug"], ["DrugStrength"], ""],
+ ["availableTest", ["DiagnosticLab"], ["MedicalTest"], ""],
+ ["availableThrough", ["DeliveryEvent"], ["DateTime"], ""],
+ [
+ "award",
+ ["CreativeWork", "Organization", "Person", "Product", "Service"],
+ ["Text"],
+ "",
+ ],
+ [
+ "awards",
+ ["CreativeWork", "Organization", "Person", "Product"],
+ ["Text"],
+ "award",
+ ],
+ ["awayTeam", ["SportsEvent"], ["Person", "SportsTeam"], ""],
+ ["backstory", ["Article"], ["CreativeWork", "Text"], ""],
+ ["bankAccountType", ["BankAccount"], ["Text", "URL"], ""],
+ [
+ "baseSalary",
+ ["EmployeeRole", "JobPosting"],
+ ["MonetaryAmount", "Number", "PriceSpecification"],
+ "",
+ ],
+ ["bccRecipient", ["Message"], ["ContactPoint", "Organization", "Person"], ""],
+ [
+ "bed",
+ ["Accommodation", "HotelRoom", "Suite"],
+ ["BedDetails", "BedType", "Text"],
+ "",
+ ],
+ ["beforeMedia", ["HowToDirection"], ["MediaObject", "URL"], ""],
+ ["beneficiaryBank", ["MoneyTransfer"], ["BankOrCreditUnion", "Text"], ""],
+ ["benefits", ["JobPosting"], ["Text"], "jobBenefits"],
+ ["benefitsSummaryUrl", ["HealthInsurancePlan"], ["URL"], ""],
+ ["bestRating", ["Rating"], ["Number", "Text"], ""],
+ ["billingAddress", ["Order"], ["PostalAddress"], ""],
+ [
+ "billingDuration",
+ ["UnitPriceSpecification"],
+ ["Duration", "Number", "QuantitativeValue"],
+ "",
+ ],
+ ["billingIncrement", ["UnitPriceSpecification"], ["Number"], ""],
+ ["billingPeriod", ["Invoice"], ["Duration"], ""],
+ ["billingStart", ["UnitPriceSpecification"], ["Number"], ""],
+ ["bioChemInteraction", ["BioChemEntity"], ["BioChemEntity"], ""],
+ ["bioChemSimilarity", ["BioChemEntity"], ["BioChemEntity"], ""],
+ ["biologicalRole", ["BioChemEntity"], ["DefinedTerm"], ""],
+ ["biomechnicalClass", ["Joint"], ["Text"], ""],
+ ["birthDate", ["Person"], ["Date"], ""],
+ ["birthPlace", ["Person"], ["Place"], ""],
+ ["bitrate", ["MediaObject"], ["Text"], ""],
+ ["blogPost", ["Blog"], ["BlogPosting"], ""],
+ ["blogPosts", ["Blog"], ["BlogPosting"], "blogPost"],
+ ["bloodSupply", ["Muscle"], ["Vessel"], ""],
+ ["boardingGroup", ["FlightReservation"], ["Text"], ""],
+ ["boardingPolicy", ["Airline", "Flight"], ["BoardingPolicyType"], ""],
+ ["bodyLocation", ["AnatomicalStructure", "MedicalProcedure"], ["Text"], ""],
+ ["bodyType", ["Vehicle"], ["QualitativeValue", "Text", "URL"], ""],
+ ["bookEdition", ["Book"], ["Text"], ""],
+ ["bookFormat", ["Book"], ["BookFormatType"], ""],
+ ["bookingAgent", ["Reservation"], ["Organization", "Person"], "broker"],
+ ["bookingTime", ["Reservation"], ["DateTime"], ""],
+ ["borrower", ["LendAction"], ["Person"], ""],
+ ["box", ["GeoShape"], ["Text"], ""],
+ ["branch", ["Nerve"], ["AnatomicalStructure"], "arterialBranch"],
+ ["branchCode", ["Place"], ["Text"], ""],
+ ["branchOf", ["LocalBusiness"], ["Organization"], "parentOrganization"],
+ [
+ "brand",
+ ["Organization", "Person", "Product", "Service"],
+ ["Brand", "Organization"],
+ "",
+ ],
+ ["breadcrumb", ["WebPage"], ["BreadcrumbList", "Text"], ""],
+ ["breastfeedingWarning", ["Drug"], ["Text"], ""],
+ ["broadcastAffiliateOf", ["BroadcastService"], ["Organization"], ""],
+ ["broadcastChannelId", ["BroadcastChannel"], ["Text"], ""],
+ ["broadcastDisplayName", ["BroadcastService"], ["Text"], ""],
+ [
+ "broadcastFrequency",
+ ["BroadcastChannel", "BroadcastService"],
+ ["BroadcastFrequencySpecification", "Text"],
+ "",
+ ],
+ [
+ "broadcastFrequencyValue",
+ ["BroadcastFrequencySpecification"],
+ ["Number", "QuantitativeValue"],
+ "",
+ ],
+ ["broadcastOfEvent", ["BroadcastEvent"], ["Event"], ""],
+ ["broadcastServiceTier", ["BroadcastChannel"], ["Text"], ""],
+ [
+ "broadcastSignalModulation",
+ ["BroadcastFrequencySpecification"],
+ ["QualitativeValue", "Text"],
+ "",
+ ],
+ ["broadcastSubChannel", ["BroadcastFrequencySpecification"], ["Text"], ""],
+ ["broadcastTimezone", ["BroadcastService"], ["Text"], ""],
+ ["broadcaster", ["BroadcastService"], ["Organization"], ""],
+ [
+ "broker",
+ ["Invoice", "Order", "Reservation", "Service"],
+ ["Organization", "Person"],
+ "",
+ ],
+ ["browserRequirements", ["WebApplication"], ["Text"], ""],
+ ["busName", ["BusTrip"], ["Text"], ""],
+ ["busNumber", ["BusTrip"], ["Text"], ""],
+ [
+ "businessDays",
+ ["ServicePeriod", "ShippingDeliveryTime"],
+ ["DayOfWeek", "OpeningHoursSpecification"],
+ "",
+ ],
+ [
+ "businessFunction",
+ ["Demand", "Offer", "TypeAndQuantityNode"],
+ ["BusinessFunction"],
+ "",
+ ],
+ ["buyer", ["SellAction"], ["Organization", "Person"], ""],
+ ["byArtist", ["MusicAlbum", "MusicRecording"], ["MusicGroup", "Person"], ""],
+ ["byDay", ["Schedule"], ["DayOfWeek", "Text"], ""],
+ ["byMonth", ["Schedule"], ["Integer"], ""],
+ ["byMonthDay", ["Schedule"], ["Integer"], ""],
+ ["byMonthWeek", ["Schedule"], ["Integer"], ""],
+ ["callSign", ["BroadcastService", "Person", "Vehicle"], ["Text"], ""],
+ ["calories", ["NutritionInformation"], ["Energy"], ""],
+ ["candidate", ["VoteAction"], ["Person"], ""],
+ [
+ "caption",
+ ["AudioObject", "ImageObject", "VideoObject"],
+ ["MediaObject", "Text"],
+ "",
+ ],
+ ["carbohydrateContent", ["NutritionInformation"], ["Mass"], ""],
+ ["cargoVolume", ["Vehicle"], ["QuantitativeValue"], ""],
+ ["carrier", ["Flight", "ParcelDelivery"], ["Organization"], "provider"],
+ ["carrierRequirements", ["MobileApplication"], ["Text"], ""],
+ ["cashBack", ["PaymentCard"], ["Boolean", "Number"], ""],
+ ["catalog", ["Dataset"], ["DataCatalog"], "includedInDataCatalog"],
+ ["catalogNumber", ["MusicRelease"], ["Text"], ""],
+ [
+ "category",
+ [
+ "ActionAccessSpecification",
+ "Guide",
+ "Invoice",
+ "Offer",
+ "PhysicalActivity",
+ "Product",
+ "Recommendation",
+ "Service",
+ "SpecialAnnouncement",
+ ],
+ ["CategoryCode", "PhysicalActivityCategory", "Text", "Thing", "URL"],
+ "",
+ ],
+ ["cause", ["MedicalCondition"], ["MedicalCause"], ""],
+ ["causeOf", ["MedicalCause"], ["MedicalEntity"], ""],
+ ["ccRecipient", ["Message"], ["ContactPoint", "Organization", "Person"], ""],
+ [
+ "certificationIdentification",
+ ["Certification"],
+ ["DefinedTerm", "Text"],
+ "",
+ ],
+ ["certificationRating", ["Certification"], ["Rating"], ""],
+ [
+ "certificationStatus",
+ ["Certification"],
+ ["CertificationStatusEnumeration"],
+ "",
+ ],
+ ["character", ["CreativeWork"], ["Person"], ""],
+ ["characterAttribute", ["Game", "VideoGameSeries"], ["Thing"], ""],
+ ["characterName", ["PerformanceRole"], ["Text"], ""],
+ ["cheatCode", ["VideoGame", "VideoGameSeries"], ["CreativeWork"], ""],
+ [
+ "checkinTime",
+ ["LodgingBusiness", "LodgingReservation"],
+ ["DateTime", "Time"],
+ "",
+ ],
+ ["checkoutPageURLTemplate", ["Offer"], ["Text"], ""],
+ [
+ "checkoutTime",
+ ["LodgingBusiness", "LodgingReservation"],
+ ["DateTime", "Time"],
+ "",
+ ],
+ ["chemicalComposition", ["ChemicalSubstance"], ["Text"], ""],
+ [
+ "chemicalRole",
+ ["ChemicalSubstance", "MolecularEntity"],
+ ["DefinedTerm"],
+ "",
+ ],
+ ["childMaxAge", ["ParentAudience"], ["Number"], ""],
+ ["childMinAge", ["ParentAudience"], ["Number"], ""],
+ ["childTaxon", ["Taxon"], ["Taxon", "Text", "URL"], ""],
+ ["children", ["Person"], ["Person"], ""],
+ ["cholesterolContent", ["NutritionInformation"], ["Mass"], ""],
+ ["circle", ["GeoShape"], ["Text"], ""],
+ ["citation", ["CreativeWork"], ["CreativeWork", "Text"], ""],
+ ["claimInterpreter", ["Claim"], ["Organization", "Person"], ""],
+ ["claimReviewed", ["ClaimReview"], ["Text"], ""],
+ ["clincalPharmacology", ["Drug"], ["Text"], "clinicalPharmacology"],
+ ["clinicalPharmacology", ["Drug"], ["Text"], ""],
+ ["clipNumber", ["Clip"], ["Integer", "Text"], ""],
+ ["closes", ["OpeningHoursSpecification"], ["Time"], ""],
+ ["coach", ["SportsTeam"], ["Person"], ""],
+ ["code", ["MedicalEntity"], ["MedicalCode"], ""],
+ ["codeRepository", ["SoftwareSourceCode"], ["URL"], ""],
+ ["codeSampleType", ["SoftwareSourceCode"], ["Text"], ""],
+ ["codeValue", ["CategoryCode", "MedicalCode"], ["Text"], ""],
+ ["codingSystem", ["MedicalCode"], ["Text"], ""],
+ ["colleague", ["Person"], ["Person", "URL"], ""],
+ ["colleagues", ["Person"], ["Person"], "colleague"],
+ ["collection", ["UpdateAction"], ["Thing"], "targetCollection"],
+ ["collectionSize", ["Collection"], ["Integer"], ""],
+ ["color", ["Product"], ["Text"], ""],
+ ["colorSwatch", ["Product"], ["ImageObject", "URL"], ""],
+ ["colorist", ["ComicIssue", "ComicStory", "VisualArtwork"], ["Person"], ""],
+ ["comment", ["CreativeWork", "RsvpAction"], ["Comment"], ""],
+ ["commentCount", ["CreativeWork"], ["Integer"], ""],
+ ["commentText", ["UserComments"], ["Text"], ""],
+ ["commentTime", ["UserComments"], ["Date", "DateTime"], ""],
+ ["companyRegistration", ["Organization"], ["Certification"], ""],
+ [
+ "competencyRequired",
+ ["EducationalOccupationalCredential", "LearningResource"],
+ ["DefinedTerm", "Text", "URL"],
+ "",
+ ],
+ ["competitor", ["SportsEvent"], ["Person", "SportsTeam"], ""],
+ ["composer", ["Event", "MusicComposition"], ["Organization", "Person"], ""],
+ [
+ "comprisedOf",
+ ["AnatomicalSystem"],
+ ["AnatomicalStructure", "AnatomicalSystem"],
+ "",
+ ],
+ ["conditionsOfAccess", ["CreativeWork"], ["Text"], ""],
+ ["confirmationNumber", ["Invoice", "Order"], ["Text"], ""],
+ ["connectedTo", ["AnatomicalStructure"], ["AnatomicalStructure"], ""],
+ ["constraintProperty", ["ConstraintNode"], ["Property", "URL"], ""],
+ ["contactOption", ["ContactPoint"], ["ContactPointOption"], ""],
+ [
+ "contactPoint",
+ ["HealthInsurancePlan", "Organization", "Person"],
+ ["ContactPoint"],
+ "",
+ ],
+ [
+ "contactPoints",
+ ["Organization", "Person"],
+ ["ContactPoint"],
+ "contactPoint",
+ ],
+ ["contactType", ["ContactPoint"], ["Text"], ""],
+ ["contactlessPayment", ["PaymentCard"], ["Boolean"], ""],
+ ["containedIn", ["Place"], ["Place"], "containedInPlace"],
+ ["containedInPlace", ["Place"], ["Place"], ""],
+ ["containsPlace", ["Place"], ["Place"], ""],
+ [
+ "containsSeason",
+ ["RadioSeries", "TVSeries", "VideoGameSeries"],
+ ["CreativeWorkSeason"],
+ "",
+ ],
+ ["contentLocation", ["CreativeWork"], ["Place"], ""],
+ ["contentRating", ["CreativeWork"], ["Rating", "Text"], ""],
+ ["contentReferenceTime", ["CreativeWork"], ["DateTime"], ""],
+ ["contentSize", ["MediaObject"], ["Text"], ""],
+ ["contentType", ["EntryPoint"], ["Text"], ""],
+ ["contentUrl", ["MediaObject"], ["URL"], ""],
+ [
+ "contraindication",
+ ["MedicalDevice", "MedicalTherapy"],
+ ["MedicalContraindication", "Text"],
+ "",
+ ],
+ ["contributor", ["CreativeWork", "Event"], ["Organization", "Person"], ""],
+ ["cookTime", ["Recipe"], ["Duration"], ""],
+ ["cookingMethod", ["Recipe"], ["Text"], ""],
+ ["copyrightHolder", ["CreativeWork"], ["Organization", "Person"], ""],
+ ["copyrightNotice", ["CreativeWork"], ["Text"], ""],
+ ["copyrightYear", ["CreativeWork"], ["Number"], ""],
+ ["correction", ["CreativeWork"], ["CorrectionComment", "Text", "URL"], ""],
+ [
+ "correctionsPolicy",
+ ["NewsMediaOrganization", "Organization"],
+ ["CreativeWork", "URL"],
+ "",
+ ],
+ ["costCategory", ["DrugCost"], ["DrugCostCategory"], ""],
+ ["costCurrency", ["DrugCost"], ["Text"], ""],
+ ["costOrigin", ["DrugCost"], ["Text"], ""],
+ ["costPerUnit", ["DrugCost"], ["Number", "QualitativeValue", "Text"], ""],
+ ["countriesNotSupported", ["SoftwareApplication"], ["Text"], ""],
+ ["countriesSupported", ["SoftwareApplication"], ["Text"], ""],
+ ["countryOfAssembly", ["Product"], ["Text"], ""],
+ ["countryOfLastProcessing", ["Product"], ["Text"], ""],
+ [
+ "countryOfOrigin",
+ ["CreativeWork", "Movie", "Product", "TVEpisode", "TVSeason", "TVSeries"],
+ ["Country"],
+ "",
+ ],
+ ["course", ["ExerciseAction"], ["Place"], "exerciseCourse"],
+ ["courseCode", ["Course"], ["Text"], ""],
+ ["courseMode", ["CourseInstance"], ["Text", "URL"], ""],
+ [
+ "coursePrerequisites",
+ ["Course"],
+ ["AlignmentObject", "Course", "Text"],
+ "",
+ ],
+ ["courseSchedule", ["CourseInstance"], ["Schedule"], ""],
+ ["courseWorkload", ["CourseInstance"], ["Text"], ""],
+ ["coverageEndTime", ["LiveBlogPosting"], ["DateTime"], ""],
+ ["coverageStartTime", ["LiveBlogPosting"], ["DateTime"], ""],
+ ["creativeWorkStatus", ["CreativeWork"], ["DefinedTerm", "Text"], ""],
+ ["creator", ["CreativeWork", "UserComments"], ["Organization", "Person"], ""],
+ ["credentialCategory", ["Credential"], ["DefinedTerm", "Text", "URL"], ""],
+ ["creditText", ["CreativeWork"], ["Text"], ""],
+ ["creditedTo", ["MusicRelease"], ["Organization", "Person"], ""],
+ [
+ "cssSelector",
+ ["SpeakableSpecification", "WebPageElement"],
+ ["CssSelectorType"],
+ "",
+ ],
+ ["currenciesAccepted", ["LocalBusiness"], ["Text"], ""],
+ [
+ "currency",
+ [
+ "DatedMoneySpecification",
+ "ExchangeRateSpecification",
+ "LoanOrCredit",
+ "MonetaryAmount",
+ "MonetaryAmountDistribution",
+ ],
+ ["Text"],
+ "",
+ ],
+ [
+ "currentExchangeRate",
+ ["ExchangeRateSpecification"],
+ ["UnitPriceSpecification"],
+ "",
+ ],
+ ["customer", ["Invoice", "Order"], ["Organization", "Person"], ""],
+ [
+ "customerRemorseReturnFees",
+ ["MerchantReturnPolicy"],
+ ["ReturnFeesEnumeration"],
+ "",
+ ],
+ [
+ "customerRemorseReturnLabelSource",
+ ["MerchantReturnPolicy"],
+ ["ReturnLabelSourceEnumeration"],
+ "",
+ ],
+ [
+ "customerRemorseReturnShippingFeesAmount",
+ ["MerchantReturnPolicy"],
+ ["MonetaryAmount"],
+ "",
+ ],
+ ["cutoffTime", ["ServicePeriod", "ShippingDeliveryTime"], ["Time"], ""],
+ ["cvdCollectionDate", ["CDCPMDRecord"], ["DateTime", "Text"], ""],
+ ["cvdFacilityCounty", ["CDCPMDRecord"], ["Text"], ""],
+ ["cvdFacilityId", ["CDCPMDRecord"], ["Text"], ""],
+ ["cvdNumBeds", ["CDCPMDRecord"], ["Number"], ""],
+ ["cvdNumBedsOcc", ["CDCPMDRecord"], ["Number"], ""],
+ ["cvdNumC19Died", ["CDCPMDRecord"], ["Number"], ""],
+ ["cvdNumC19HOPats", ["CDCPMDRecord"], ["Number"], ""],
+ ["cvdNumC19HospPats", ["CDCPMDRecord"], ["Number"], ""],
+ ["cvdNumC19MechVentPats", ["CDCPMDRecord"], ["Number"], ""],
+ ["cvdNumC19OFMechVentPats", ["CDCPMDRecord"], ["Number"], ""],
+ ["cvdNumC19OverflowPats", ["CDCPMDRecord"], ["Number"], ""],
+ ["cvdNumICUBeds", ["CDCPMDRecord"], ["Number"], ""],
+ ["cvdNumICUBedsOcc", ["CDCPMDRecord"], ["Number"], ""],
+ ["cvdNumTotBeds", ["CDCPMDRecord"], ["Number"], ""],
+ ["cvdNumVent", ["CDCPMDRecord"], ["Number"], ""],
+ ["cvdNumVentUse", ["CDCPMDRecord"], ["Number"], ""],
+ ["data", ["InstantaneousEvent"], ["Thing"], ""],
+ ["dataFeedElement", ["DataFeed"], ["DataFeedItem", "Text", "Thing"], ""],
+ ["dataset", ["DataCatalog"], ["Dataset"], ""],
+ ["datasetTimeInterval", ["Dataset"], ["DateTime"], "temporalCoverage"],
+ ["dateCreated", ["CreativeWork", "DataFeedItem"], ["Date", "DateTime"], ""],
+ ["dateDeleted", ["DataFeedItem"], ["Date", "DateTime"], ""],
+ ["dateIssued", ["Ticket"], ["Date", "DateTime"], ""],
+ ["dateModified", ["CreativeWork", "DataFeedItem"], ["Date", "DateTime"], ""],
+ [
+ "datePosted",
+ ["CDCPMDRecord", "JobPosting", "RealEstateListing", "SpecialAnnouncement"],
+ ["Date", "DateTime"],
+ "",
+ ],
+ [
+ "datePublished",
+ ["Certification", "CreativeWork"],
+ ["Date", "DateTime"],
+ "",
+ ],
+ ["dateRead", ["Message"], ["Date", "DateTime"], ""],
+ ["dateReceived", ["Message"], ["DateTime"], ""],
+ ["dateSent", ["Message"], ["DateTime"], ""],
+ ["dateVehicleFirstRegistered", ["Vehicle"], ["Date"], ""],
+ ["dateline", ["NewsArticle"], ["Text"], ""],
+ [
+ "dayOfWeek",
+ ["EducationalOccupationalProgram", "OpeningHoursSpecification"],
+ ["DayOfWeek"],
+ "",
+ ],
+ ["deathDate", ["Person"], ["Date"], ""],
+ ["deathPlace", ["Person"], ["Place"], ""],
+ ["defaultValue", ["PropertyValueSpecification"], ["Text", "Thing"], ""],
+ ["deliveryAddress", ["ParcelDelivery"], ["PostalAddress"], ""],
+ ["deliveryLeadTime", ["Demand", "Offer"], ["QuantitativeValue"], ""],
+ [
+ "deliveryMethod",
+ ["OrderAction", "ReceiveAction", "SendAction", "TrackAction"],
+ ["DeliveryMethod"],
+ "",
+ ],
+ ["deliveryStatus", ["ParcelDelivery"], ["DeliveryEvent"], ""],
+ [
+ "deliveryTime",
+ ["DeliveryTimeSettings", "OfferShippingDetails"],
+ ["ShippingDeliveryTime"],
+ "",
+ ],
+ ["department", ["Organization"], ["Organization"], ""],
+ ["departureAirport", ["Flight"], ["Airport"], ""],
+ ["departureBoatTerminal", ["BoatTrip"], ["BoatTerminal"], ""],
+ ["departureBusStop", ["BusTrip"], ["BusStation", "BusStop"], ""],
+ ["departureGate", ["Flight"], ["Text"], ""],
+ ["departurePlatform", ["TrainTrip"], ["Text"], ""],
+ ["departureStation", ["TrainTrip"], ["TrainStation"], ""],
+ ["departureTerminal", ["Flight"], ["Text"], ""],
+ ["departureTime", ["Trip"], ["DateTime", "Time"], ""],
+ ["dependencies", ["TechArticle"], ["Text"], ""],
+ [
+ "depth",
+ ["OfferShippingDetails", "Product", "ShippingConditions", "VisualArtwork"],
+ ["Distance", "QuantitativeValue"],
+ "",
+ ],
+ ["description", ["Thing"], ["Text", "TextObject"], ""],
+ ["device", ["SoftwareApplication"], ["Text"], "availableOnDevice"],
+ ["diagnosis", ["DDxElement", "Patient"], ["MedicalCondition"], ""],
+ ["diagram", ["AnatomicalStructure"], ["ImageObject"], ""],
+ ["diet", ["ExerciseAction"], ["Diet"], ""],
+ ["dietFeatures", ["Diet"], ["Text"], ""],
+ ["differentialDiagnosis", ["MedicalCondition"], ["DDxElement"], ""],
+ ["digitalSourceType", ["CreativeWork"], ["IPTCDigitalSourceEnumeration"], ""],
+ ["directApply", ["JobPosting"], ["Boolean"], ""],
+ [
+ "director",
+ [
+ "Clip",
+ "CreativeWorkSeason",
+ "Episode",
+ "Event",
+ "Movie",
+ "MovieSeries",
+ "RadioSeries",
+ "TVSeries",
+ "VideoGame",
+ "VideoGameSeries",
+ "VideoObject",
+ ],
+ ["Person"],
+ "",
+ ],
+ [
+ "directors",
+ [
+ "Clip",
+ "Episode",
+ "Movie",
+ "MovieSeries",
+ "RadioSeries",
+ "TVSeries",
+ "VideoGame",
+ "VideoGameSeries",
+ "VideoObject",
+ ],
+ ["Person"],
+ "director",
+ ],
+ ["disambiguatingDescription", ["Thing"], ["Text"], ""],
+ ["discount", ["Order"], ["Number", "Text"], ""],
+ ["discountCode", ["Order"], ["Text"], ""],
+ ["discountCurrency", ["Order"], ["Text"], ""],
+ ["discusses", ["UserComments"], ["CreativeWork"], ""],
+ ["discussionUrl", ["CreativeWork"], ["URL"], ""],
+ ["diseasePreventionInfo", ["SpecialAnnouncement"], ["URL", "WebContent"], ""],
+ [
+ "diseaseSpreadStatistics",
+ ["SpecialAnnouncement"],
+ ["Dataset", "Observation", "URL", "WebContent"],
+ "",
+ ],
+ ["displayLocation", ["CreativeWork", "Product"], ["Place"], ""],
+ ["dissolutionDate", ["Organization"], ["Date"], ""],
+ ["distance", ["ExerciseAction", "TravelAction"], ["Distance"], ""],
+ ["distinguishingSign", ["DDxElement"], ["MedicalSignOrSymptom"], ""],
+ ["distribution", ["Dataset"], ["DataDownload"], ""],
+ [
+ "diversityPolicy",
+ ["NewsMediaOrganization", "Organization"],
+ ["CreativeWork", "URL"],
+ "",
+ ],
+ [
+ "diversityStaffingReport",
+ ["NewsMediaOrganization", "Organization"],
+ ["Article", "URL"],
+ "",
+ ],
+ ["documentation", ["WebAPI"], ["CreativeWork", "URL"], ""],
+ [
+ "doesNotShip",
+ ["OfferShippingDetails", "ShippingConditions", "ShippingRateSettings"],
+ ["Boolean"],
+ "",
+ ],
+ ["domainIncludes", ["Property"], ["Class"], ""],
+ ["domiciledMortgage", ["MortgageLoan"], ["Boolean"], ""],
+ ["doorTime", ["Event"], ["DateTime", "Time"], ""],
+ ["dosageForm", ["Drug"], ["Text"], ""],
+ ["doseSchedule", ["Drug", "TherapeuticProcedure"], ["DoseSchedule"], ""],
+ ["doseUnit", ["DoseSchedule"], ["Text"], ""],
+ ["doseValue", ["DoseSchedule"], ["Number", "QualitativeValue"], ""],
+ ["downPayment", ["RepaymentSpecification"], ["MonetaryAmount", "Number"], ""],
+ ["downloadUrl", ["SoftwareApplication"], ["URL"], ""],
+ ["downvoteCount", ["Comment"], ["Integer"], ""],
+ ["drainsTo", ["Vein"], ["Vessel"], ""],
+ [
+ "driveWheelConfiguration",
+ ["Vehicle"],
+ ["DriveWheelConfigurationValue", "Text"],
+ "",
+ ],
+ ["dropoffLocation", ["RentalCarReservation"], ["Place"], ""],
+ ["dropoffTime", ["RentalCarReservation"], ["DateTime"], ""],
+ [
+ "drug",
+ ["DrugClass", "MedicalCondition", "Patient", "TherapeuticProcedure"],
+ ["Drug"],
+ "",
+ ],
+ ["drugClass", ["Drug"], ["DrugClass"], ""],
+ ["drugUnit", ["Drug", "DrugCost"], ["Text"], ""],
+ ["duns", ["Organization", "Person"], ["Text"], ""],
+ ["duplicateTherapy", ["MedicalTherapy"], ["MedicalTherapy"], ""],
+ [
+ "duration",
+ [
+ "Audiobook",
+ "Episode",
+ "Event",
+ "MediaObject",
+ "Movie",
+ "MusicRecording",
+ "MusicRelease",
+ "QuantitativeValueDistribution",
+ "Schedule",
+ "ServicePeriod",
+ ],
+ ["Duration", "QuantitativeValue"],
+ "",
+ ],
+ ["durationOfWarranty", ["WarrantyPromise"], ["QuantitativeValue"], ""],
+ ["duringMedia", ["HowToDirection"], ["MediaObject", "URL"], ""],
+ [
+ "earlyPrepaymentPenalty",
+ ["RepaymentSpecification"],
+ ["MonetaryAmount"],
+ "",
+ ],
+ ["editEIDR", ["CreativeWork"], ["Text", "URL"], ""],
+ ["editor", ["CreativeWork"], ["Person"], ""],
+ ["eduQuestionType", ["Question", "SolveMathAction"], ["Text"], ""],
+ [
+ "educationRequirements",
+ ["JobPosting", "Occupation"],
+ ["EducationalOccupationalCredential", "Text"],
+ "",
+ ],
+ [
+ "educationalAlignment",
+ ["CreativeWork", "LearningResource"],
+ ["AlignmentObject"],
+ "",
+ ],
+ [
+ "educationalCredentialAwarded",
+ ["Course", "EducationalOccupationalProgram"],
+ ["EducationalOccupationalCredential", "Text", "URL"],
+ "",
+ ],
+ ["educationalFramework", ["AlignmentObject"], ["Text"], ""],
+ [
+ "educationalLevel",
+ [
+ "CreativeWork",
+ "EducationEvent",
+ "EducationalOccupationalCredential",
+ "LearningResource",
+ ],
+ ["DefinedTerm", "Text", "URL"],
+ "",
+ ],
+ [
+ "educationalProgramMode",
+ ["EducationalOccupationalProgram"],
+ ["Text", "URL"],
+ "",
+ ],
+ ["educationalRole", ["EducationalAudience"], ["Text"], ""],
+ [
+ "educationalUse",
+ ["CreativeWork", "LearningResource"],
+ ["DefinedTerm", "Text"],
+ "",
+ ],
+ ["elevation", ["GeoCoordinates", "GeoShape"], ["Number", "Text"], ""],
+ ["eligibilityToWorkRequirement", ["JobPosting"], ["Text"], ""],
+ ["eligibleCustomerType", ["Demand", "Offer"], ["BusinessEntityType"], ""],
+ ["eligibleDuration", ["Demand", "Offer"], ["QuantitativeValue"], ""],
+ [
+ "eligibleQuantity",
+ ["Demand", "Offer", "PriceSpecification"],
+ ["QuantitativeValue"],
+ "",
+ ],
+ [
+ "eligibleRegion",
+ [
+ "ActionAccessSpecification",
+ "DeliveryChargeSpecification",
+ "Demand",
+ "Offer",
+ ],
+ ["GeoShape", "Place", "Text"],
+ "",
+ ],
+ [
+ "eligibleTransactionVolume",
+ ["Demand", "Offer", "PriceSpecification"],
+ ["PriceSpecification"],
+ "",
+ ],
+ ["eligibleWithSupplier", ["FinancialIncentive"], ["Organization"], ""],
+ ["email", ["ContactPoint", "Organization", "Person"], ["Text"], ""],
+ ["embedUrl", ["MediaObject"], ["URL"], ""],
+ [
+ "embeddedTextCaption",
+ ["AudioObject", "ImageObject", "VideoObject"],
+ ["Text"],
+ "",
+ ],
+ ["emissionsCO2", ["Vehicle"], ["Number"], ""],
+ ["employee", ["Organization"], ["Person"], ""],
+ ["employees", ["Organization"], ["Person"], "employee"],
+ ["employerOverview", ["JobPosting"], ["Text"], ""],
+ ["employmentType", ["JobPosting"], ["Text"], ""],
+ ["employmentUnit", ["JobPosting"], ["Organization"], ""],
+ ["encodesBioChemEntity", ["Gene"], ["BioChemEntity"], ""],
+ ["encodesCreativeWork", ["MediaObject"], ["CreativeWork"], ""],
+ ["encoding", ["CreativeWork"], ["MediaObject"], ""],
+ ["encodingFormat", ["CreativeWork", "MediaObject"], ["Text", "URL"], ""],
+ ["encodingType", ["EntryPoint"], ["Text"], ""],
+ ["encodings", ["CreativeWork"], ["MediaObject"], "encoding"],
+ [
+ "endDate",
+ [
+ "CreativeWorkSeason",
+ "CreativeWorkSeries",
+ "DatedMoneySpecification",
+ "EducationalOccupationalProgram",
+ "Event",
+ "MerchantReturnPolicySeasonalOverride",
+ "Role",
+ "Schedule",
+ ],
+ ["Date", "DateTime"],
+ "",
+ ],
+ ["endOffset", ["Clip"], ["HyperTocEntry", "Number"], ""],
+ [
+ "endTime",
+ [
+ "Action",
+ "FoodEstablishmentReservation",
+ "InteractionCounter",
+ "MediaObject",
+ "Schedule",
+ ],
+ ["DateTime", "Time"],
+ "",
+ ],
+ ["endorsee", ["EndorseAction"], ["Organization", "Person"], ""],
+ ["endorsers", ["Diet"], ["Organization", "Person"], ""],
+ [
+ "energyEfficiencyScaleMax",
+ ["EnergyConsumptionDetails"],
+ ["EUEnergyEfficiencyEnumeration"],
+ "",
+ ],
+ [
+ "energyEfficiencyScaleMin",
+ ["EnergyConsumptionDetails"],
+ ["EUEnergyEfficiencyEnumeration"],
+ "",
+ ],
+ ["engineDisplacement", ["EngineSpecification"], ["QuantitativeValue"], ""],
+ ["enginePower", ["EngineSpecification"], ["QuantitativeValue"], ""],
+ [
+ "engineType",
+ ["EngineSpecification"],
+ ["QualitativeValue", "Text", "URL"],
+ "",
+ ],
+ ["entertainmentBusiness", ["PerformAction"], ["EntertainmentBusiness"], ""],
+ ["epidemiology", ["MedicalCondition", "PhysicalActivity"], ["Text"], ""],
+ [
+ "episode",
+ ["CreativeWorkSeason", "RadioSeries", "TVSeries", "VideoGameSeries"],
+ ["Episode"],
+ "",
+ ],
+ ["episodeNumber", ["Episode"], ["Integer", "Text"], ""],
+ [
+ "episodes",
+ ["CreativeWorkSeason", "RadioSeries", "TVSeries", "VideoGameSeries"],
+ ["Episode"],
+ "episode",
+ ],
+ ["equal", ["QualitativeValue"], ["QualitativeValue"], ""],
+ ["error", ["Action"], ["Thing"], ""],
+ [
+ "errorCode",
+ ["Error"],
+ ["DefinedTerm", "Integer", "StatusEnumeration", "Text"],
+ "",
+ ],
+ ["estimatedCost", ["HowTo", "HowToSupply"], ["MonetaryAmount", "Text"], ""],
+ ["estimatedFlightDuration", ["Flight"], ["Duration", "Text"], ""],
+ [
+ "estimatedSalary",
+ ["JobPosting", "Occupation"],
+ ["MonetaryAmount", "MonetaryAmountDistribution", "Number"],
+ "",
+ ],
+ ["estimatesRiskOf", ["MedicalRiskEstimator"], ["MedicalEntity"], ""],
+ [
+ "ethicsPolicy",
+ ["NewsMediaOrganization", "Organization"],
+ ["CreativeWork", "URL"],
+ "",
+ ],
+ [
+ "event",
+ [
+ "InformAction",
+ "InviteAction",
+ "JoinAction",
+ "LeaveAction",
+ "Organization",
+ "Place",
+ "PlayAction",
+ ],
+ ["Event"],
+ "",
+ ],
+ ["eventAttendanceMode", ["Event"], ["EventAttendanceModeEnumeration"], ""],
+ ["eventSchedule", ["Event"], ["Schedule"], ""],
+ ["eventStatus", ["Event"], ["EventStatusType"], ""],
+ ["events", ["Organization", "Place"], ["Event"], "event"],
+ ["evidenceLevel", ["MedicalGuideline"], ["MedicalEvidenceLevel"], ""],
+ ["evidenceOrigin", ["MedicalGuideline"], ["Text"], ""],
+ ["exampleOfWork", ["CreativeWork"], ["CreativeWork"], ""],
+ ["exceptDate", ["Schedule"], ["Date", "DateTime"], ""],
+ [
+ "exchangeRateSpread",
+ ["ExchangeRateSpecification"],
+ ["MonetaryAmount", "Number"],
+ "",
+ ],
+ ["executableLibraryName", ["APIReference"], ["Text"], ""],
+ ["exerciseCourse", ["ExerciseAction"], ["Place"], ""],
+ ["exercisePlan", ["ExerciseAction"], ["ExercisePlan"], ""],
+ ["exerciseRelatedDiet", ["ExerciseAction"], ["Diet"], ""],
+ ["exerciseType", ["ExerciseAction", "ExercisePlan"], ["Text"], ""],
+ ["exifData", ["ImageObject"], ["PropertyValue", "Text"], ""],
+ ["expectedArrivalFrom", ["ParcelDelivery"], ["Date", "DateTime"], ""],
+ ["expectedArrivalUntil", ["ParcelDelivery"], ["Date", "DateTime"], ""],
+ ["expectedPrognosis", ["MedicalCondition"], ["Text"], ""],
+ [
+ "expectsAcceptanceOf",
+ ["ActionAccessSpecification", "ConsumeAction", "MediaSubscription"],
+ ["Offer"],
+ "",
+ ],
+ ["experienceInPlaceOfEducation", ["JobPosting"], ["Boolean"], ""],
+ [
+ "experienceRequirements",
+ ["JobPosting", "Occupation"],
+ ["OccupationalExperienceRequirements", "Text"],
+ "",
+ ],
+ ["expertConsiderations", ["Diet"], ["Text"], ""],
+ ["expires", ["Certification", "CreativeWork"], ["Date", "DateTime"], ""],
+ [
+ "expressedIn",
+ ["Gene"],
+ ["AnatomicalStructure", "AnatomicalSystem", "BioChemEntity", "DefinedTerm"],
+ "",
+ ],
+ ["extendedAddress", ["PostalAddress"], ["Text"], ""],
+ ["familyName", ["Person"], ["Text"], ""],
+ ["fatContent", ["NutritionInformation"], ["Mass"], ""],
+ [
+ "faxNumber",
+ ["ContactPoint", "Organization", "Person", "Place"],
+ ["Text"],
+ "",
+ ],
+ ["featureList", ["SoftwareApplication"], ["Text", "URL"], ""],
+ [
+ "feesAndCommissionsSpecification",
+ ["FinancialProduct", "FinancialService"],
+ ["Text", "URL"],
+ "",
+ ],
+ ["fiberContent", ["NutritionInformation"], ["Mass"], ""],
+ ["fileFormat", ["CreativeWork"], ["Text", "URL"], "encodingFormat"],
+ ["fileSize", ["SoftwareApplication"], ["Text"], ""],
+ [
+ "financialAidEligible",
+ ["Course", "EducationalOccupationalProgram"],
+ ["DefinedTerm", "Text"],
+ "",
+ ],
+ ["firstAppearance", ["Claim"], ["CreativeWork"], ""],
+ ["firstPerformance", ["MusicComposition"], ["Event"], ""],
+ ["flightDistance", ["Flight"], ["Distance", "Text"], ""],
+ ["flightNumber", ["Flight"], ["Text"], ""],
+ ["floorLevel", ["Accommodation", "LocalBusiness", "Residence"], ["Text"], ""],
+ ["floorLimit", ["PaymentCard"], ["MonetaryAmount"], ""],
+ ["floorSize", ["Accommodation", "FloorPlan"], ["QuantitativeValue"], ""],
+ ["followee", ["FollowAction"], ["Organization", "Person"], ""],
+ ["follows", ["Person"], ["Person"], ""],
+ ["followup", ["MedicalProcedure"], ["Text"], ""],
+ ["foodEstablishment", ["CookAction"], ["FoodEstablishment", "Place"], ""],
+ ["foodEvent", ["CookAction"], ["FoodEvent"], ""],
+ ["foodWarning", ["Drug"], ["Text"], ""],
+ ["founder", ["Organization"], ["Organization", "Person"], ""],
+ ["founders", ["Organization"], ["Person"], "founder"],
+ ["foundingDate", ["Organization"], ["Date"], ""],
+ ["foundingLocation", ["Organization"], ["Place"], ""],
+ ["free", ["PublicationEvent"], ["Boolean"], "isAccessibleForFree"],
+ [
+ "freeShippingThreshold",
+ ["ShippingRateSettings"],
+ ["DeliveryChargeSpecification", "MonetaryAmount"],
+ "",
+ ],
+ ["frequency", ["DoseSchedule"], ["Text"], ""],
+ [
+ "fromLocation",
+ ["ExerciseAction", "MoveAction", "TransferAction"],
+ ["Place"],
+ "",
+ ],
+ ["fuelCapacity", ["Vehicle"], ["QuantitativeValue"], ""],
+ ["fuelConsumption", ["Vehicle"], ["QuantitativeValue"], ""],
+ ["fuelEfficiency", ["Vehicle"], ["QuantitativeValue"], ""],
+ [
+ "fuelType",
+ ["EngineSpecification", "Vehicle"],
+ ["QualitativeValue", "Text", "URL"],
+ "",
+ ],
+ ["fulfillmentType", ["ShippingService"], ["FulfillmentTypeEnumeration"], ""],
+ ["functionalClass", ["Joint"], ["MedicalEntity", "Text"], ""],
+ [
+ "fundedItem",
+ ["Grant"],
+ [
+ "BioChemEntity",
+ "CreativeWork",
+ "Event",
+ "MedicalEntity",
+ "Organization",
+ "Person",
+ "Product",
+ ],
+ "",
+ ],
+ [
+ "funder",
+ [
+ "CreativeWork",
+ "Event",
+ "Grant",
+ "MonetaryGrant",
+ "Organization",
+ "Person",
+ ],
+ ["Organization", "Person"],
+ "",
+ ],
+ [
+ "funding",
+ [
+ "BioChemEntity",
+ "CreativeWork",
+ "Event",
+ "MedicalEntity",
+ "Organization",
+ "Person",
+ "Product",
+ ],
+ ["Grant"],
+ "",
+ ],
+ ["game", ["GameServer"], ["VideoGame"], ""],
+ [
+ "gameAvailabilityType",
+ ["PlayGameAction"],
+ ["GameAvailabilityEnumeration", "Text"],
+ "",
+ ],
+ ["gameEdition", ["VideoGame"], ["Text"], ""],
+ ["gameItem", ["Game", "VideoGameSeries"], ["Thing"], ""],
+ [
+ "gameLocation",
+ ["Game", "VideoGameSeries"],
+ ["Place", "PostalAddress", "URL"],
+ "",
+ ],
+ [
+ "gamePlatform",
+ ["VideoGame", "VideoGameSeries"],
+ ["Text", "Thing", "URL"],
+ "",
+ ],
+ ["gameServer", ["VideoGame"], ["GameServer"], ""],
+ ["gameTip", ["VideoGame"], ["CreativeWork"], ""],
+ ["gender", ["Person", "SportsTeam"], ["GenderType", "Text"], ""],
+ [
+ "genre",
+ ["BroadcastChannel", "CreativeWork", "MusicGroup"],
+ ["DefinedTerm", "Text", "URL"],
+ "",
+ ],
+ ["geo", ["Place"], ["GeoCoordinates", "GeoShape"], ""],
+ [
+ "geoContains",
+ ["GeospatialGeometry", "Place"],
+ ["GeospatialGeometry", "Place"],
+ "",
+ ],
+ [
+ "geoCoveredBy",
+ ["GeospatialGeometry", "Place"],
+ ["GeospatialGeometry", "Place"],
+ "",
+ ],
+ [
+ "geoCovers",
+ ["GeospatialGeometry", "Place"],
+ ["GeospatialGeometry", "Place"],
+ "",
+ ],
+ [
+ "geoCrosses",
+ ["GeospatialGeometry", "Place"],
+ ["GeospatialGeometry", "Place"],
+ "",
+ ],
+ [
+ "geoDisjoint",
+ ["GeospatialGeometry", "Place"],
+ ["GeospatialGeometry", "Place"],
+ "",
+ ],
+ [
+ "geoEquals",
+ ["GeospatialGeometry", "Place"],
+ ["GeospatialGeometry", "Place"],
+ "",
+ ],
+ [
+ "geoIntersects",
+ ["GeospatialGeometry", "Place"],
+ ["GeospatialGeometry", "Place"],
+ "",
+ ],
+ ["geoMidpoint", ["GeoCircle"], ["GeoCoordinates"], ""],
+ [
+ "geoOverlaps",
+ ["GeospatialGeometry", "Place"],
+ ["GeospatialGeometry", "Place"],
+ "",
+ ],
+ ["geoRadius", ["GeoCircle"], ["Distance", "Number", "Text"], ""],
+ [
+ "geoTouches",
+ ["GeospatialGeometry", "Place"],
+ ["GeospatialGeometry", "Place"],
+ "",
+ ],
+ [
+ "geoWithin",
+ ["GeospatialGeometry", "Place"],
+ ["GeospatialGeometry", "Place"],
+ "",
+ ],
+ ["geographicArea", ["Audience"], ["AdministrativeArea"], ""],
+ ["gettingTestedInfo", ["SpecialAnnouncement"], ["URL", "WebContent"], ""],
+ ["givenName", ["Person"], ["Text"], ""],
+ ["globalLocationNumber", ["Organization", "Person", "Place"], ["Text"], ""],
+ [
+ "governmentBenefitsInfo",
+ ["SpecialAnnouncement"],
+ ["GovernmentService"],
+ "",
+ ],
+ ["gracePeriod", ["LoanOrCredit"], ["Duration"], ""],
+ [
+ "grantee",
+ ["DigitalDocumentPermission"],
+ ["Audience", "ContactPoint", "Organization", "Person"],
+ "",
+ ],
+ ["greater", ["QualitativeValue"], ["QualitativeValue"], ""],
+ ["greaterOrEqual", ["QualitativeValue"], ["QualitativeValue"], ""],
+ ["gtin", ["Demand", "Offer", "Product"], ["Text", "URL"], ""],
+ ["gtin12", ["Demand", "Offer", "Product"], ["Text"], ""],
+ ["gtin13", ["Demand", "Offer", "Product"], ["Text"], ""],
+ ["gtin14", ["Demand", "Offer", "Product"], ["Text"], ""],
+ ["gtin8", ["Demand", "Offer", "Product"], ["Text"], ""],
+ ["guideline", ["MedicalEntity"], ["MedicalGuideline"], ""],
+ ["guidelineDate", ["MedicalGuideline"], ["Date"], ""],
+ ["guidelineSubject", ["MedicalGuideline"], ["MedicalEntity"], ""],
+ [
+ "handlingTime",
+ ["ShippingDeliveryTime", "ShippingService"],
+ ["QuantitativeValue", "ServicePeriod"],
+ "",
+ ],
+ [
+ "hasAdultConsideration",
+ ["Offer", "Product"],
+ ["AdultOrientedEnumeration"],
+ "",
+ ],
+ ["hasBioChemEntityPart", ["BioChemEntity"], ["BioChemEntity"], ""],
+ ["hasBioPolymerSequence", ["Gene", "Protein"], ["Text"], ""],
+ ["hasBroadcastChannel", ["BroadcastService"], ["BroadcastChannel"], ""],
+ ["hasCategoryCode", ["CategoryCodeSet"], ["CategoryCode"], ""],
+ [
+ "hasCertification",
+ ["Organization", "Person", "Place", "Product", "Service"],
+ ["Certification"],
+ "",
+ ],
+ ["hasCourse", ["EducationalOccupationalProgram"], ["Course"], ""],
+ ["hasCourseInstance", ["Course"], ["CourseInstance"], ""],
+ ["hasCredential", ["Organization", "Person"], ["Credential"], ""],
+ ["hasDefinedTerm", ["DefinedTermSet", "Taxon"], ["DefinedTerm"], ""],
+ [
+ "hasDeliveryMethod",
+ ["DeliveryEvent", "ParcelDelivery"],
+ ["DeliveryMethod"],
+ "",
+ ],
+ [
+ "hasDigitalDocumentPermission",
+ ["DigitalDocument"],
+ ["DigitalDocumentPermission"],
+ "",
+ ],
+ ["hasDriveThroughService", ["Place"], ["Boolean"], ""],
+ [
+ "hasEnergyConsumptionDetails",
+ ["Product"],
+ ["EnergyConsumptionDetails"],
+ "",
+ ],
+ [
+ "hasEnergyEfficiencyCategory",
+ ["EnergyConsumptionDetails"],
+ ["EnergyEfficiencyEnumeration"],
+ "",
+ ],
+ [
+ "hasGS1DigitalLink",
+ ["Offer", "Organization", "Place", "Product"],
+ ["URL"],
+ "",
+ ],
+ ["hasHealthAspect", ["HealthTopicContent"], ["HealthAspectEnumeration"], ""],
+ ["hasMap", ["Place"], ["Map", "URL"], ""],
+ [
+ "hasMeasurement",
+ ["Certification", "Offer", "Product", "SizeSpecification"],
+ ["QuantitativeValue"],
+ "",
+ ],
+ ["hasMemberProgram", ["Organization"], ["MemberProgram"], ""],
+ ["hasMenu", ["FoodEstablishment"], ["Menu", "Text", "URL"], ""],
+ ["hasMenuItem", ["Menu", "MenuSection"], ["MenuItem"], ""],
+ ["hasMenuSection", ["Menu", "MenuSection"], ["MenuSection"], ""],
+ [
+ "hasMerchantReturnPolicy",
+ ["Offer", "Organization", "Product"],
+ ["MerchantReturnPolicy"],
+ "",
+ ],
+ [
+ "hasMolecularFunction",
+ ["BioChemEntity"],
+ ["DefinedTerm", "PropertyValue", "URL"],
+ "",
+ ],
+ ["hasOccupation", ["Person"], ["Occupation"], ""],
+ [
+ "hasOfferCatalog",
+ ["Organization", "Person", "Service"],
+ ["OfferCatalog"],
+ "",
+ ],
+ ["hasPOS", ["Organization", "Person"], ["Place"], ""],
+ ["hasPart", ["CreativeWork"], ["CreativeWork"], ""],
+ ["hasParticipationOffer", ["Event"], ["Offer"], ""],
+ [
+ "hasRepresentation",
+ ["BioChemEntity"],
+ ["PropertyValue", "Text", "URL"],
+ "",
+ ],
+ [
+ "hasShippingService",
+ ["OfferShippingDetails", "Organization"],
+ ["ShippingService"],
+ "",
+ ],
+ ["hasSponsorshipOffer", ["Event"], ["Offer"], ""],
+ ["hasStore", ["OnlineMarketplace"], ["OnlineStore"], ""],
+ ["hasTierBenefit", ["MemberProgramTier"], ["TierBenefitEnumeration"], ""],
+ [
+ "hasTierRequirement",
+ ["MemberProgramTier"],
+ ["CreditCard", "MonetaryAmount", "Text", "UnitPriceSpecification"],
+ "",
+ ],
+ ["hasTiers", ["MemberProgram"], ["MemberProgramTier"], ""],
+ ["hasVariant", ["ProductGroup"], ["Product"], ""],
+ ["headline", ["CreativeWork"], ["Text"], ""],
+ [
+ "healthCondition",
+ ["MedicalStudy", "Patient", "PeopleAudience"],
+ ["MedicalCondition"],
+ "",
+ ],
+ [
+ "healthPlanCoinsuranceOption",
+ ["HealthPlanCostSharingSpecification"],
+ ["Text"],
+ "",
+ ],
+ [
+ "healthPlanCoinsuranceRate",
+ ["HealthPlanCostSharingSpecification"],
+ ["Number"],
+ "",
+ ],
+ [
+ "healthPlanCopay",
+ ["HealthPlanCostSharingSpecification"],
+ ["PriceSpecification"],
+ "",
+ ],
+ [
+ "healthPlanCopayOption",
+ ["HealthPlanCostSharingSpecification"],
+ ["Text"],
+ "",
+ ],
+ [
+ "healthPlanCostSharing",
+ ["HealthPlanFormulary", "HealthPlanNetwork"],
+ ["Boolean", "HealthPlanCostSharingSpecification"],
+ "",
+ ],
+ ["healthPlanDrugOption", ["HealthInsurancePlan"], ["Text"], ""],
+ [
+ "healthPlanDrugTier",
+ ["HealthInsurancePlan", "HealthPlanFormulary"],
+ ["Text"],
+ "",
+ ],
+ ["healthPlanId", ["HealthInsurancePlan"], ["Text"], ""],
+ ["healthPlanMarketingUrl", ["HealthInsurancePlan"], ["URL"], ""],
+ [
+ "healthPlanNetworkId",
+ ["HealthPlanNetwork", "MedicalOrganization"],
+ ["Text"],
+ "",
+ ],
+ ["healthPlanNetworkTier", ["HealthPlanNetwork"], ["Text"], ""],
+ [
+ "healthPlanPharmacyCategory",
+ ["HealthPlanCostSharingSpecification"],
+ ["Text"],
+ "",
+ ],
+ ["healthcareReportingData", ["Hospital"], ["CDCPMDRecord", "Dataset"], ""],
+ [
+ "height",
+ [
+ "MediaObject",
+ "OfferShippingDetails",
+ "Person",
+ "Product",
+ "ShippingConditions",
+ "VisualArtwork",
+ ],
+ ["Distance", "QuantitativeValue"],
+ "",
+ ],
+ ["highPrice", ["AggregateOffer"], ["Number", "Text"], ""],
+ ["hiringOrganization", ["JobPosting"], ["Organization", "Person"], ""],
+ ["holdingArchive", ["ArchiveComponent"], ["ArchiveOrganization"], ""],
+ ["homeLocation", ["Person"], ["ContactPoint", "Place"], ""],
+ ["homeTeam", ["SportsEvent"], ["Person", "SportsTeam"], ""],
+ ["honorificPrefix", ["Person"], ["Text"], ""],
+ ["honorificSuffix", ["Person"], ["Text"], ""],
+ ["hospitalAffiliation", ["Physician"], ["Hospital"], ""],
+ [
+ "hostingOrganization",
+ ["MemberProgram", "ProgramMembership"],
+ ["Organization"],
+ "",
+ ],
+ [
+ "hoursAvailable",
+ ["ContactPoint", "LocationFeatureSpecification", "Service"],
+ ["OpeningHoursSpecification"],
+ "",
+ ],
+ ["howPerformed", ["MedicalProcedure"], ["Text"], ""],
+ ["httpMethod", ["EntryPoint"], ["Text"], ""],
+ ["iataCode", ["Airline", "Airport"], ["Text"], ""],
+ ["icaoCode", ["Airport"], ["Text"], ""],
+ ["identifier", ["Thing"], ["PropertyValue", "Text", "URL"], ""],
+ ["identifyingExam", ["MedicalSign"], ["PhysicalExam"], ""],
+ ["identifyingTest", ["MedicalSign"], ["MedicalTest"], ""],
+ ["illustrator", ["Book"], ["Person"], ""],
+ ["image", ["Thing"], ["ImageObject", "URL"], ""],
+ ["imagingTechnique", ["ImagingTest"], ["MedicalImagingTechnique"], ""],
+ ["inAlbum", ["MusicRecording"], ["MusicAlbum"], ""],
+ ["inBroadcastLineup", ["BroadcastChannel"], ["CableOrSatelliteService"], ""],
+ ["inChI", ["MolecularEntity"], ["Text"], ""],
+ ["inChIKey", ["MolecularEntity"], ["Text"], ""],
+ ["inCodeSet", ["CategoryCode"], ["CategoryCodeSet", "URL"], ""],
+ ["inDefinedTermSet", ["DefinedTerm"], ["DefinedTermSet", "URL"], ""],
+ [
+ "inLanguage",
+ [
+ "BroadcastService",
+ "CommunicateAction",
+ "CreativeWork",
+ "Event",
+ "LinkRole",
+ "PronounceableText",
+ "WriteAction",
+ ],
+ ["Language", "Text"],
+ "",
+ ],
+ ["inPlaylist", ["MusicRecording"], ["MusicPlaylist"], ""],
+ ["inProductGroupWithID", ["Product"], ["Text"], ""],
+ ["inStoreReturnsOffered", ["MerchantReturnPolicy"], ["Boolean"], ""],
+ ["inSupportOf", ["Thesis"], ["Text"], ""],
+ [
+ "incentiveAmount",
+ ["FinancialIncentive"],
+ ["LoanOrCredit", "QuantitativeValue", "UnitPriceSpecification"],
+ "",
+ ],
+ ["incentiveCompensation", ["JobPosting"], ["Text"], ""],
+ ["incentiveStatus", ["FinancialIncentive"], ["IncentiveStatus"], ""],
+ ["incentiveType", ["FinancialIncentive"], ["IncentiveType"], ""],
+ ["incentives", ["JobPosting"], ["Text"], "incentiveCompensation"],
+ ["incentivizedItem", ["FinancialIncentive"], ["DefinedTerm", "Product"], ""],
+ ["includedComposition", ["MusicComposition"], ["MusicComposition"], ""],
+ [
+ "includedDataCatalog",
+ ["Dataset"],
+ ["DataCatalog"],
+ "includedInDataCatalog",
+ ],
+ ["includedInDataCatalog", ["Dataset"], ["DataCatalog"], ""],
+ ["includedInHealthInsurancePlan", ["Drug"], ["HealthInsurancePlan"], ""],
+ ["includedRiskFactor", ["MedicalRiskEstimator"], ["MedicalRiskFactor"], ""],
+ ["includesAttraction", ["TouristDestination"], ["TouristAttraction"], ""],
+ [
+ "includesHealthPlanFormulary",
+ ["HealthInsurancePlan"],
+ ["HealthPlanFormulary"],
+ "",
+ ],
+ [
+ "includesHealthPlanNetwork",
+ ["HealthInsurancePlan"],
+ ["HealthPlanNetwork"],
+ "",
+ ],
+ [
+ "includesObject",
+ ["Demand", "Offer", "ProductCollection"],
+ ["TypeAndQuantityNode"],
+ "",
+ ],
+ ["incomeLimit", ["FinancialIncentive"], ["MonetaryAmount", "Text"], ""],
+ ["increasesRiskOf", ["MedicalRiskFactor"], ["MedicalEntity"], ""],
+ ["industry", ["JobPosting"], ["DefinedTerm", "Text"], ""],
+ [
+ "ineligibleRegion",
+ [
+ "ActionAccessSpecification",
+ "DeliveryChargeSpecification",
+ "Demand",
+ "MediaObject",
+ "Offer",
+ ],
+ ["GeoShape", "Place", "Text"],
+ "",
+ ],
+ ["infectiousAgent", ["InfectiousDisease"], ["Text"], ""],
+ ["infectiousAgentClass", ["InfectiousDisease"], ["InfectiousAgentClass"], ""],
+ ["ingredients", ["Recipe"], ["Text"], "recipeIngredient"],
+ ["inker", ["ComicIssue", "ComicStory", "VisualArtwork"], ["Person"], ""],
+ ["insertion", ["Muscle"], ["AnatomicalStructure"], ""],
+ ["installUrl", ["SoftwareApplication"], ["URL"], ""],
+ ["instructor", ["CourseInstance"], ["Person"], ""],
+ ["instrument", ["Action"], ["Thing"], ""],
+ ["intensity", ["ExercisePlan"], ["QuantitativeValue", "Text"], ""],
+ ["interactingDrug", ["Drug"], ["Drug"], ""],
+ ["interactionCount", [], [], "interactionStatistic"],
+ [
+ "interactionService",
+ ["InteractionCounter"],
+ ["SoftwareApplication", "WebSite"],
+ "",
+ ],
+ [
+ "interactionStatistic",
+ ["CreativeWork", "Organization", "Person"],
+ ["InteractionCounter"],
+ "",
+ ],
+ ["interactionType", ["InteractionCounter"], ["Action"], ""],
+ ["interactivityType", ["CreativeWork"], ["Text"], ""],
+ ["interestRate", ["FinancialProduct"], ["Number", "QuantitativeValue"], ""],
+ ["interpretedAsClaim", ["CreativeWork", "MediaObject"], ["Claim"], ""],
+ [
+ "inventoryLevel",
+ ["Demand", "Offer", "SomeProducts"],
+ ["QuantitativeValue"],
+ "",
+ ],
+ ["inverseOf", ["Property"], ["Property"], ""],
+ ["isAcceptingNewPatients", ["MedicalOrganization"], ["Boolean"], ""],
+ ["isAccessibleForFree", ["CreativeWork", "Event", "Place"], ["Boolean"], ""],
+ ["isAccessoryOrSparePartFor", ["Product"], ["Product"], ""],
+ ["isAvailableGenerically", ["Drug"], ["Boolean"], ""],
+ ["isBasedOn", ["CreativeWork"], ["CreativeWork", "Product", "URL"], ""],
+ [
+ "isBasedOnUrl",
+ ["CreativeWork"],
+ ["CreativeWork", "Product", "URL"],
+ "isBasedOn",
+ ],
+ ["isConsumableFor", ["Product"], ["Product"], ""],
+ ["isEncodedByBioChemEntity", ["BioChemEntity"], ["Gene"], ""],
+ ["isFamilyFriendly", ["CreativeWork", "Offer", "Product"], ["Boolean"], ""],
+ ["isGift", ["Order"], ["Boolean"], ""],
+ [
+ "isInvolvedInBiologicalProcess",
+ ["BioChemEntity"],
+ ["DefinedTerm", "PropertyValue", "URL"],
+ "",
+ ],
+ ["isLiveBroadcast", ["BroadcastEvent"], ["Boolean"], ""],
+ [
+ "isLocatedInSubcellularLocation",
+ ["BioChemEntity"],
+ ["DefinedTerm", "PropertyValue", "URL"],
+ "",
+ ],
+ ["isPartOf", ["CreativeWork"], ["CreativeWork", "URL"], ""],
+ ["isPartOfBioChemEntity", ["BioChemEntity"], ["BioChemEntity"], ""],
+ ["isPlanForApartment", ["FloorPlan"], ["Accommodation"], ""],
+ ["isProprietary", ["DietarySupplement", "Drug"], ["Boolean"], ""],
+ ["isRelatedTo", ["Product", "Service"], ["Product", "Service"], ""],
+ ["isResizable", ["3DModel"], ["Boolean"], ""],
+ ["isSimilarTo", ["Product", "Service"], ["Product", "Service"], ""],
+ ["isStoreOn", ["OnlineStore"], ["OnlineMarketplace"], ""],
+ ["isTierOf", ["MemberProgramTier"], ["MemberProgram"], ""],
+ [
+ "isUnlabelledFallback",
+ ["DeliveryTimeSettings", "ShippingRateSettings"],
+ ["Boolean"],
+ "",
+ ],
+ [
+ "isVariantOf",
+ ["Product", "ProductModel"],
+ ["ProductGroup", "ProductModel"],
+ "",
+ ],
+ ["isbn", ["Book"], ["Text"], ""],
+ ["isicV4", ["Organization", "Person", "Place"], ["Text"], ""],
+ ["iso6523Code", ["Organization"], ["Text"], ""],
+ ["isrcCode", ["MusicRecording"], ["Text"], ""],
+ ["issn", ["Blog", "CreativeWorkSeries", "Dataset", "WebSite"], ["Text"], ""],
+ ["issueNumber", ["PublicationIssue"], ["Integer", "Text"], ""],
+ ["issuedBy", ["Certification", "Permit", "Ticket"], ["Organization"], ""],
+ ["issuedThrough", ["Permit"], ["Service"], ""],
+ ["iswcCode", ["MusicComposition"], ["Text"], ""],
+ ["item", ["DataFeedItem", "ListItem"], ["Thing"], ""],
+ [
+ "itemCondition",
+ ["Demand", "MerchantReturnPolicy", "Offer", "Product"],
+ ["OfferItemCondition"],
+ "",
+ ],
+ [
+ "itemDefectReturnFees",
+ ["MerchantReturnPolicy"],
+ ["ReturnFeesEnumeration"],
+ "",
+ ],
+ [
+ "itemDefectReturnLabelSource",
+ ["MerchantReturnPolicy"],
+ ["ReturnLabelSourceEnumeration"],
+ "",
+ ],
+ [
+ "itemDefectReturnShippingFeesAmount",
+ ["MerchantReturnPolicy"],
+ ["MonetaryAmount"],
+ "",
+ ],
+ ["itemListElement", ["ItemList"], ["ListItem", "Text", "Thing"], ""],
+ ["itemListOrder", ["ItemList"], ["ItemListOrderType", "Text"], ""],
+ [
+ "itemLocation",
+ ["ArchiveComponent"],
+ ["Place", "PostalAddress", "Text"],
+ "",
+ ],
+ [
+ "itemOffered",
+ ["Demand", "Offer"],
+ [
+ "AggregateOffer",
+ "CreativeWork",
+ "Event",
+ "MenuItem",
+ "Product",
+ "Service",
+ "Trip",
+ ],
+ "",
+ ],
+ ["itemReviewed", ["AggregateRating", "Review"], ["Thing"], ""],
+ ["itemShipped", ["ParcelDelivery"], ["Product"], ""],
+ ["itinerary", ["Trip"], ["ItemList", "Place"], ""],
+ ["iupacName", ["MolecularEntity"], ["Text"], ""],
+ ["jobBenefits", ["JobPosting"], ["Text"], ""],
+ ["jobDuration", ["JobPosting"], ["Duration", "QuantitativeValue"], ""],
+ ["jobImmediateStart", ["JobPosting"], ["Boolean"], ""],
+ ["jobLocation", ["JobPosting"], ["Place"], ""],
+ ["jobLocationType", ["JobPosting"], ["Text"], ""],
+ ["jobStartDate", ["JobPosting"], ["Date", "Text"], ""],
+ ["jobTitle", ["Person"], ["DefinedTerm", "Text"], ""],
+ [
+ "jurisdiction",
+ ["GovernmentService", "Legislation"],
+ ["AdministrativeArea", "Text"],
+ "",
+ ],
+ [
+ "keywords",
+ ["CreativeWork", "Event", "Organization", "Place", "Product"],
+ ["DefinedTerm", "Text", "URL"],
+ "",
+ ],
+ ["knownVehicleDamages", ["Vehicle"], ["Text"], ""],
+ ["knows", ["Person"], ["Person"], ""],
+ ["knowsAbout", ["Organization", "Person"], ["Text", "Thing", "URL"], ""],
+ ["knowsLanguage", ["Organization", "Person"], ["Language", "Text"], ""],
+ ["labelDetails", ["Drug"], ["URL"], ""],
+ ["landlord", ["RentAction"], ["Organization", "Person"], ""],
+ [
+ "language",
+ ["CommunicateAction", "WriteAction"],
+ ["Language"],
+ "inLanguage",
+ ],
+ ["lastReviewed", ["WebPage"], ["Date"], ""],
+ ["latitude", ["GeoCoordinates", "Place"], ["Number", "Text"], ""],
+ ["layoutImage", ["FloorPlan"], ["ImageObject", "URL"], ""],
+ [
+ "learningResourceType",
+ ["CreativeWork", "LearningResource"],
+ ["DefinedTerm", "Text"],
+ "",
+ ],
+ [
+ "leaseLength",
+ ["Accommodation", "Offer", "RealEstateListing"],
+ ["Duration", "QuantitativeValue"],
+ "",
+ ],
+ ["legalAddress", ["Organization"], ["PostalAddress"], ""],
+ ["legalName", ["Organization"], ["Text"], ""],
+ ["legalRepresentative", ["Organization"], ["Person"], ""],
+ [
+ "legalStatus",
+ ["DietarySupplement", "Drug", "MedicalEntity"],
+ ["DrugLegalStatus", "MedicalEnumeration", "Text"],
+ "",
+ ],
+ ["legislationAmends", ["Legislation"], ["Legislation"], ""],
+ ["legislationApplies", ["Legislation"], ["Legislation"], ""],
+ ["legislationChanges", ["Legislation"], ["Legislation"], ""],
+ ["legislationCommences", ["Legislation"], ["Legislation"], ""],
+ ["legislationConsolidates", ["Legislation"], ["Legislation"], ""],
+ ["legislationCorrects", ["Legislation"], ["Legislation"], ""],
+ [
+ "legislationCountersignedBy",
+ ["Legislation"],
+ ["Organization", "Person"],
+ "",
+ ],
+ ["legislationDate", ["Legislation"], ["Date"], ""],
+ ["legislationDateOfApplicability", ["Legislation"], ["Date"], ""],
+ ["legislationDateVersion", ["Legislation"], ["Date"], ""],
+ ["legislationEnsuresImplementationOf", ["Legislation"], ["Legislation"], ""],
+ ["legislationIdentifier", ["Legislation"], ["Text", "URL"], ""],
+ [
+ "legislationJurisdiction",
+ ["Legislation"],
+ ["AdministrativeArea", "Text"],
+ "",
+ ],
+ ["legislationLegalForce", ["Legislation"], ["LegalForceStatus"], ""],
+ ["legislationLegalValue", ["LegislationObject"], ["LegalValueLevel"], ""],
+ ["legislationPassedBy", ["Legislation"], ["Organization", "Person"], ""],
+ ["legislationRepeals", ["Legislation"], ["Legislation"], ""],
+ ["legislationResponsible", ["Legislation"], ["Organization", "Person"], ""],
+ ["legislationTransposes", ["Legislation"], ["Legislation"], ""],
+ ["legislationType", ["Legislation"], ["CategoryCode", "Text"], ""],
+ ["leiCode", ["Organization"], ["Text"], ""],
+ ["lender", ["BorrowAction"], ["Organization", "Person"], ""],
+ ["lesser", ["QualitativeValue"], ["QualitativeValue"], ""],
+ ["lesserOrEqual", ["QualitativeValue"], ["QualitativeValue"], ""],
+ ["letterer", ["ComicIssue", "ComicStory", "VisualArtwork"], ["Person"], ""],
+ ["license", ["CreativeWork"], ["CreativeWork", "URL"], ""],
+ ["lifeEvent", ["Person"], ["Event"], ""],
+ ["line", ["GeoShape"], ["Text"], ""],
+ ["linkRelationship", ["LinkRole"], ["Text"], ""],
+ ["liveBlogUpdate", ["LiveBlogPosting"], ["BlogPosting"], ""],
+ ["loanMortgageMandateAmount", ["MortgageLoan"], ["MonetaryAmount"], ""],
+ ["loanPaymentAmount", ["RepaymentSpecification"], ["MonetaryAmount"], ""],
+ ["loanPaymentFrequency", ["RepaymentSpecification"], ["Number"], ""],
+ ["loanRepaymentForm", ["LoanOrCredit"], ["RepaymentSpecification"], ""],
+ ["loanTerm", ["LoanOrCredit"], ["QuantitativeValue"], ""],
+ ["loanType", ["LoanOrCredit"], ["Text", "URL"], ""],
+ [
+ "location",
+ ["Action", "Event", "InteractionCounter", "Organization"],
+ ["Place", "PostalAddress", "Text", "VirtualLocation"],
+ "",
+ ],
+ ["locationCreated", ["CreativeWork"], ["Place"], ""],
+ ["lodgingUnitDescription", ["LodgingReservation"], ["Text"], ""],
+ ["lodgingUnitType", ["LodgingReservation"], ["QualitativeValue", "Text"], ""],
+ [
+ "logo",
+ ["Brand", "Certification", "Organization", "Place", "Product", "Service"],
+ ["ImageObject", "URL"],
+ "",
+ ],
+ ["longitude", ["GeoCoordinates", "Place"], ["Number", "Text"], ""],
+ ["loser", ["WinAction"], ["Person"], ""],
+ ["lowPrice", ["AggregateOffer"], ["Number", "Text"], ""],
+ ["lyricist", ["MusicComposition"], ["Person"], ""],
+ ["lyrics", ["MusicComposition"], ["CreativeWork"], ""],
+ ["mainContentOfPage", ["WebPage"], ["WebPageElement"], ""],
+ ["mainEntity", ["CreativeWork"], ["Thing"], ""],
+ ["mainEntityOfPage", ["Thing"], ["CreativeWork", "URL"], ""],
+ ["maintainer", ["CreativeWork"], ["Organization", "Person"], ""],
+ ["makesOffer", ["Organization", "Person"], ["Offer"], ""],
+ ["manufacturer", ["Product"], ["Organization"], ""],
+ ["map", ["Place"], ["URL"], "hasMap"],
+ ["mapType", ["Map"], ["MapCategoryType"], ""],
+ ["maps", ["Place"], ["URL"], "hasMap"],
+ ["marginOfError", ["Observation"], ["QuantitativeValue"], ""],
+ ["masthead", ["NewsMediaOrganization"], ["CreativeWork", "URL"], ""],
+ ["material", ["CreativeWork", "Product"], ["Product", "Text", "URL"], ""],
+ ["materialExtent", ["CreativeWork"], ["QuantitativeValue", "Text"], ""],
+ ["mathExpression", ["MathSolver"], ["SolveMathAction", "Text"], ""],
+ ["maxPrice", ["PriceSpecification"], ["Number"], ""],
+ [
+ "maxValue",
+ [
+ "MonetaryAmount",
+ "PropertyValue",
+ "PropertyValueSpecification",
+ "QuantitativeValue",
+ ],
+ ["Number"],
+ "",
+ ],
+ ["maximumAttendeeCapacity", ["Event", "Place"], ["Integer"], ""],
+ ["maximumEnrollment", ["EducationalOccupationalProgram"], ["Integer"], ""],
+ [
+ "maximumIntake",
+ ["DietarySupplement", "Drug", "DrugStrength", "Substance"],
+ ["MaximumDoseSchedule"],
+ "",
+ ],
+ ["maximumPhysicalAttendeeCapacity", ["Event"], ["Integer"], ""],
+ ["maximumVirtualAttendeeCapacity", ["Event"], ["Integer"], ""],
+ ["mealService", ["Flight"], ["Text"], ""],
+ [
+ "measuredProperty",
+ ["Observation", "StatisticalVariable"],
+ ["Property"],
+ "",
+ ],
+ [
+ "measurementDenominator",
+ ["Observation", "StatisticalVariable"],
+ ["StatisticalVariable"],
+ "",
+ ],
+ [
+ "measurementMethod",
+ [
+ "DataCatalog",
+ "DataDownload",
+ "Dataset",
+ "Observation",
+ "PropertyValue",
+ "StatisticalVariable",
+ ],
+ ["DefinedTerm", "MeasurementMethodEnum", "Text", "URL"],
+ "",
+ ],
+ [
+ "measurementQualifier",
+ ["Observation", "StatisticalVariable"],
+ ["Enumeration"],
+ "",
+ ],
+ [
+ "measurementTechnique",
+ [
+ "DataCatalog",
+ "DataDownload",
+ "Dataset",
+ "Observation",
+ "PropertyValue",
+ "StatisticalVariable",
+ ],
+ ["DefinedTerm", "MeasurementMethodEnum", "Text", "URL"],
+ "",
+ ],
+ ["mechanismOfAction", ["DietarySupplement", "Drug"], ["Text"], ""],
+ [
+ "mediaAuthenticityCategory",
+ ["MediaReview"],
+ ["MediaManipulationRatingEnumeration"],
+ "",
+ ],
+ ["mediaItemAppearance", ["MediaReviewItem"], ["MediaObject"], ""],
+ ["median", ["QuantitativeValueDistribution"], ["Number"], ""],
+ [
+ "medicalAudience",
+ ["MedicalWebPage"],
+ ["MedicalAudience", "MedicalAudienceType"],
+ "",
+ ],
+ [
+ "medicalSpecialty",
+ ["Hospital", "MedicalClinic", "MedicalOrganization", "Physician"],
+ ["MedicalSpecialty"],
+ "",
+ ],
+ ["medicineSystem", ["MedicalEntity"], ["MedicineSystem"], ""],
+ [
+ "meetsEmissionStandard",
+ ["Vehicle"],
+ ["QualitativeValue", "Text", "URL"],
+ "",
+ ],
+ [
+ "member",
+ ["Organization", "ProgramMembership"],
+ ["Organization", "Person"],
+ "",
+ ],
+ [
+ "memberOf",
+ ["Organization", "Person"],
+ ["MemberProgramTier", "Organization", "ProgramMembership"],
+ "",
+ ],
+ [
+ "members",
+ ["Organization", "ProgramMembership"],
+ ["Organization", "Person"],
+ "member",
+ ],
+ ["membershipNumber", ["ProgramMembership"], ["Text"], ""],
+ [
+ "membershipPointsEarned",
+ ["MemberProgramTier", "PriceSpecification", "ProgramMembership"],
+ ["Number", "QuantitativeValue"],
+ "",
+ ],
+ ["memoryRequirements", ["SoftwareApplication"], ["Text", "URL"], ""],
+ ["mentions", ["CreativeWork"], ["Thing"], ""],
+ ["menu", ["FoodEstablishment"], ["Menu", "Text", "URL"], "hasMenu"],
+ ["menuAddOn", ["MenuItem"], ["MenuItem", "MenuSection"], ""],
+ ["merchant", ["Order"], ["Organization", "Person"], "seller"],
+ [
+ "merchantReturnDays",
+ ["MerchantReturnPolicy", "MerchantReturnPolicySeasonalOverride"],
+ ["Date", "DateTime", "Integer"],
+ "",
+ ],
+ ["merchantReturnLink", ["MerchantReturnPolicy"], ["URL"], ""],
+ ["messageAttachment", ["Message"], ["CreativeWork"], ""],
+ ["mileageFromOdometer", ["Vehicle"], ["QuantitativeValue"], ""],
+ ["minPrice", ["PriceSpecification"], ["Number"], ""],
+ [
+ "minValue",
+ [
+ "MonetaryAmount",
+ "PropertyValue",
+ "PropertyValueSpecification",
+ "QuantitativeValue",
+ ],
+ ["Number"],
+ "",
+ ],
+ [
+ "minimumPaymentDue",
+ ["Invoice"],
+ ["MonetaryAmount", "PriceSpecification"],
+ "",
+ ],
+ [
+ "missionCoveragePrioritiesPolicy",
+ ["NewsMediaOrganization"],
+ ["CreativeWork", "URL"],
+ "",
+ ],
+ ["mobileUrl", ["Offer", "Product"], ["Text"], ""],
+ ["model", ["Product"], ["ProductModel", "Text"], ""],
+ ["modelDate", ["Vehicle"], ["Date"], ""],
+ ["modifiedTime", ["Reservation"], ["DateTime"], ""],
+ ["molecularFormula", ["MolecularEntity"], ["Text"], ""],
+ ["molecularWeight", ["MolecularEntity"], ["QuantitativeValue", "Text"], ""],
+ [
+ "monoisotopicMolecularWeight",
+ ["MolecularEntity"],
+ ["QuantitativeValue", "Text"],
+ "",
+ ],
+ [
+ "monthlyMinimumRepaymentAmount",
+ ["PaymentCard"],
+ ["MonetaryAmount", "Number"],
+ "",
+ ],
+ [
+ "monthsOfExperience",
+ ["OccupationalExperienceRequirements"],
+ ["Number"],
+ "",
+ ],
+ ["mpn", ["Demand", "Offer", "Product"], ["Text"], ""],
+ ["multipleValues", ["PropertyValueSpecification"], ["Boolean"], ""],
+ ["muscleAction", ["Muscle"], ["Text"], ""],
+ ["musicArrangement", ["MusicComposition"], ["MusicComposition"], ""],
+ [
+ "musicBy",
+ [
+ "Clip",
+ "Episode",
+ "Movie",
+ "MovieSeries",
+ "RadioSeries",
+ "TVSeries",
+ "VideoGame",
+ "VideoGameSeries",
+ "VideoObject",
+ ],
+ ["MusicGroup", "Person"],
+ "",
+ ],
+ ["musicCompositionForm", ["MusicComposition"], ["Text"], ""],
+ ["musicGroupMember", ["MusicGroup"], ["Person"], "member"],
+ ["musicReleaseFormat", ["MusicRelease"], ["MusicReleaseFormatType"], ""],
+ ["musicalKey", ["MusicComposition"], ["Text"], ""],
+ ["naics", ["Organization", "Person"], ["Text"], ""],
+ ["name", ["Thing"], ["Text"], ""],
+ ["namedPosition", ["Role"], ["Text", "URL"], "roleName"],
+ ["nationality", ["Person"], ["Country"], ""],
+ ["naturalProgression", ["MedicalCondition"], ["Text"], ""],
+ [
+ "negativeNotes",
+ ["Product", "Review"],
+ ["ItemList", "ListItem", "Text", "WebContent"],
+ "",
+ ],
+ ["nerve", ["Muscle"], ["Nerve"], ""],
+ ["nerveMotor", ["Nerve"], ["Muscle"], ""],
+ ["netWorth", ["Person"], ["MonetaryAmount", "PriceSpecification"], ""],
+ [
+ "newsUpdatesAndGuidelines",
+ ["SpecialAnnouncement"],
+ ["URL", "WebContent"],
+ "",
+ ],
+ ["nextItem", ["ListItem"], ["ListItem"], ""],
+ ["noBylinesPolicy", ["NewsMediaOrganization"], ["CreativeWork", "URL"], ""],
+ ["nonEqual", ["QualitativeValue"], ["QualitativeValue"], ""],
+ ["nonProprietaryName", ["DietarySupplement", "Drug"], ["Text"], ""],
+ ["nonprofitStatus", ["Organization"], ["NonprofitType"], ""],
+ ["normalRange", ["MedicalTest"], ["MedicalEnumeration", "Text"], ""],
+ ["nsn", ["Product"], ["Text"], ""],
+ ["numAdults", ["LodgingReservation"], ["Integer", "QuantitativeValue"], ""],
+ ["numChildren", ["LodgingReservation"], ["Integer", "QuantitativeValue"], ""],
+ ["numConstraints", ["ConstraintNode"], ["Integer"], ""],
+ ["numItems", ["ShippingConditions"], ["QuantitativeValue"], ""],
+ ["numTracks", ["MusicPlaylist"], ["Integer"], ""],
+ [
+ "numberOfAccommodationUnits",
+ ["ApartmentComplex", "FloorPlan"],
+ ["QuantitativeValue"],
+ "",
+ ],
+ ["numberOfAirbags", ["Vehicle"], ["Number", "Text"], ""],
+ [
+ "numberOfAvailableAccommodationUnits",
+ ["ApartmentComplex", "FloorPlan"],
+ ["QuantitativeValue"],
+ "",
+ ],
+ ["numberOfAxles", ["Vehicle"], ["Number", "QuantitativeValue"], ""],
+ ["numberOfBathroomsTotal", ["Accommodation", "FloorPlan"], ["Integer"], ""],
+ [
+ "numberOfBedrooms",
+ ["Accommodation", "ApartmentComplex", "FloorPlan"],
+ ["Number", "QuantitativeValue"],
+ "",
+ ],
+ ["numberOfBeds", ["BedDetails"], ["Number"], ""],
+ [
+ "numberOfCredits",
+ ["Course", "EducationalOccupationalProgram"],
+ ["Integer", "StructuredValue"],
+ "",
+ ],
+ ["numberOfDoors", ["Vehicle"], ["Number", "QuantitativeValue"], ""],
+ [
+ "numberOfEmployees",
+ ["BusinessAudience", "Organization"],
+ ["QuantitativeValue"],
+ "",
+ ],
+ [
+ "numberOfEpisodes",
+ ["CreativeWorkSeason", "RadioSeries", "TVSeries", "VideoGameSeries"],
+ ["Integer"],
+ "",
+ ],
+ ["numberOfForwardGears", ["Vehicle"], ["Number", "QuantitativeValue"], ""],
+ ["numberOfFullBathrooms", ["Accommodation", "FloorPlan"], ["Number"], ""],
+ ["numberOfItems", ["ItemList"], ["Integer"], ""],
+ ["numberOfLoanPayments", ["RepaymentSpecification"], ["Number"], ""],
+ ["numberOfPages", ["Book"], ["Integer"], ""],
+ ["numberOfPartialBathrooms", ["Accommodation", "FloorPlan"], ["Number"], ""],
+ ["numberOfPlayers", ["Game", "VideoGameSeries"], ["QuantitativeValue"], ""],
+ ["numberOfPreviousOwners", ["Vehicle"], ["Number", "QuantitativeValue"], ""],
+ [
+ "numberOfRooms",
+ [
+ "Accommodation",
+ "Apartment",
+ "FloorPlan",
+ "House",
+ "LodgingBusiness",
+ "SingleFamilyResidence",
+ "Suite",
+ ],
+ ["Number", "QuantitativeValue"],
+ "",
+ ],
+ [
+ "numberOfSeasons",
+ ["RadioSeries", "TVSeries", "VideoGameSeries"],
+ ["Integer"],
+ "",
+ ],
+ ["numberedPosition", ["OrganizationRole"], ["Number"], ""],
+ ["nutrition", ["MenuItem", "Recipe"], ["NutritionInformation"], ""],
+ ["object", ["Action"], ["Thing"], ""],
+ ["observationAbout", ["Observation"], ["Place", "Thing"], ""],
+ ["observationDate", ["Observation"], ["Date", "DateTime"], ""],
+ ["observationPeriod", ["Observation"], ["Text"], ""],
+ [
+ "occupancy",
+ [
+ "Accommodation",
+ "Apartment",
+ "HotelRoom",
+ "SingleFamilyResidence",
+ "Suite",
+ ],
+ ["QuantitativeValue"],
+ "",
+ ],
+ ["occupationLocation", ["Occupation"], ["AdministrativeArea"], ""],
+ [
+ "occupationalCategory",
+ [
+ "EducationalOccupationalProgram",
+ "JobPosting",
+ "Occupation",
+ "Physician",
+ "WorkBasedProgram",
+ ],
+ ["CategoryCode", "Text"],
+ "",
+ ],
+ [
+ "occupationalCredentialAwarded",
+ ["Course", "EducationalOccupationalProgram"],
+ ["EducationalOccupationalCredential", "Text", "URL"],
+ "",
+ ],
+ ["offerCount", ["AggregateOffer"], ["Integer"], ""],
+ ["offeredBy", ["Offer"], ["Organization", "Person"], ""],
+ [
+ "offers",
+ [
+ "AggregateOffer",
+ "CreativeWork",
+ "EducationalOccupationalProgram",
+ "Event",
+ "MenuItem",
+ "Product",
+ "Service",
+ "Trip",
+ ],
+ ["Demand", "Offer"],
+ "",
+ ],
+ ["offersPrescriptionByMail", ["HealthPlanFormulary"], ["Boolean"], ""],
+ ["openingHours", ["CivicStructure", "LocalBusiness"], ["Text"], ""],
+ ["openingHoursSpecification", ["Place"], ["OpeningHoursSpecification"], ""],
+ ["opens", ["OpeningHoursSpecification"], ["Time"], ""],
+ ["operatingSystem", ["SoftwareApplication"], ["OperatingSystem", "Text"], ""],
+ ["opponent", ["ExerciseAction"], ["Person"], ""],
+ ["option", ["ChooseAction"], ["Text", "Thing"], "actionOption"],
+ ["orderDate", ["Order"], ["Date", "DateTime"], ""],
+ ["orderDelivery", ["Order", "OrderItem"], ["ParcelDelivery"], ""],
+ ["orderItemNumber", ["OrderItem"], ["Text"], ""],
+ ["orderItemStatus", ["OrderItem"], ["OrderStatus"], ""],
+ ["orderNumber", ["Order"], ["Text"], ""],
+ ["orderPercentage", ["ShippingRateSettings"], ["Number"], ""],
+ ["orderQuantity", ["OrderItem"], ["Number", "QuantitativeValue"], ""],
+ ["orderStatus", ["Order"], ["OrderStatus"], ""],
+ ["orderValue", ["ShippingConditions"], ["MonetaryAmount"], ""],
+ [
+ "orderedItem",
+ ["Order", "OrderItem"],
+ ["OrderItem", "Product", "Service"],
+ "",
+ ],
+ ["organizer", ["Event"], ["Organization", "Person"], ""],
+ ["originAddress", ["ParcelDelivery"], ["PostalAddress"], ""],
+ ["originalMediaContextDescription", ["MediaReview"], ["Text"], ""],
+ ["originalMediaLink", ["MediaReview"], ["MediaObject", "URL", "WebPage"], ""],
+ ["originatesFrom", ["LymphaticVessel"], ["Vessel"], ""],
+ ["overdosage", ["Drug"], ["Text"], ""],
+ ["ownedFrom", ["OwnershipInfo"], ["DateTime"], ""],
+ ["ownedThrough", ["OwnershipInfo"], ["DateTime"], ""],
+ ["owner", ["Thing"], ["Organization", "Person"], ""],
+ [
+ "ownershipFundingInfo",
+ ["NewsMediaOrganization", "Organization"],
+ ["AboutPage", "CreativeWork", "Text", "URL"],
+ "",
+ ],
+ ["owns", ["Organization", "Person"], ["Thing"], ""],
+ [
+ "pageEnd",
+ ["Article", "Chapter", "PublicationIssue", "PublicationVolume"],
+ ["Integer", "Text"],
+ "",
+ ],
+ [
+ "pageStart",
+ ["Article", "Chapter", "PublicationIssue", "PublicationVolume"],
+ ["Integer", "Text"],
+ "",
+ ],
+ [
+ "pagination",
+ ["Article", "Chapter", "PublicationIssue", "PublicationVolume"],
+ ["Text"],
+ "",
+ ],
+ ["parent", ["Person"], ["Person"], ""],
+ [
+ "parentItem",
+ ["Answer", "Comment", "Question"],
+ ["Comment", "CreativeWork"],
+ "",
+ ],
+ ["parentOrganization", ["Organization"], ["Organization"], ""],
+ ["parentService", ["BroadcastService"], ["BroadcastService"], ""],
+ ["parentTaxon", ["Taxon"], ["Taxon", "Text", "URL"], ""],
+ ["parents", ["Person"], ["Person"], "parent"],
+ ["partOfEpisode", ["Clip"], ["Episode"], ""],
+ ["partOfInvoice", ["Order"], ["Invoice"], ""],
+ ["partOfOrder", ["ParcelDelivery"], ["Order"], ""],
+ ["partOfSeason", ["Clip", "Episode"], ["CreativeWorkSeason"], ""],
+ [
+ "partOfSeries",
+ ["Clip", "CreativeWorkSeason", "Episode"],
+ ["CreativeWorkSeries"],
+ "",
+ ],
+ ["partOfSystem", ["AnatomicalStructure"], ["AnatomicalSystem"], ""],
+ [
+ "partOfTVSeries",
+ ["TVClip", "TVEpisode", "TVSeason"],
+ ["TVSeries"],
+ "partOfSeries",
+ ],
+ ["partOfTrip", ["Trip"], ["Trip"], ""],
+ ["participant", ["Action"], ["Organization", "Person"], ""],
+ [
+ "partySize",
+ ["FoodEstablishmentReservation", "TaxiReservation"],
+ ["Integer", "QuantitativeValue"],
+ "",
+ ],
+ [
+ "passengerPriorityStatus",
+ ["FlightReservation"],
+ ["QualitativeValue", "Text"],
+ "",
+ ],
+ ["passengerSequenceNumber", ["FlightReservation"], ["Text"], ""],
+ ["pathophysiology", ["MedicalCondition", "PhysicalActivity"], ["Text"], ""],
+ ["pattern", ["CreativeWork", "Product"], ["DefinedTerm", "Text"], ""],
+ ["payload", ["Vehicle"], ["QuantitativeValue"], ""],
+ ["paymentAccepted", ["LocalBusiness"], ["Text"], ""],
+ ["paymentDue", ["Invoice", "Order"], ["DateTime"], "paymentDueDate"],
+ ["paymentDueDate", ["Invoice", "Order"], ["Date", "DateTime"], ""],
+ ["paymentMethod", ["Invoice", "Order"], ["PaymentMethod", "Text"], ""],
+ ["paymentMethodId", ["Invoice", "Order"], ["Text"], ""],
+ ["paymentMethodType", ["PaymentMethod"], ["PaymentMethodType"], ""],
+ ["paymentStatus", ["Invoice"], ["PaymentStatusType", "Text"], ""],
+ ["paymentUrl", ["Order"], ["URL"], ""],
+ ["penciler", ["ComicIssue", "ComicStory", "VisualArtwork"], ["Person"], ""],
+ ["percentile10", ["QuantitativeValueDistribution"], ["Number"], ""],
+ ["percentile25", ["QuantitativeValueDistribution"], ["Number"], ""],
+ ["percentile75", ["QuantitativeValueDistribution"], ["Number"], ""],
+ ["percentile90", ["QuantitativeValueDistribution"], ["Number"], ""],
+ ["performTime", ["HowTo", "HowToDirection"], ["Duration"], ""],
+ ["performer", ["Event"], ["Organization", "Person"], ""],
+ ["performerIn", ["Person"], ["Event"], ""],
+ ["performers", ["Event"], ["Organization", "Person"], "performer"],
+ [
+ "permissionType",
+ ["DigitalDocumentPermission"],
+ ["DigitalDocumentPermissionType"],
+ "",
+ ],
+ ["permissions", ["SoftwareApplication"], ["Text"], ""],
+ ["permitAudience", ["Permit"], ["Audience"], ""],
+ ["permittedUsage", ["Accommodation"], ["Text"], ""],
+ [
+ "petsAllowed",
+ ["Accommodation", "ApartmentComplex", "FloorPlan", "LodgingBusiness"],
+ ["Boolean", "Text"],
+ "",
+ ],
+ ["phoneticText", ["PronounceableText"], ["Text"], ""],
+ ["photo", ["Place"], ["ImageObject", "Photograph"], ""],
+ ["photos", ["Place"], ["ImageObject", "Photograph"], "photo"],
+ ["physicalRequirement", ["JobPosting"], ["DefinedTerm", "Text", "URL"], ""],
+ ["physiologicalBenefits", ["Diet"], ["Text"], ""],
+ [
+ "pickupLocation",
+ ["RentalCarReservation", "TaxiReservation"],
+ ["Place"],
+ "",
+ ],
+ ["pickupTime", ["RentalCarReservation", "TaxiReservation"], ["DateTime"], ""],
+ ["playMode", ["VideoGame", "VideoGameSeries"], ["GamePlayMode"], ""],
+ ["playerType", ["MediaObject"], ["Text"], ""],
+ ["playersOnline", ["GameServer"], ["Integer"], ""],
+ ["polygon", ["GeoShape"], ["Text"], ""],
+ [
+ "populationType",
+ ["StatisticalPopulation", "StatisticalVariable"],
+ ["Class"],
+ "",
+ ],
+ ["position", ["CreativeWork", "ListItem"], ["Integer", "Text"], ""],
+ [
+ "positiveNotes",
+ ["Product", "Review"],
+ ["ItemList", "ListItem", "Text", "WebContent"],
+ "",
+ ],
+ ["possibleComplication", ["MedicalCondition"], ["Text"], ""],
+ [
+ "possibleTreatment",
+ ["MedicalCondition", "MedicalSignOrSymptom"],
+ ["Drug", "DrugClass", "LifestyleModification", "MedicalTherapy"],
+ "",
+ ],
+ ["postOfficeBoxNumber", ["PostalAddress"], ["Text"], ""],
+ ["postOp", ["MedicalDevice"], ["Text"], ""],
+ [
+ "postalCode",
+ ["DefinedRegion", "GeoCoordinates", "GeoShape", "PostalAddress"],
+ ["Text"],
+ "",
+ ],
+ ["postalCodeBegin", ["PostalCodeRangeSpecification"], ["Text"], ""],
+ ["postalCodeEnd", ["PostalCodeRangeSpecification"], ["Text"], ""],
+ ["postalCodePrefix", ["DefinedRegion"], ["Text"], ""],
+ ["postalCodeRange", ["DefinedRegion"], ["PostalCodeRangeSpecification"], ""],
+ ["potentialAction", ["Thing"], ["Action"], ""],
+ [
+ "potentialUse",
+ ["ChemicalSubstance", "MolecularEntity"],
+ ["DefinedTerm"],
+ "",
+ ],
+ ["practicesAt", ["IndividualPhysician"], ["MedicalOrganization"], ""],
+ ["preOp", ["MedicalDevice"], ["Text"], ""],
+ ["predecessorOf", ["ProductModel"], ["ProductModel"], ""],
+ ["pregnancyCategory", ["Drug"], ["DrugPregnancyCategory"], ""],
+ ["pregnancyWarning", ["Drug"], ["Text"], ""],
+ ["prepTime", ["HowTo", "HowToDirection"], ["Duration"], ""],
+ ["preparation", ["MedicalProcedure"], ["MedicalEntity", "Text"], ""],
+ ["prescribingInfo", ["Drug"], ["URL"], ""],
+ ["prescriptionStatus", ["Drug"], ["DrugPrescriptionStatus", "Text"], ""],
+ ["previousItem", ["ListItem"], ["ListItem"], ""],
+ ["previousStartDate", ["Event"], ["Date", "DateTime"], ""],
+ [
+ "price",
+ ["DonateAction", "Offer", "PriceSpecification", "TradeAction"],
+ ["Number", "Text"],
+ "",
+ ],
+ [
+ "priceComponent",
+ ["CompoundPriceSpecification"],
+ ["PriceSpecification"],
+ "",
+ ],
+ [
+ "priceComponentType",
+ ["UnitPriceSpecification"],
+ ["PriceComponentTypeEnumeration"],
+ "",
+ ],
+ [
+ "priceCurrency",
+ [
+ "DonateAction",
+ "Offer",
+ "PriceSpecification",
+ "Reservation",
+ "Ticket",
+ "TradeAction",
+ ],
+ ["Text"],
+ "",
+ ],
+ ["priceRange", ["LocalBusiness"], ["Text"], ""],
+ [
+ "priceSpecification",
+ ["Demand", "DonateAction", "Offer", "TradeAction"],
+ ["PriceSpecification"],
+ "",
+ ],
+ [
+ "priceType",
+ ["CompoundPriceSpecification", "UnitPriceSpecification"],
+ ["PriceTypeEnumeration", "Text"],
+ "",
+ ],
+ ["priceValidUntil", ["Offer"], ["Date"], ""],
+ ["primaryImageOfPage", ["WebPage"], ["ImageObject"], ""],
+ ["primaryPrevention", ["MedicalCondition"], ["MedicalTherapy"], ""],
+ ["printColumn", ["NewsArticle"], ["Text"], ""],
+ ["printEdition", ["NewsArticle"], ["Text"], ""],
+ ["printPage", ["NewsArticle"], ["Text"], ""],
+ ["printSection", ["NewsArticle"], ["Text"], ""],
+ ["procedure", ["MedicalDevice"], ["Text"], ""],
+ ["procedureType", ["MedicalProcedure"], ["MedicalProcedureType"], ""],
+ ["processingTime", ["ServiceChannel"], ["Duration"], ""],
+ ["processorRequirements", ["SoftwareApplication"], ["Text"], ""],
+ ["producer", ["CreativeWork"], ["Organization", "Person"], ""],
+ ["produces", ["Service"], ["Thing"], "serviceOutput"],
+ ["productGroupID", ["ProductGroup"], ["Text"], ""],
+ ["productID", ["Product"], ["Text"], ""],
+ ["productSupported", ["ContactPoint"], ["Product", "Text"], ""],
+ [
+ "productionCompany",
+ [
+ "CreativeWorkSeason",
+ "Episode",
+ "MediaObject",
+ "Movie",
+ "MovieSeries",
+ "RadioSeries",
+ "TVSeries",
+ "VideoGameSeries",
+ ],
+ ["Organization"],
+ "",
+ ],
+ ["productionDate", ["Product", "Vehicle"], ["Date"], ""],
+ ["proficiencyLevel", ["TechArticle"], ["Text"], ""],
+ ["program", ["ProgramMembership"], ["MemberProgram"], ""],
+ ["programMembershipUsed", ["Reservation"], ["ProgramMembership"], ""],
+ ["programName", ["ProgramMembership"], ["Text"], ""],
+ [
+ "programPrerequisites",
+ ["EducationalOccupationalProgram"],
+ ["AlignmentObject", "Course", "EducationalOccupationalCredential", "Text"],
+ "",
+ ],
+ [
+ "programType",
+ ["EducationalOccupationalProgram"],
+ ["DefinedTerm", "Text"],
+ "",
+ ],
+ [
+ "programmingLanguage",
+ ["SoftwareSourceCode"],
+ ["ComputerLanguage", "Text"],
+ "",
+ ],
+ ["programmingModel", ["APIReference"], ["Text"], ""],
+ ["pronouns", ["Person"], ["DefinedTerm", "StructuredValue", "Text"], ""],
+ ["propertyID", ["PropertyValue"], ["Text", "URL"], ""],
+ ["proprietaryName", ["DietarySupplement", "Drug"], ["Text"], ""],
+ ["proteinContent", ["NutritionInformation"], ["Mass"], ""],
+ [
+ "provider",
+ [
+ "Action",
+ "CreativeWork",
+ "EducationalOccupationalProgram",
+ "FinancialIncentive",
+ "Invoice",
+ "ParcelDelivery",
+ "Reservation",
+ "Service",
+ "Trip",
+ ],
+ ["Organization", "Person"],
+ "",
+ ],
+ ["providerMobility", ["Service"], ["Text"], ""],
+ ["providesBroadcastService", ["BroadcastChannel"], ["BroadcastService"], ""],
+ ["providesService", ["ServiceChannel"], ["Service"], ""],
+ ["publicAccess", ["Place"], ["Boolean"], ""],
+ [
+ "publicTransportClosuresInfo",
+ ["SpecialAnnouncement"],
+ ["URL", "WebContent"],
+ "",
+ ],
+ ["publication", ["CreativeWork"], ["PublicationEvent"], ""],
+ ["publicationType", ["MedicalScholarlyArticle"], ["Text"], ""],
+ ["publishedBy", ["PublicationEvent"], ["Organization", "Person"], ""],
+ ["publishedOn", ["PublicationEvent"], ["BroadcastService"], ""],
+ [
+ "publisher",
+ ["CreativeWork", "FinancialIncentive"],
+ ["Organization", "Person"],
+ "",
+ ],
+ ["publisherImprint", ["CreativeWork"], ["Organization"], ""],
+ [
+ "publishingPrinciples",
+ ["CreativeWork", "Organization", "Person"],
+ ["CreativeWork", "URL"],
+ "",
+ ],
+ ["purchaseDate", ["Product", "Vehicle"], ["Date"], ""],
+ ["purchasePriceLimit", ["FinancialIncentive"], ["MonetaryAmount"], ""],
+ ["purchaseType", ["FinancialIncentive"], ["PurchaseType"], ""],
+ ["qualifications", ["JobPosting", "Occupation"], ["Credential", "Text"], ""],
+ [
+ "qualifiedExpense",
+ ["FinancialIncentive"],
+ ["IncentiveQualifiedExpenseType"],
+ "",
+ ],
+ ["quarantineGuidelines", ["SpecialAnnouncement"], ["URL", "WebContent"], ""],
+ ["query", ["SearchAction"], ["Text"], ""],
+ ["quest", ["Game", "VideoGameSeries"], ["Thing"], ""],
+ ["question", ["AskAction"], ["Question"], ""],
+ ["rangeIncludes", ["Property"], ["Class"], ""],
+ ["ratingCount", ["AggregateRating"], ["Integer"], ""],
+ ["ratingExplanation", ["Rating"], ["Text"], ""],
+ ["ratingValue", ["Rating"], ["Number", "Text"], ""],
+ ["readBy", ["Audiobook"], ["Person"], ""],
+ ["readonlyValue", ["PropertyValueSpecification"], ["Boolean"], ""],
+ ["realEstateAgent", ["RentAction"], ["RealEstateAgent"], ""],
+ ["recipe", ["CookAction"], ["Recipe"], ""],
+ ["recipeCategory", ["Recipe"], ["Text"], ""],
+ ["recipeCuisine", ["Recipe"], ["Text"], ""],
+ ["recipeIngredient", ["Recipe"], ["ItemList", "PropertyValue", "Text"], ""],
+ ["recipeInstructions", ["Recipe"], ["CreativeWork", "ItemList", "Text"], ""],
+ ["recipeYield", ["Recipe"], ["QuantitativeValue", "Text"], ""],
+ [
+ "recipient",
+ [
+ "AuthorizeAction",
+ "CommunicateAction",
+ "DonateAction",
+ "GiveAction",
+ "Message",
+ "PayAction",
+ "ReturnAction",
+ "SendAction",
+ "TipAction",
+ ],
+ ["Audience", "ContactPoint", "Organization", "Person"],
+ "",
+ ],
+ ["recognizedBy", ["Credential"], ["Organization"], ""],
+ ["recognizingAuthority", ["MedicalEntity"], ["Organization"], ""],
+ ["recommendationStrength", ["MedicalGuidelineRecommendation"], ["Text"], ""],
+ ["recommendedIntake", ["DietarySupplement"], ["RecommendedDoseSchedule"], ""],
+ ["recordLabel", ["MusicRelease"], ["Organization"], ""],
+ ["recordedAs", ["MusicComposition"], ["MusicRecording"], ""],
+ ["recordedAt", ["CreativeWork"], ["Event"], ""],
+ ["recordedIn", ["Event"], ["CreativeWork"], ""],
+ ["recordingOf", ["MusicRecording"], ["MusicComposition"], ""],
+ ["recourseLoan", ["LoanOrCredit"], ["Boolean"], ""],
+ ["referee", ["SportsEvent"], ["Person"], ""],
+ ["referenceQuantity", ["UnitPriceSpecification"], ["QuantitativeValue"], ""],
+ ["referencesOrder", ["Invoice"], ["Order"], ""],
+ [
+ "refundType",
+ ["MerchantReturnPolicy", "MerchantReturnPolicySeasonalOverride"],
+ ["RefundTypeEnumeration"],
+ "",
+ ],
+ [
+ "regionDrained",
+ ["LymphaticVessel", "Vein"],
+ ["AnatomicalStructure", "AnatomicalSystem"],
+ "",
+ ],
+ ["regionsAllowed", ["MediaObject"], ["Place"], ""],
+ [
+ "relatedAnatomy",
+ ["SuperficialAnatomy"],
+ ["AnatomicalStructure", "AnatomicalSystem"],
+ "",
+ ],
+ [
+ "relatedCondition",
+ ["AnatomicalStructure", "AnatomicalSystem", "SuperficialAnatomy"],
+ ["MedicalCondition"],
+ "",
+ ],
+ ["relatedDrug", ["Drug"], ["Drug"], ""],
+ ["relatedLink", ["WebPage"], ["URL"], ""],
+ ["relatedStructure", ["AnatomicalSystem"], ["AnatomicalStructure"], ""],
+ [
+ "relatedTherapy",
+ ["AnatomicalStructure", "AnatomicalSystem", "SuperficialAnatomy"],
+ ["MedicalTherapy"],
+ "",
+ ],
+ ["relatedTo", ["Person"], ["Person"], ""],
+ ["releaseDate", ["Product"], ["Date"], ""],
+ ["releaseNotes", ["SoftwareApplication"], ["Text", "URL"], ""],
+ ["releaseOf", ["MusicRelease"], ["MusicAlbum"], ""],
+ ["releasedEvent", ["CreativeWork"], ["PublicationEvent"], ""],
+ ["relevantOccupation", ["JobPosting"], ["Occupation"], ""],
+ ["relevantSpecialty", ["MedicalEntity"], ["MedicalSpecialty"], ""],
+ ["remainingAttendeeCapacity", ["Event"], ["Integer"], ""],
+ ["renegotiableLoan", ["LoanOrCredit"], ["Boolean"], ""],
+ ["repeatCount", ["Schedule"], ["Integer"], ""],
+ ["repeatFrequency", ["Schedule"], ["Duration", "Text"], ""],
+ ["repetitions", ["ExercisePlan"], ["Number", "QuantitativeValue"], ""],
+ ["replacee", ["ReplaceAction"], ["Thing"], ""],
+ ["replacer", ["ReplaceAction"], ["Thing"], ""],
+ ["replyToUrl", ["UserComments"], ["URL"], ""],
+ ["reportNumber", ["Report"], ["Text"], ""],
+ ["representativeOfPage", ["ImageObject"], ["Boolean"], ""],
+ ["requiredCollateral", ["LoanOrCredit"], ["Text", "Thing"], ""],
+ ["requiredGender", ["PeopleAudience"], ["Text"], ""],
+ ["requiredMaxAge", ["PeopleAudience"], ["Integer"], ""],
+ ["requiredMinAge", ["PeopleAudience"], ["Integer"], ""],
+ [
+ "requiredQuantity",
+ ["HowToItem"],
+ ["Number", "QuantitativeValue", "Text"],
+ "",
+ ],
+ [
+ "requirements",
+ ["SoftwareApplication"],
+ ["Text", "URL"],
+ "softwareRequirements",
+ ],
+ [
+ "requiresSubscription",
+ ["ActionAccessSpecification", "MediaObject"],
+ ["Boolean", "MediaSubscription"],
+ "",
+ ],
+ ["reservationFor", ["Reservation"], ["Thing"], ""],
+ ["reservationId", ["Reservation"], ["Text"], ""],
+ ["reservationStatus", ["Reservation"], ["ReservationStatusType"], ""],
+ ["reservedTicket", ["Reservation"], ["Ticket"], ""],
+ ["responsibilities", ["JobPosting", "Occupation"], ["Text"], ""],
+ ["restPeriods", ["ExercisePlan"], ["QuantitativeValue", "Text"], ""],
+ [
+ "restockingFee",
+ ["MerchantReturnPolicy", "MerchantReturnPolicySeasonalOverride"],
+ ["MonetaryAmount", "Number"],
+ "",
+ ],
+ ["result", ["Action"], ["Thing"], ""],
+ ["resultComment", ["CommentAction", "ReplyAction"], ["Comment"], ""],
+ ["resultReview", ["ReviewAction"], ["Review"], ""],
+ [
+ "returnFees",
+ ["MerchantReturnPolicy", "MerchantReturnPolicySeasonalOverride"],
+ ["ReturnFeesEnumeration"],
+ "",
+ ],
+ [
+ "returnLabelSource",
+ ["MerchantReturnPolicy"],
+ ["ReturnLabelSourceEnumeration"],
+ "",
+ ],
+ [
+ "returnMethod",
+ ["MerchantReturnPolicy", "MerchantReturnPolicySeasonalOverride"],
+ ["ReturnMethodEnumeration"],
+ "",
+ ],
+ [
+ "returnPolicyCategory",
+ ["MerchantReturnPolicy", "MerchantReturnPolicySeasonalOverride"],
+ ["MerchantReturnEnumeration"],
+ "",
+ ],
+ ["returnPolicyCountry", ["MerchantReturnPolicy"], ["Country", "Text"], ""],
+ [
+ "returnPolicySeasonalOverride",
+ ["MerchantReturnPolicy"],
+ ["MerchantReturnPolicySeasonalOverride"],
+ "",
+ ],
+ [
+ "returnShippingFeesAmount",
+ ["MerchantReturnPolicy", "MerchantReturnPolicySeasonalOverride"],
+ ["MonetaryAmount"],
+ "",
+ ],
+ [
+ "review",
+ [
+ "Brand",
+ "CreativeWork",
+ "Event",
+ "Offer",
+ "Organization",
+ "Place",
+ "Product",
+ "Service",
+ ],
+ ["Review"],
+ "",
+ ],
+ [
+ "reviewAspect",
+ ["Guide", "Rating", "Review"],
+ ["StructuredValue", "Text"],
+ "",
+ ],
+ ["reviewBody", ["Review"], ["Text"], ""],
+ ["reviewCount", ["AggregateRating"], ["Integer"], ""],
+ ["reviewRating", ["Review"], ["Rating"], ""],
+ ["reviewedBy", ["WebPage"], ["Organization", "Person"], ""],
+ [
+ "reviews",
+ ["CreativeWork", "Offer", "Organization", "Place", "Product"],
+ ["Review"],
+ "review",
+ ],
+ ["riskFactor", ["MedicalCondition"], ["MedicalRiskFactor"], ""],
+ ["risks", ["Diet"], ["Text"], ""],
+ ["roleName", ["Role"], ["Text", "URL"], ""],
+ ["roofLoad", ["BusOrCoach", "Car"], ["QuantitativeValue"], ""],
+ ["rsvpResponse", ["RsvpAction"], ["RsvpResponseType"], ""],
+ ["runsTo", ["LymphaticVessel"], ["Vessel"], ""],
+ ["runtime", ["SoftwareSourceCode"], ["Text"], "runtimePlatform"],
+ [
+ "runtimePlatform",
+ ["SoftwareApplication", "SoftwareSourceCode"],
+ ["RuntimePlatform", "Text"],
+ "",
+ ],
+ ["rxcui", ["Drug"], ["Text"], ""],
+ ["safetyConsideration", ["DietarySupplement"], ["Text"], ""],
+ ["salaryCurrency", ["EmployeeRole", "JobPosting"], ["Text"], ""],
+ [
+ "salaryUponCompletion",
+ ["EducationalOccupationalProgram"],
+ ["MonetaryAmountDistribution"],
+ "",
+ ],
+ ["sameAs", ["Thing"], ["URL"], ""],
+ ["sampleType", ["SoftwareSourceCode"], ["Text"], "codeSampleType"],
+ ["saturatedFatContent", ["NutritionInformation"], ["Mass"], ""],
+ ["scheduleTimezone", ["Schedule"], ["Text"], ""],
+ ["scheduledPaymentDate", ["Invoice"], ["Date"], ""],
+ ["scheduledTime", ["PlanAction"], ["Date", "DateTime"], ""],
+ ["schemaVersion", ["CreativeWork"], ["Text", "URL"], ""],
+ ["schoolClosuresInfo", ["SpecialAnnouncement"], ["URL", "WebContent"], ""],
+ ["screenCount", ["MovieTheater"], ["Number"], ""],
+ ["screenshot", ["SoftwareApplication"], ["ImageObject", "URL"], ""],
+ ["sdDatePublished", ["CreativeWork"], ["Date"], ""],
+ ["sdLicense", ["CreativeWork"], ["CreativeWork", "URL"], ""],
+ ["sdPublisher", ["CreativeWork"], ["Organization", "Person"], ""],
+ [
+ "season",
+ ["RadioSeries", "TVSeries", "VideoGameSeries"],
+ ["CreativeWorkSeason", "URL"],
+ "containsSeason",
+ ],
+ ["seasonNumber", ["CreativeWorkSeason"], ["Integer", "Text"], ""],
+ [
+ "seasonalOverride",
+ ["ShippingConditions"],
+ ["OpeningHoursSpecification"],
+ "",
+ ],
+ [
+ "seasons",
+ ["RadioSeries", "TVSeries", "VideoGameSeries"],
+ ["CreativeWorkSeason"],
+ "season",
+ ],
+ ["seatNumber", ["Seat"], ["Text"], ""],
+ ["seatRow", ["Seat"], ["Text"], ""],
+ ["seatSection", ["Seat"], ["Text"], ""],
+ ["seatingCapacity", ["Vehicle"], ["Number", "QuantitativeValue"], ""],
+ ["seatingType", ["Seat"], ["QualitativeValue", "Text"], ""],
+ [
+ "secondaryPrevention",
+ ["MedicalCondition"],
+ ["Drug", "DrugClass", "LifestyleModification", "MedicalTherapy"],
+ "",
+ ],
+ ["securityClearanceRequirement", ["JobPosting"], ["Text", "URL"], ""],
+ ["securityScreening", ["FlightReservation"], ["Text"], ""],
+ ["seeks", ["Organization", "Person"], ["Demand"], ""],
+ [
+ "seller",
+ ["BuyAction", "Demand", "Flight", "Offer", "Order"],
+ ["Organization", "Person"],
+ "",
+ ],
+ [
+ "sender",
+ ["Message", "ReceiveAction"],
+ ["Audience", "Organization", "Person"],
+ "",
+ ],
+ ["sensoryRequirement", ["JobPosting"], ["DefinedTerm", "Text", "URL"], ""],
+ ["sensoryUnit", ["Nerve"], ["AnatomicalStructure", "SuperficialAnatomy"], ""],
+ ["serialNumber", ["Demand", "IndividualProduct", "Offer"], ["Text"], ""],
+ [
+ "seriousAdverseOutcome",
+ ["MedicalDevice", "MedicalTherapy"],
+ ["MedicalEntity"],
+ "",
+ ],
+ ["serverStatus", ["GameServer"], ["GameServerStatus"], ""],
+ ["servesCuisine", ["FoodEstablishment"], ["Text"], ""],
+ [
+ "serviceArea",
+ ["ContactPoint", "Organization", "Service"],
+ ["AdministrativeArea", "GeoShape", "Place"],
+ "areaServed",
+ ],
+ ["serviceAudience", ["Service"], ["Audience"], "audience"],
+ ["serviceLocation", ["ServiceChannel"], ["Place"], ""],
+ ["serviceOperator", ["GovernmentService"], ["Organization"], ""],
+ ["serviceOutput", ["Service"], ["Thing"], ""],
+ ["servicePhone", ["ServiceChannel"], ["ContactPoint"], ""],
+ ["servicePostalAddress", ["ServiceChannel"], ["PostalAddress"], ""],
+ ["serviceSmsNumber", ["ServiceChannel"], ["ContactPoint"], ""],
+ ["serviceType", ["Service"], ["GovernmentBenefitsType", "Text"], ""],
+ ["serviceUrl", ["ServiceChannel"], ["URL"], ""],
+ ["servingSize", ["NutritionInformation"], ["Text"], ""],
+ ["sha256", ["MediaObject"], ["Text"], ""],
+ ["sharedContent", ["Comment", "SocialMediaPosting"], ["CreativeWork"], ""],
+ ["shippingConditions", ["ShippingService"], ["ShippingConditions"], ""],
+ [
+ "shippingDestination",
+ [
+ "DeliveryTimeSettings",
+ "OfferShippingDetails",
+ "ShippingConditions",
+ "ShippingRateSettings",
+ ],
+ ["DefinedRegion"],
+ "",
+ ],
+ ["shippingDetails", ["Offer"], ["OfferShippingDetails"], ""],
+ [
+ "shippingOrigin",
+ ["OfferShippingDetails", "ShippingConditions"],
+ ["DefinedRegion"],
+ "",
+ ],
+ [
+ "shippingRate",
+ ["OfferShippingDetails", "ShippingConditions", "ShippingRateSettings"],
+ ["MonetaryAmount", "ShippingRateSettings"],
+ "",
+ ],
+ ["sibling", ["Person"], ["Person"], ""],
+ ["siblings", ["Person"], ["Person"], "sibling"],
+ ["signDetected", ["MedicalTest"], ["MedicalSign"], ""],
+ ["signOrSymptom", ["MedicalCondition"], ["MedicalSignOrSymptom"], ""],
+ ["significance", ["SuperficialAnatomy"], ["Text"], ""],
+ ["significantLink", ["WebPage"], ["URL"], ""],
+ ["significantLinks", ["WebPage"], ["URL"], "significantLink"],
+ [
+ "size",
+ ["CreativeWork", "Product"],
+ ["DefinedTerm", "QuantitativeValue", "SizeSpecification", "Text"],
+ "",
+ ],
+ ["sizeGroup", ["SizeSpecification"], ["SizeGroupEnumeration", "Text"], ""],
+ ["sizeSystem", ["SizeSpecification"], ["SizeSystemEnumeration", "Text"], ""],
+ [
+ "skills",
+ ["JobPosting", "Occupation", "Organization", "Person"],
+ ["DefinedTerm", "Text"],
+ "",
+ ],
+ ["sku", ["Demand", "Offer", "Product"], ["Text"], ""],
+ [
+ "slogan",
+ ["Brand", "Organization", "Place", "Product", "Service"],
+ ["Text"],
+ "",
+ ],
+ ["smiles", ["MolecularEntity"], ["Text"], ""],
+ ["smokingAllowed", ["Place"], ["Boolean"], ""],
+ ["sodiumContent", ["NutritionInformation"], ["Mass"], ""],
+ ["softwareAddOn", ["SoftwareApplication"], ["SoftwareApplication"], ""],
+ ["softwareHelp", ["SoftwareApplication"], ["CreativeWork"], ""],
+ [
+ "softwareRequirements",
+ ["SoftwareApplication"],
+ ["SoftwareApplication", "Text", "URL"],
+ "",
+ ],
+ ["softwareVersion", ["SoftwareApplication"], ["Text"], ""],
+ ["source", ["InstantaneousEvent"], ["Thing"], ""],
+ ["sourceOrganization", ["CreativeWork"], ["Organization"], ""],
+ ["sourcedFrom", ["Nerve"], ["BrainStructure"], ""],
+ ["spatial", ["CreativeWork"], ["Place"], ""],
+ ["spatialCoverage", ["CreativeWork"], ["Place"], ""],
+ ["speakable", ["Article", "WebPage"], ["SpeakableSpecification", "URL"], ""],
+ ["specialCommitments", ["JobPosting"], ["Text"], ""],
+ [
+ "specialOpeningHoursSpecification",
+ ["Place"],
+ ["OpeningHoursSpecification"],
+ "",
+ ],
+ ["specialty", ["WebPage"], ["Specialty"], ""],
+ ["speechToTextMarkup", ["PronounceableText"], ["Text"], ""],
+ ["speed", ["Vehicle"], ["QuantitativeValue"], ""],
+ ["spokenByCharacter", ["Quotation"], ["Organization", "Person"], ""],
+ [
+ "sponsor",
+ [
+ "CreativeWork",
+ "Event",
+ "Grant",
+ "MedicalStudy",
+ "Organization",
+ "Person",
+ ],
+ ["Organization", "Person"],
+ "",
+ ],
+ ["sport", ["SportsEvent", "SportsOrganization"], ["Text", "URL"], ""],
+ [
+ "sportsActivityLocation",
+ ["ExerciseAction"],
+ ["SportsActivityLocation"],
+ "",
+ ],
+ ["sportsEvent", ["ExerciseAction"], ["SportsEvent"], ""],
+ ["sportsTeam", ["ExerciseAction"], ["SportsTeam"], ""],
+ ["spouse", ["Person"], ["Person"], ""],
+ ["stage", ["MedicalCondition"], ["MedicalConditionStage"], ""],
+ ["stageAsNumber", ["MedicalConditionStage"], ["Number"], ""],
+ ["starRating", ["FoodEstablishment", "LodgingBusiness"], ["Rating"], ""],
+ [
+ "startDate",
+ [
+ "CreativeWorkSeason",
+ "CreativeWorkSeries",
+ "DatedMoneySpecification",
+ "EducationalOccupationalProgram",
+ "Event",
+ "MerchantReturnPolicySeasonalOverride",
+ "Role",
+ "Schedule",
+ ],
+ ["Date", "DateTime"],
+ "",
+ ],
+ ["startOffset", ["Clip", "SeekToAction"], ["HyperTocEntry", "Number"], ""],
+ [
+ "startTime",
+ [
+ "Action",
+ "FoodEstablishmentReservation",
+ "InteractionCounter",
+ "MediaObject",
+ "Schedule",
+ ],
+ ["DateTime", "Time"],
+ "",
+ ],
+ ["statType", ["StatisticalVariable"], ["Property", "Text", "URL"], ""],
+ [
+ "status",
+ ["MedicalCondition", "MedicalProcedure", "MedicalStudy"],
+ ["EventStatusType", "MedicalStudyStatus", "Text"],
+ "",
+ ],
+ ["steeringPosition", ["Vehicle"], ["SteeringPositionValue"], ""],
+ [
+ "step",
+ ["HowTo"],
+ ["CreativeWork", "HowToSection", "HowToStep", "Text"],
+ "",
+ ],
+ ["stepValue", ["PropertyValueSpecification"], ["Number"], ""],
+ [
+ "steps",
+ ["HowTo", "HowToSection"],
+ ["CreativeWork", "ItemList", "Text"],
+ "step",
+ ],
+ ["storageRequirements", ["SoftwareApplication"], ["Text", "URL"], ""],
+ ["streetAddress", ["PostalAddress"], ["Text"], ""],
+ ["strengthUnit", ["DrugStrength"], ["Text"], ""],
+ ["strengthValue", ["DrugStrength"], ["Number"], ""],
+ ["structuralClass", ["Joint"], ["Text"], ""],
+ ["study", ["MedicalEntity"], ["MedicalStudy"], ""],
+ [
+ "studyDesign",
+ ["MedicalObservationalStudy"],
+ ["MedicalObservationalStudyDesign"],
+ "",
+ ],
+ ["studyLocation", ["MedicalStudy"], ["AdministrativeArea"], ""],
+ ["studySubject", ["MedicalStudy"], ["MedicalEntity"], ""],
+ ["subEvent", ["Event"], ["Event"], ""],
+ ["subEvents", ["Event"], ["Event"], "subEvent"],
+ ["subOrganization", ["Organization"], ["Organization"], ""],
+ ["subReservation", ["ReservationPackage"], ["Reservation"], ""],
+ ["subStageSuffix", ["MedicalConditionStage"], ["Text"], ""],
+ ["subStructure", ["AnatomicalStructure"], ["AnatomicalStructure"], ""],
+ ["subTest", ["MedicalTestPanel"], ["MedicalTest"], ""],
+ ["subTrip", ["Trip"], ["Trip"], ""],
+ ["subjectOf", ["Thing"], ["CreativeWork", "Event"], ""],
+ [
+ "subtitleLanguage",
+ ["BroadcastEvent", "Movie", "ScreeningEvent", "TVEpisode"],
+ ["Language", "Text"],
+ "",
+ ],
+ ["successorOf", ["ProductModel"], ["ProductModel"], ""],
+ ["sugarContent", ["NutritionInformation"], ["Mass"], ""],
+ [
+ "suggestedAge",
+ ["PeopleAudience", "SizeSpecification"],
+ ["QuantitativeValue"],
+ "",
+ ],
+ ["suggestedAnswer", ["Question"], ["Answer", "ItemList"], ""],
+ [
+ "suggestedGender",
+ ["PeopleAudience", "SizeSpecification"],
+ ["GenderType", "Text"],
+ "",
+ ],
+ ["suggestedMaxAge", ["PeopleAudience"], ["Number"], ""],
+ [
+ "suggestedMeasurement",
+ ["PeopleAudience", "SizeSpecification"],
+ ["QuantitativeValue"],
+ "",
+ ],
+ ["suggestedMinAge", ["PeopleAudience"], ["Number"], ""],
+ ["suitableForDiet", ["MenuItem", "Recipe"], ["Diet", "RestrictedDiet"], ""],
+ ["superEvent", ["Event"], ["Event"], ""],
+ [
+ "supersededBy",
+ ["Class", "Enumeration", "Property"],
+ ["Class", "Enumeration", "Property"],
+ "",
+ ],
+ ["supply", ["HowTo", "HowToDirection"], ["HowToSupply", "Text"], ""],
+ ["supplyTo", ["Artery"], ["AnatomicalStructure"], ""],
+ ["supportingData", ["SoftwareApplication"], ["DataFeed"], ""],
+ ["surface", ["VisualArtwork"], ["Text", "URL"], "artworkSurface"],
+ ["syllabusSections", ["Course"], ["Syllabus"], ""],
+ ["target", ["Action"], ["EntryPoint", "URL"], ""],
+ ["targetCollection", ["UpdateAction"], ["Thing"], ""],
+ ["targetDescription", ["AlignmentObject"], ["Text"], ""],
+ ["targetName", ["AlignmentObject"], ["Text"], ""],
+ ["targetPlatform", ["APIReference"], ["Text"], ""],
+ ["targetPopulation", ["DietarySupplement", "DoseSchedule"], ["Text"], ""],
+ ["targetProduct", ["SoftwareSourceCode"], ["SoftwareApplication"], ""],
+ ["targetUrl", ["AlignmentObject"], ["URL"], ""],
+ ["taxID", ["Organization", "Person"], ["Text"], ""],
+ ["taxonRank", ["Taxon"], ["PropertyValue", "Text", "URL"], ""],
+ [
+ "taxonomicRange",
+ ["BioChemEntity"],
+ ["DefinedTerm", "Taxon", "Text", "URL"],
+ "",
+ ],
+ [
+ "teaches",
+ ["CreativeWork", "EducationEvent", "LearningResource"],
+ ["DefinedTerm", "Text"],
+ "",
+ ],
+ [
+ "telephone",
+ ["ContactPoint", "Organization", "Person", "Place"],
+ ["Text"],
+ "",
+ ],
+ ["temporal", ["CreativeWork"], ["DateTime", "Text"], ""],
+ ["temporalCoverage", ["CreativeWork"], ["DateTime", "Text", "URL"], ""],
+ ["termCode", ["DefinedTerm"], ["Text"], ""],
+ ["termDuration", ["EducationalOccupationalProgram"], ["Duration"], ""],
+ ["termsOfService", ["Service"], ["Text", "URL"], ""],
+ ["termsPerYear", ["EducationalOccupationalProgram"], ["Number"], ""],
+ ["text", ["CreativeWork"], ["Text"], ""],
+ ["textValue", ["PronounceableText"], ["Text"], ""],
+ ["thumbnail", ["CreativeWork"], ["ImageObject"], ""],
+ ["thumbnailUrl", ["CreativeWork"], ["URL"], ""],
+ ["tickerSymbol", ["Corporation"], ["Text"], ""],
+ ["ticketNumber", ["Ticket"], ["Text"], ""],
+ ["ticketToken", ["Ticket"], ["Text", "URL"], ""],
+ ["ticketedSeat", ["Ticket"], ["Seat"], ""],
+ ["timeOfDay", ["EducationalOccupationalProgram"], ["Text"], ""],
+ ["timeRequired", ["CreativeWork"], ["Duration"], ""],
+ ["timeToComplete", ["EducationalOccupationalProgram"], ["Duration"], ""],
+ ["timestamp", ["InstantaneousEvent"], ["DateTime"], ""],
+ ["tissueSample", ["PathologyTest"], ["Text"], ""],
+ ["title", ["JobPosting"], ["Text"], ""],
+ [
+ "titleEIDR",
+ ["Movie", "TVEpisode", "TVSeason", "TVSeries"],
+ ["Text", "URL"],
+ "",
+ ],
+ [
+ "toLocation",
+ ["ExerciseAction", "InsertAction", "MoveAction", "TransferAction"],
+ ["Place"],
+ "",
+ ],
+ [
+ "toRecipient",
+ ["Message"],
+ ["Audience", "ContactPoint", "Organization", "Person"],
+ "",
+ ],
+ ["tocContinuation", ["HyperTocEntry"], ["HyperTocEntry"], ""],
+ ["tocEntry", ["HyperToc"], ["HyperTocEntry"], ""],
+ ["tongueWeight", ["Vehicle"], ["QuantitativeValue"], ""],
+ ["tool", ["HowTo", "HowToDirection"], ["HowToTool", "Text"], ""],
+ ["torque", ["EngineSpecification"], ["QuantitativeValue"], ""],
+ ["totalHistoricalEnrollment", ["Course"], ["Integer"], ""],
+ ["totalJobOpenings", ["JobPosting"], ["Integer"], ""],
+ [
+ "totalPaymentDue",
+ ["Invoice"],
+ ["MonetaryAmount", "PriceSpecification"],
+ "",
+ ],
+ [
+ "totalPrice",
+ ["Reservation", "Ticket"],
+ ["Number", "PriceSpecification", "Text"],
+ "",
+ ],
+ ["totalTime", ["HowTo", "HowToDirection"], ["Duration"], ""],
+ [
+ "tourBookingPage",
+ ["Accommodation", "ApartmentComplex", "Place"],
+ ["URL"],
+ "",
+ ],
+ [
+ "touristType",
+ ["TouristAttraction", "TouristDestination", "TouristTrip"],
+ ["Audience", "Text"],
+ "",
+ ],
+ [
+ "track",
+ ["MusicGroup", "MusicPlaylist"],
+ ["ItemList", "MusicRecording"],
+ "",
+ ],
+ ["trackingNumber", ["ParcelDelivery"], ["Text"], ""],
+ ["trackingUrl", ["ParcelDelivery"], ["URL"], ""],
+ ["tracks", ["MusicGroup", "MusicPlaylist"], ["MusicRecording"], "track"],
+ [
+ "trailer",
+ [
+ "CreativeWorkSeason",
+ "Episode",
+ "Movie",
+ "MovieSeries",
+ "RadioSeries",
+ "TVSeries",
+ "VideoGame",
+ "VideoGameSeries",
+ ],
+ ["VideoObject"],
+ "",
+ ],
+ ["trailerWeight", ["Vehicle"], ["QuantitativeValue"], ""],
+ ["trainName", ["TrainTrip"], ["Text"], ""],
+ ["trainNumber", ["TrainTrip"], ["Text"], ""],
+ [
+ "trainingSalary",
+ ["EducationalOccupationalProgram", "WorkBasedProgram"],
+ ["MonetaryAmountDistribution"],
+ "",
+ ],
+ ["transFatContent", ["NutritionInformation"], ["Mass"], ""],
+ ["transcript", ["AudioObject", "VideoObject"], ["Text"], ""],
+ [
+ "transitTime",
+ ["ShippingConditions", "ShippingDeliveryTime"],
+ ["QuantitativeValue", "ServicePeriod"],
+ "",
+ ],
+ ["translationOfWork", ["CreativeWork"], ["CreativeWork"], ""],
+ ["translator", ["CreativeWork", "Event"], ["Organization", "Person"], ""],
+ ["transmissionMethod", ["InfectiousDisease"], ["Text"], ""],
+ ["travelBans", ["SpecialAnnouncement"], ["URL", "WebContent"], ""],
+ ["trialDesign", ["MedicalTrial"], ["MedicalTrialDesign"], ""],
+ ["tributary", ["Vein"], ["AnatomicalStructure"], ""],
+ ["tripOrigin", ["Trip"], ["Place"], ""],
+ ["typeOfBed", ["BedDetails"], ["BedType", "Text"], ""],
+ [
+ "typeOfGood",
+ ["OwnershipInfo", "TypeAndQuantityNode"],
+ ["Product", "Service"],
+ "",
+ ],
+ ["typicalAgeRange", ["CreativeWork", "Event"], ["Text"], ""],
+ [
+ "typicalCreditsPerTerm",
+ ["EducationalOccupationalProgram"],
+ ["Integer", "StructuredValue"],
+ "",
+ ],
+ ["typicalTest", ["MedicalCondition"], ["MedicalTest"], ""],
+ ["underName", ["Reservation", "Ticket"], ["Organization", "Person"], ""],
+ [
+ "unitCode",
+ [
+ "PropertyValue",
+ "QuantitativeValue",
+ "TypeAndQuantityNode",
+ "UnitPriceSpecification",
+ ],
+ ["Text", "URL"],
+ "",
+ ],
+ [
+ "unitText",
+ [
+ "PropertyValue",
+ "QuantitativeValue",
+ "TypeAndQuantityNode",
+ "UnitPriceSpecification",
+ ],
+ ["Text"],
+ "",
+ ],
+ [
+ "unnamedSourcesPolicy",
+ ["NewsMediaOrganization", "Organization"],
+ ["CreativeWork", "URL"],
+ "",
+ ],
+ ["unsaturatedFatContent", ["NutritionInformation"], ["Mass"], ""],
+ ["uploadDate", ["MediaObject"], ["Date", "DateTime"], ""],
+ ["upvoteCount", ["Comment"], ["Integer"], ""],
+ ["url", ["Thing"], ["URL"], ""],
+ ["urlTemplate", ["EntryPoint"], ["Text"], ""],
+ ["usNPI", ["Physician"], ["Text"], ""],
+ ["usageInfo", ["CreativeWork"], ["CreativeWork", "URL"], ""],
+ ["usedToDiagnose", ["MedicalTest"], ["MedicalCondition"], ""],
+ ["userInteractionCount", ["InteractionCounter"], ["Integer"], ""],
+ ["usesDevice", ["MedicalTest"], ["MedicalDevice"], ""],
+ ["usesHealthPlanIdStandard", ["HealthInsurancePlan"], ["Text", "URL"], ""],
+ ["utterances", ["HyperTocEntry"], ["Text"], ""],
+ ["validFor", ["Credential", "Permit"], ["Duration"], ""],
+ [
+ "validForMemberTier",
+ [
+ "MerchantReturnPolicy",
+ "Offer",
+ "OfferShippingDetails",
+ "PriceSpecification",
+ "ShippingService",
+ ],
+ ["MemberProgramTier"],
+ "",
+ ],
+ [
+ "validFrom",
+ [
+ "Certification",
+ "Demand",
+ "FinancialIncentive",
+ "LocationFeatureSpecification",
+ "MonetaryAmount",
+ "Offer",
+ "OpeningHoursSpecification",
+ "Permit",
+ "PriceSpecification",
+ ],
+ ["Date", "DateTime"],
+ "",
+ ],
+ [
+ "validIn",
+ ["Certification", "Credential", "Permit"],
+ ["AdministrativeArea"],
+ "",
+ ],
+ [
+ "validThrough",
+ [
+ "Demand",
+ "FinancialIncentive",
+ "JobPosting",
+ "LocationFeatureSpecification",
+ "MonetaryAmount",
+ "Offer",
+ "OpeningHoursSpecification",
+ "PriceSpecification",
+ ],
+ ["Date", "DateTime"],
+ "",
+ ],
+ ["validUntil", ["Permit"], ["Date"], ""],
+ [
+ "value",
+ ["MonetaryAmount", "PropertyValue", "QuantitativeValue"],
+ ["Boolean", "Number", "StructuredValue", "Text"],
+ "",
+ ],
+ ["valueAddedTaxIncluded", ["PriceSpecification"], ["Boolean"], ""],
+ ["valueMaxLength", ["PropertyValueSpecification"], ["Number"], ""],
+ ["valueMinLength", ["PropertyValueSpecification"], ["Number"], ""],
+ ["valueName", ["PropertyValueSpecification"], ["Text"], ""],
+ ["valuePattern", ["PropertyValueSpecification"], ["Text"], ""],
+ [
+ "valueReference",
+ ["PropertyValue", "QualitativeValue", "QuantitativeValue"],
+ [
+ "DefinedTerm",
+ "Enumeration",
+ "MeasurementTypeEnumeration",
+ "PropertyValue",
+ "QualitativeValue",
+ "QuantitativeValue",
+ "StructuredValue",
+ "Text",
+ ],
+ "",
+ ],
+ ["valueRequired", ["PropertyValueSpecification"], ["Boolean"], ""],
+ [
+ "variableMeasured",
+ ["Dataset", "Observation"],
+ ["Property", "PropertyValue", "StatisticalVariable", "Text"],
+ "",
+ ],
+ ["variantCover", ["ComicIssue"], ["Text"], ""],
+ ["variesBy", ["ProductGroup"], ["DefinedTerm", "Text"], ""],
+ ["vatID", ["Organization", "Person"], ["Text"], ""],
+ ["vehicleConfiguration", ["Vehicle"], ["Text"], ""],
+ ["vehicleEngine", ["Vehicle"], ["EngineSpecification"], ""],
+ ["vehicleIdentificationNumber", ["Vehicle"], ["Text"], ""],
+ ["vehicleInteriorColor", ["Vehicle"], ["Text"], ""],
+ ["vehicleInteriorType", ["Vehicle"], ["Text"], ""],
+ ["vehicleModelDate", ["Vehicle"], ["Date"], ""],
+ ["vehicleSeatingCapacity", ["Vehicle"], ["Number", "QuantitativeValue"], ""],
+ ["vehicleSpecialUsage", ["Vehicle"], ["CarUsageType", "Text"], ""],
+ ["vehicleTransmission", ["Vehicle"], ["QualitativeValue", "Text", "URL"], ""],
+ ["vendor", ["BuyAction"], ["Organization", "Person"], "seller"],
+ [
+ "verificationFactCheckingPolicy",
+ ["NewsMediaOrganization"],
+ ["CreativeWork", "URL"],
+ "",
+ ],
+ ["version", ["CreativeWork"], ["Number", "Text"], ""],
+ ["video", ["CreativeWork"], ["Clip", "VideoObject"], ""],
+ [
+ "videoFormat",
+ ["BroadcastEvent", "BroadcastService", "ScreeningEvent"],
+ ["Text"],
+ "",
+ ],
+ ["videoFrameSize", ["VideoObject"], ["Text"], ""],
+ ["videoQuality", ["VideoObject"], ["Text"], ""],
+ ["volumeNumber", ["PublicationVolume"], ["Integer", "Text"], ""],
+ ["warning", ["Drug"], ["Text", "URL"], ""],
+ ["warranty", ["Demand", "Offer"], ["WarrantyPromise"], ""],
+ [
+ "warrantyPromise",
+ ["BuyAction", "SellAction"],
+ ["WarrantyPromise"],
+ "warranty",
+ ],
+ ["warrantyScope", ["WarrantyPromise"], ["WarrantyScope"], ""],
+ ["webCheckinTime", ["Flight"], ["DateTime"], ""],
+ [
+ "webFeed",
+ ["PodcastSeries", "SpecialAnnouncement"],
+ ["DataFeed", "URL"],
+ "",
+ ],
+ [
+ "weight",
+ [
+ "OfferShippingDetails",
+ "Person",
+ "Product",
+ "ShippingConditions",
+ "VisualArtwork",
+ ],
+ ["Mass", "QuantitativeValue"],
+ "",
+ ],
+ ["weightPercentage", ["ShippingRateSettings"], ["Number"], ""],
+ ["weightTotal", ["Vehicle"], ["QuantitativeValue"], ""],
+ ["wheelbase", ["Vehicle"], ["QuantitativeValue"], ""],
+ [
+ "width",
+ [
+ "MediaObject",
+ "OfferShippingDetails",
+ "Product",
+ "ShippingConditions",
+ "VisualArtwork",
+ ],
+ ["Distance", "QuantitativeValue"],
+ "",
+ ],
+ ["winner", ["LoseAction"], ["Person"], ""],
+ ["wordCount", ["Article", "CreativeWork"], ["Integer"], ""],
+ ["workExample", ["CreativeWork"], ["CreativeWork"], ""],
+ ["workFeatured", ["Event"], ["CreativeWork"], ""],
+ ["workHours", ["JobPosting"], ["Text"], ""],
+ ["workLocation", ["Person"], ["ContactPoint", "Place"], ""],
+ ["workPerformed", ["Event"], ["CreativeWork"], ""],
+ ["workPresented", ["ScreeningEvent"], ["Movie"], ""],
+ ["workTranslation", ["CreativeWork"], ["CreativeWork"], ""],
+ ["workload", ["ExercisePlan"], ["Energy", "QuantitativeValue"], ""],
+ ["worksFor", ["Person"], ["Organization"], ""],
+ ["worstRating", ["Rating"], ["Number", "Text"], ""],
+ ["xpath", ["SpeakableSpecification", "WebPageElement"], ["XPathType"], ""],
+ ["yearBuilt", ["Accommodation"], ["Number"], ""],
+ ["yearlyRevenue", ["BusinessAudience"], ["QuantitativeValue"], ""],
+ ["yearsInOperation", ["BusinessAudience"], ["QuantitativeValue"], ""],
+ ["yield", ["HowTo"], ["QuantitativeValue", "Text"], ""],
+];
diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts
index b4fe2f465a..a5afd97d5f 100644
--- a/packages/sdk/src/index.ts
+++ b/packages/sdk/src/index.ts
@@ -23,6 +23,7 @@ export * from "./resources-generator";
export * from "./page-meta-generator";
export * from "./url-pattern";
export * from "./link-utils";
+export * from "./json-ld";
export * from "./css";
export * from "./__generated__/tags";
export {
diff --git a/packages/sdk/src/json-ld-utils.ts b/packages/sdk/src/json-ld-utils.ts
new file mode 100644
index 0000000000..3dbfe46c12
--- /dev/null
+++ b/packages/sdk/src/json-ld-utils.ts
@@ -0,0 +1,18 @@
+export const isJsonObject = (
+ value: unknown
+): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && Array.isArray(value) === false;
+
+export const appendJsonPath = (path: string, key: string | number) =>
+ typeof key === "number"
+ ? `${path}[${key}]`
+ : /^[A-Za-z_$][\w$]*$/.test(key)
+ ? `${path}.${key}`
+ : `${path}[${JSON.stringify(key)}]`;
+
+export const getJsonLdTypes = (value: unknown) =>
+ typeof value === "string"
+ ? [value]
+ : Array.isArray(value) && value.every((item) => typeof item === "string")
+ ? value
+ : [];
diff --git a/packages/sdk/src/json-ld.test.ts b/packages/sdk/src/json-ld.test.ts
new file mode 100644
index 0000000000..a18012e697
--- /dev/null
+++ b/packages/sdk/src/json-ld.test.ts
@@ -0,0 +1,272 @@
+import { expect, test } from "vitest";
+import { hasTopLevelJsonLdContext, parseJsonLd } from "./json-ld";
+import { validateJsonLdWithSchemaOrg } from "./schema-org";
+
+test("parses JSON-LD objects and arrays", () => {
+ expect(parseJsonLd('{"@context":"https://schema.org"}')).toEqual({
+ success: true,
+ value: { "@context": "https://schema.org" },
+ });
+ expect(parseJsonLd([{ "@type": "Organization" }]).success).toBe(true);
+});
+
+test.each(["invalid", '"text"', "1", "null", undefined])(
+ "rejects non-object JSON-LD %j",
+ (value) => {
+ expect(parseJsonLd(value)).toEqual({ success: false });
+ }
+);
+
+test("rejects values that cannot be represented as JSON", () => {
+ const cyclic: Record<string, unknown> = {};
+ cyclic.self = cyclic;
+
+ for (const value of [
+ new Date(),
+ new Map(),
+ { nested: undefined },
+ { nested: () => undefined },
+ { nested: Number.NaN },
+ cyclic,
+ ]) {
+ expect(parseJsonLd(value)).toEqual({ success: false });
+ }
+});
+
+test("detects context on objects and top-level array entries", () => {
+ expect(hasTopLevelJsonLdContext({ "@context": "https://schema.org" })).toBe(
+ true
+ );
+ expect(hasTopLevelJsonLdContext([{ "@context": "https://schema.org" }])).toBe(
+ true
+ );
+ expect(hasTopLevelJsonLdContext({ "@type": "Organization" })).toBe(false);
+});
+
+test("validates JSON-LD keyword shapes", () => {
+ expect(
+ validateJsonLdWithSchemaOrg({
+ "@context": "https://schema.org",
+ "@type": 1,
+ "@id": {},
+ })
+ ).toMatchObject({
+ success: false,
+ diagnostics: expect.arrayContaining([
+ expect.objectContaining({
+ severity: "error",
+ code: "invalid-keyword-value",
+ path: '$["@type"]',
+ }),
+ expect.objectContaining({
+ severity: "error",
+ code: "invalid-keyword-value",
+ path: '$["@id"]',
+ }),
+ ]),
+ });
+ expect(validateJsonLdWithSchemaOrg(["not a node"])).toMatchObject({
+ success: false,
+ diagnostics: [
+ expect.objectContaining({ code: "invalid-root", path: "$[0]" }),
+ ],
+ });
+});
+
+test("validates nested, reverse, and nullable language keyword shapes", () => {
+ expect(
+ validateJsonLdWithSchemaOrg({
+ "@context": "https://schema.org",
+ "@nest": { name: "Acme" },
+ "@reverse": { parentOrganization: { "@id": "https://example.com" } },
+ description: { "@value": "Description", "@language": null },
+ })
+ ).toMatchObject({ success: true });
+ expect(
+ validateJsonLdWithSchemaOrg({
+ "@context": "https://schema.org",
+ "@nest": "name",
+ "@reverse": [],
+ })
+ ).toMatchObject({
+ success: false,
+ diagnostics: expect.arrayContaining([
+ expect.objectContaining({
+ code: "invalid-keyword-value",
+ path: '$["@nest"]',
+ }),
+ expect.objectContaining({
+ code: "invalid-keyword-value",
+ path: '$["@reverse"]',
+ }),
+ ]),
+ });
+});
+
+test("accepts known Schema.org types and inherited properties", () => {
+ expect(
+ validateJsonLdWithSchemaOrg({
+ "@context": "https://schema.org",
+ "@type": "Organization",
+ name: "Acme",
+ url: "https://example.com",
+ sameAs: ["https://social.example/acme"],
+ })
+ ).toEqual({
+ success: true,
+ value: {
+ "@context": "https://schema.org",
+ "@type": "Organization",
+ name: "Acme",
+ url: "https://example.com",
+ sameAs: ["https://social.example/acme"],
+ },
+ diagnostics: [],
+ });
+});
+
+test("accepts full Schema.org IRIs and does not judge custom type IRIs", () => {
+ expect(
+ validateJsonLdWithSchemaOrg({
+ "@context": "https://schema.org",
+ "@type": [
+ "https://schema.org/Organization",
+ "https://example.com/CustomType",
+ ],
+ name: "Acme",
+ }).diagnostics
+ ).toEqual([]);
+});
+
+test("accepts primitive JSON-LD list values", () => {
+ expect(
+ validateJsonLdWithSchemaOrg({
+ "@context": "https://schema.org",
+ "@type": "ItemList",
+ itemListElement: {
+ "@list": ["One", "Two"],
+ },
+ }).diagnostics
+ ).toEqual([]);
+});
+
+test("accepts JSON-LD 1.1 JSON literals", () => {
+ expect(
+ validateJsonLdWithSchemaOrg({
+ "@context": "https://schema.org",
+ subjectOf: {
+ "@value": { theme: "dark", flags: ["a", "b"] },
+ "@type": "@json",
+ },
+ }).diagnostics
+ ).toEqual([]);
+});
+
+test("resolves mixed contexts, custom term overrides, and prefixes", () => {
+ expect(
+ validateJsonLdWithSchemaOrg({
+ "@context": [
+ "https://schema.org",
+ {
+ customField: "https://example.com/customField",
+ name: "https://example.com/name",
+ },
+ ],
+ "@type": "Organization",
+ name: "Custom vocabulary name",
+ customField: "value",
+ }).diagnostics
+ ).toEqual([]);
+
+ expect(
+ validateJsonLdWithSchemaOrg({
+ "@context": { schema: "https://schema.org/" },
+ "@type": "schema:Organization",
+ "schema:name": "Acme",
+ }).diagnostics
+ ).toEqual([]);
+});
+
+test("validates common JSON-LD context keyword types", () => {
+ expect(
+ validateJsonLdWithSchemaOrg({
+ "@context": { "@vocab": 1, "@propagate": "yes" },
+ })
+ ).toMatchObject({
+ success: false,
+ diagnostics: expect.arrayContaining([
+ expect.objectContaining({ code: "invalid-context" }),
+ ]),
+ });
+});
+
+test("rejects primitive JSON-LD context term definitions", () => {
+ expect(
+ validateJsonLdWithSchemaOrg({
+ "@context": {
+ name: 1,
+ enabled: true,
+ valid: "https://example.com/valid",
+ },
+ "@type": "Thing",
+ })
+ ).toMatchObject({
+ success: false,
+ diagnostics: expect.arrayContaining([
+ expect.objectContaining({
+ code: "invalid-context",
+ path: '$["@context"].name',
+ }),
+ expect.objectContaining({
+ code: "invalid-context",
+ path: '$["@context"].enabled',
+ }),
+ ]),
+ });
+});
+
+test("allows a nested context to reset the inherited Schema.org vocabulary", () => {
+ expect(
+ validateJsonLdWithSchemaOrg({
+ "@context": "https://schema.org",
+ "@type": "Organization",
+ subjectOf: {
+ "@context": null,
+ "@type": "CustomType",
+ customProperty: true,
+ },
+ }).diagnostics
+ ).toEqual([]);
+});
+
+test("warns about unknown, deprecated, unsupported, and incompatible Schema.org terms", () => {
+ const result = validateJsonLdWithSchemaOrg({
+ "@context": "https://schema.org",
+ "@type": ["Organization", "UnknownBusiness"],
+ awards: "Award",
+ recipeCategory: "Dinner",
+ madeUpProperty: true,
+ numberOfEmployees: "many",
+ isAccessibleForFree: "yes",
+ });
+ expect(result.success).toBe(true);
+ expect(result.diagnostics).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ code: "unknown-schema-org-type" }),
+ expect.objectContaining({ code: "deprecated-schema-org-property" }),
+ expect.objectContaining({ code: "unsupported-schema-org-property" }),
+ expect.objectContaining({ code: "unknown-schema-org-property" }),
+ expect.objectContaining({ code: "incompatible-schema-org-value" }),
+ ])
+ );
+});
+
+test("does not apply Schema.org vocabulary warnings to custom contexts", () => {
+ expect(
+ validateJsonLdWithSchemaOrg({
+ "@context": "https://example.com/context",
+ "@type": "CustomType",
+ customProperty: "value",
+ }).diagnostics
+ ).toEqual([]);
+});
diff --git a/packages/sdk/src/json-ld.ts b/packages/sdk/src/json-ld.ts
new file mode 100644
index 0000000000..8a80ea2298
--- /dev/null
+++ b/packages/sdk/src/json-ld.ts
@@ -0,0 +1,407 @@
+import { appendJsonPath, getJsonLdTypes, isJsonObject } from "./json-ld-utils";
+
+export type JsonLdPrimitive = string | number | boolean | null;
+export type JsonLdData =
+ | JsonLdPrimitive
+ | { [key: string]: JsonLdData }
+ | JsonLdData[];
+export type JsonLdValue = { [key: string]: JsonLdData } | JsonLdData[];
+
+export type JsonLdStructuralDiagnostic = {
+ severity: "error";
+ code:
+ | "invalid-json"
+ | "invalid-root"
+ | "invalid-context"
+ | "invalid-keyword-value"
+ | "invalid-value-object";
+ path: string;
+ message: string;
+};
+
+export type JsonLdValidationResult =
+ | {
+ success: true;
+ value: JsonLdValue;
+ diagnostics: JsonLdStructuralDiagnostic[];
+ }
+ | {
+ success: false;
+ value?: JsonLdValue;
+ diagnostics: JsonLdStructuralDiagnostic[];
+ };
+
+const pushKeywordTypeError = (
+ diagnostics: JsonLdStructuralDiagnostic[],
+ path: string,
+ message: string
+) => {
+ diagnostics.push({
+ severity: "error",
+ code: "invalid-keyword-value",
+ path,
+ message,
+ });
+};
+
+export const escapeJsonLdScriptText = (value: string) =>
+ value.replace(/</g, "\\u003c");
+
+const validateContextTermDefinition = (
+ definition: unknown,
+ path: string,
+ diagnostics: JsonLdStructuralDiagnostic[]
+) => {
+ if (
+ definition === null ||
+ typeof definition === "string" ||
+ isJsonObject(definition)
+ ) {
+ if (isJsonObject(definition) && definition["@context"] !== undefined) {
+ validateContext(
+ definition["@context"],
+ appendJsonPath(path, "@context"),
+ diagnostics
+ );
+ }
+ return;
+ }
+ diagnostics.push({
+ severity: "error",
+ code: "invalid-context",
+ path,
+ message: "JSON-LD context terms must map to a string, object, or null.",
+ });
+};
+
+const validateContext = (
+ context: unknown,
+ path: string,
+ diagnostics: JsonLdStructuralDiagnostic[]
+) => {
+ if (context === null || typeof context === "string") {
+ return;
+ }
+ if (Array.isArray(context)) {
+ context.forEach((item, index) =>
+ validateContext(item, appendJsonPath(path, index), diagnostics)
+ );
+ return;
+ }
+ if (isJsonObject(context) === false) {
+ diagnostics.push({
+ severity: "error",
+ code: "invalid-context",
+ path,
+ message: "@context must be a string, object, array of contexts, or null.",
+ });
+ return;
+ }
+ for (const keyword of ["@base", "@vocab", "@language"] as const) {
+ if (
+ context[keyword] !== undefined &&
+ context[keyword] !== null &&
+ typeof context[keyword] !== "string"
+ ) {
+ diagnostics.push({
+ severity: "error",
+ code: "invalid-context",
+ path: appendJsonPath(path, keyword),
+ message: `${keyword} must be a string or null.`,
+ });
+ }
+ }
+ if (
+ context["@direction"] !== undefined &&
+ context["@direction"] !== null &&
+ context["@direction"] !== "ltr" &&
+ context["@direction"] !== "rtl"
+ ) {
+ diagnostics.push({
+ severity: "error",
+ code: "invalid-context",
+ path: appendJsonPath(path, "@direction"),
+ message: '@direction must be "ltr", "rtl", or null.',
+ });
+ }
+ if (
+ context["@propagate"] !== undefined &&
+ typeof context["@propagate"] !== "boolean"
+ ) {
+ diagnostics.push({
+ severity: "error",
+ code: "invalid-context",
+ path: appendJsonPath(path, "@propagate"),
+ message: "@propagate must be a boolean.",
+ });
+ }
+ if (context["@version"] !== undefined && context["@version"] !== 1.1) {
+ diagnostics.push({
+ severity: "error",
+ code: "invalid-context",
+ path: appendJsonPath(path, "@version"),
+ message: "@version must be 1.1.",
+ });
+ }
+ for (const [term, definition] of Object.entries(context)) {
+ if (term.startsWith("@")) {
+ continue;
+ }
+ validateContextTermDefinition(
+ definition,
+ appendJsonPath(path, term),
+ diagnostics
+ );
+ }
+};
+
+const validateNestedValues = (
+ value: unknown,
+ path: string,
+ diagnostics: JsonLdStructuralDiagnostic[]
+) => {
+ if (isJsonObject(value)) {
+ validateNode(value, path, diagnostics);
+ return;
+ }
+ if (Array.isArray(value)) {
+ value.forEach((item, index) => {
+ if (isJsonObject(item) || Array.isArray(item)) {
+ validateNestedValues(item, appendJsonPath(path, index), diagnostics);
+ }
+ });
+ }
+};
+
+const validateNode = (
+ value: unknown,
+ path: string,
+ diagnostics: JsonLdStructuralDiagnostic[]
+) => {
+ if (Array.isArray(value)) {
+ value.forEach((item, index) =>
+ validateNode(item, appendJsonPath(path, index), diagnostics)
+ );
+ return;
+ }
+ if (isJsonObject(value) === false) {
+ diagnostics.push({
+ severity: "error",
+ code: "invalid-root",
+ path,
+ message: "JSON-LD nodes must be objects.",
+ });
+ return;
+ }
+
+ if (value["@context"] !== undefined) {
+ validateContext(
+ value["@context"],
+ appendJsonPath(path, "@context"),
+ diagnostics
+ );
+ }
+ const typeValue = value["@type"];
+ if (
+ typeValue !== undefined &&
+ (getJsonLdTypes(typeValue).length === 0 ||
+ (Array.isArray(typeValue) && typeValue.length === 0))
+ ) {
+ pushKeywordTypeError(
+ diagnostics,
+ appendJsonPath(path, "@type"),
+ "@type must be a non-empty string or array of strings."
+ );
+ }
+ if (value["@id"] !== undefined && typeof value["@id"] !== "string") {
+ pushKeywordTypeError(
+ diagnostics,
+ appendJsonPath(path, "@id"),
+ "@id must be a string."
+ );
+ }
+ if (
+ value["@graph"] !== undefined &&
+ isJsonObject(value["@graph"]) === false &&
+ Array.isArray(value["@graph"]) === false
+ ) {
+ pushKeywordTypeError(
+ diagnostics,
+ appendJsonPath(path, "@graph"),
+ "@graph must be an object or array of objects."
+ );
+ }
+ if (
+ value["@language"] !== undefined &&
+ value["@language"] !== null &&
+ typeof value["@language"] !== "string"
+ ) {
+ pushKeywordTypeError(
+ diagnostics,
+ appendJsonPath(path, "@language"),
+ "@language must be a string or null."
+ );
+ }
+ if (
+ value["@nest"] !== undefined &&
+ isJsonObject(value["@nest"]) === false &&
+ (Array.isArray(value["@nest"]) === false ||
+ value["@nest"].every(isJsonObject) === false)
+ ) {
+ pushKeywordTypeError(
+ diagnostics,
+ appendJsonPath(path, "@nest"),
+ "@nest must be an object or array of objects."
+ );
+ }
+ if (
+ value["@reverse"] !== undefined &&
+ isJsonObject(value["@reverse"]) === false
+ ) {
+ pushKeywordTypeError(
+ diagnostics,
+ appendJsonPath(path, "@reverse"),
+ "@reverse must be an object."
+ );
+ }
+ for (const keyword of ["@index"] as const) {
+ if (value[keyword] !== undefined && typeof value[keyword] !== "string") {
+ pushKeywordTypeError(
+ diagnostics,
+ appendJsonPath(path, keyword),
+ `${keyword} must be a string.`
+ );
+ }
+ }
+ if (
+ value["@direction"] !== undefined &&
+ value["@direction"] !== "ltr" &&
+ value["@direction"] !== "rtl" &&
+ value["@direction"] !== null
+ ) {
+ pushKeywordTypeError(
+ diagnostics,
+ appendJsonPath(path, "@direction"),
+ '@direction must be "ltr", "rtl", or null.'
+ );
+ }
+ if ("@value" in value) {
+ const invalidKeys = ["@id", "@graph", "@list", "@set", "@reverse"].filter(
+ (key) => key in value
+ );
+ const isJsonLiteral = value["@type"] === "@json";
+ const hasStructuredValue =
+ typeof value["@value"] === "object" && value["@value"] !== null;
+ if (
+ invalidKeys.length > 0 ||
+ (hasStructuredValue && isJsonLiteral === false) ||
+ ("@type" in value &&
+ value["@type"] !== "@json" &&
+ ("@language" in value || "@direction" in value))
+ ) {
+ diagnostics.push({
+ severity: "error",
+ code: "invalid-value-object",
+ path,
+ message:
+ "A JSON-LD value object has an incompatible keyword or @value shape.",
+ });
+ }
+ }
+
+ for (const [property, propertyValue] of Object.entries(value)) {
+ const propertyPath = appendJsonPath(path, property);
+ if (property === "@context") {
+ continue;
+ }
+ if (["@graph", "@included", "@nest", "@reverse"].includes(property)) {
+ validateNode(propertyValue, propertyPath, diagnostics);
+ continue;
+ }
+ if (property.startsWith("@")) {
+ if (["@list", "@set"].includes(property)) {
+ validateNestedValues(propertyValue, propertyPath, diagnostics);
+ }
+ continue;
+ }
+ validateNestedValues(propertyValue, propertyPath, diagnostics);
+ }
+};
+
+const isJsonLdData = (
+ value: unknown,
+ ancestors: Set<object>
+): value is JsonLdData => {
+ if (
+ value === null ||
+ typeof value === "string" ||
+ typeof value === "boolean" ||
+ (typeof value === "number" && Number.isFinite(value))
+ ) {
+ return true;
+ }
+ if (typeof value !== "object" || value === null || ancestors.has(value)) {
+ return false;
+ }
+ const prototype = Object.getPrototypeOf(value);
+ if (Array.isArray(value) === false && prototype !== Object.prototype) {
+ return false;
+ }
+ ancestors.add(value);
+ const isValid = Array.isArray(value)
+ ? value.every((item) => isJsonLdData(item, ancestors))
+ : Object.values(value).every((item) => isJsonLdData(item, ancestors));
+ ancestors.delete(value);
+ return isValid;
+};
+
+const isJsonLdValue = (value: unknown): value is JsonLdValue =>
+ (Array.isArray(value) || isJsonObject(value)) &&
+ isJsonLdData(value, new Set());
+
+export const parseJsonLd = (
+ input: unknown
+): { success: true; value: JsonLdValue } | { success: false } => {
+ try {
+ const value: unknown =
+ typeof input === "string" ? JSON.parse(input) : input;
+ if (isJsonLdValue(value)) {
+ return { success: true, value };
+ }
+ } catch {
+ // Invalid JSON is represented by the unsuccessful result.
+ }
+ return { success: false };
+};
+
+export const validateJsonLd = (input: unknown): JsonLdValidationResult => {
+ const parsed = parseJsonLd(input);
+ if (parsed.success === false) {
+ return {
+ success: false,
+ diagnostics: [
+ {
+ severity: "error",
+ code: typeof input === "string" ? "invalid-json" : "invalid-root",
+ path: "$",
+ message: "JSON-LD must be a valid JSON object or array.",
+ },
+ ],
+ };
+ }
+ const diagnostics: JsonLdStructuralDiagnostic[] = [];
+ validateNode(parsed.value, "$", diagnostics);
+ if (diagnostics.length > 0) {
+ return { success: false, value: parsed.value, diagnostics };
+ }
+ return { success: true, value: parsed.value, diagnostics };
+};
+
+export const hasTopLevelJsonLdContext = (value: JsonLdValue) => {
+ if (Array.isArray(value)) {
+ return value.some(
+ (item) => typeof item === "object" && item !== null && "@context" in item
+ );
+ }
+ return "@context" in value;
+};
diff --git a/packages/sdk/src/runtime.ts b/packages/sdk/src/runtime.ts
index b2f7d3067e..dd766a7bd1 100644
--- a/packages/sdk/src/runtime.ts
+++ b/packages/sdk/src/runtime.ts
@@ -1,6 +1,7 @@
export * from "./resource-loader";
export * from "./to-string";
export * from "./form-fields";
+export * from "./json-ld";
export const tagProperty = "data-ws-tag";
diff --git a/packages/sdk/src/schema-org-data.test.ts b/packages/sdk/src/schema-org-data.test.ts
new file mode 100644
index 0000000000..2e2a7cd76c
--- /dev/null
+++ b/packages/sdk/src/schema-org-data.test.ts
@@ -0,0 +1,35 @@
+import { expect, test } from "vitest";
+import {
+ schemaOrgDataSourceSha256,
+ schemaOrgDataVersion,
+ schemaOrgPropertyRows,
+ schemaOrgTypeRows,
+} from "./__generated__/schema-org-data";
+
+test("records reproducible Schema.org source provenance", () => {
+ expect(schemaOrgDataVersion).toBe("30.0");
+ expect(schemaOrgDataSourceSha256).toEqual({
+ types: "1ae97702e7bd9b91a90b78df5133b8897a0f025a6f94669491a55c0bf1867626",
+ properties:
+ "3a6319bd496d2d3dc276e3a8af9b0ff6415993e7d1f6b466072fcbdec1e0d257",
+ });
+});
+
+test("contains sorted Schema.org type inheritance data", () => {
+ const names = schemaOrgTypeRows.map(([name]) => name);
+ expect(names).toEqual([...names].sort());
+ expect(new Set(names).size).toBe(names.length);
+ expect(schemaOrgTypeRows).toContainEqual(["Organization", ["Thing"], ""]);
+});
+
+test("contains sorted Schema.org property domain and range data", () => {
+ const names = schemaOrgPropertyRows.map(([name]) => name);
+ expect(names).toEqual([...names].sort());
+ expect(new Set(names).size).toBe(names.length);
+ expect(schemaOrgPropertyRows).toContainEqual([
+ "name",
+ ["Thing"],
+ ["Text"],
+ "",
+ ]);
+});
diff --git a/packages/sdk/src/schema-org.ts b/packages/sdk/src/schema-org.ts
new file mode 100644
index 0000000000..295dc82174
--- /dev/null
+++ b/packages/sdk/src/schema-org.ts
@@ -0,0 +1,331 @@
+import {
+ schemaOrgPropertyRows,
+ schemaOrgTypeRows,
+} from "./__generated__/schema-org-data";
+import {
+ validateJsonLd,
+ type JsonLdStructuralDiagnostic,
+ type JsonLdValidationResult,
+ type JsonLdValue,
+} from "./json-ld";
+import { appendJsonPath, getJsonLdTypes, isJsonObject } from "./json-ld-utils";
+
+export type SchemaOrgDiagnostic = {
+ severity: "warning";
+ code:
+ | "unknown-schema-org-type"
+ | "deprecated-schema-org-type"
+ | "unknown-schema-org-property"
+ | "deprecated-schema-org-property"
+ | "unsupported-schema-org-property"
+ | "incompatible-schema-org-value";
+ path: string;
+ message: string;
+};
+
+export type JsonLdSchemaOrgValidationResult =
+ | {
+ success: true;
+ value: JsonLdValue;
+ diagnostics: Array<JsonLdStructuralDiagnostic | SchemaOrgDiagnostic>;
+ }
+ | JsonLdValidationResult;
+
+type VocabularyState = {
+ vocabulary: "schema-org" | "other" | undefined;
+ terms: Map<string, string | null>;
+};
+
+const typeByName = new Map(
+ schemaOrgTypeRows.map(([name, parentTypes, supersededBy]) => [
+ name,
+ { parentTypes, supersededBy },
+ ])
+);
+
+const propertyByName = new Map(
+ schemaOrgPropertyRows.map(([name, domains, ranges, supersededBy]) => [
+ name,
+ { domains, ranges, supersededBy },
+ ])
+);
+
+const schemaOrgContextPattern = /^https?:\/\/(?:www\.)?schema\.org\/?$/i;
+const schemaOrgTermPattern = /^https?:\/\/(?:www\.)?schema\.org\/([^/#]+)$/i;
+
+const getMappedIri = (definition: unknown) => {
+ if (typeof definition === "string") {
+ return definition;
+ }
+ if (isJsonObject(definition) && typeof definition["@id"] === "string") {
+ return definition["@id"];
+ }
+ return definition === null ? null : undefined;
+};
+
+const applyContext = (
+ inherited: VocabularyState,
+ context: unknown
+): VocabularyState => {
+ if (context === undefined) {
+ return inherited;
+ }
+ if (context === null) {
+ return { vocabulary: undefined, terms: new Map() };
+ }
+ if (Array.isArray(context)) {
+ return context.reduce(applyContext, inherited);
+ }
+ const next: VocabularyState = {
+ vocabulary: inherited.vocabulary,
+ terms: new Map(inherited.terms),
+ };
+ if (typeof context === "string") {
+ next.vocabulary = schemaOrgContextPattern.test(context)
+ ? "schema-org"
+ : "other";
+ return next;
+ }
+ if (isJsonObject(context) === false) {
+ return next;
+ }
+ if (context["@vocab"] === null) {
+ next.vocabulary = undefined;
+ } else if (typeof context["@vocab"] === "string") {
+ next.vocabulary = schemaOrgContextPattern.test(context["@vocab"])
+ ? "schema-org"
+ : "other";
+ }
+ for (const [term, definition] of Object.entries(context)) {
+ if (term.startsWith("@")) {
+ continue;
+ }
+ const iri = getMappedIri(definition);
+ if (iri !== undefined) {
+ next.terms.set(term, iri);
+ }
+ }
+ return next;
+};
+
+const expandTerm = (value: string, state: VocabularyState) => {
+ if (value.startsWith("@")) {
+ return;
+ }
+ const directSchemaOrgMatch = value.match(schemaOrgTermPattern);
+ if (directSchemaOrgMatch !== null) {
+ return directSchemaOrgMatch[1];
+ }
+ const mapped = state.terms.get(value);
+ if (mapped !== undefined) {
+ if (mapped === null) {
+ return;
+ }
+ return mapped.match(schemaOrgTermPattern)?.[1];
+ }
+ const colon = value.indexOf(":");
+ if (colon > 0) {
+ const prefix = state.terms.get(value.slice(0, colon));
+ if (typeof prefix === "string") {
+ return `${prefix}${value.slice(colon + 1)}`.match(
+ schemaOrgTermPattern
+ )?.[1];
+ }
+ return;
+ }
+ return state.vocabulary === "schema-org" ? value : undefined;
+};
+
+const isTypeOrSubtypeOf = (
+ type: string,
+ expected: string,
+ visited = new Set<string>()
+): boolean => {
+ if (type === expected) {
+ return true;
+ }
+ if (visited.has(type)) {
+ return false;
+ }
+ visited.add(type);
+ return (
+ typeByName
+ .get(type)
+ ?.parentTypes.some((parent) =>
+ isTypeOrSubtypeOf(parent, expected, visited)
+ ) ?? false
+ );
+};
+
+const primitiveRangeMatches = (range: string, value: unknown) => {
+ if (range === "Boolean") {
+ return typeof value === "boolean";
+ }
+ if (range === "Integer") {
+ return typeof value === "number" && Number.isInteger(value);
+ }
+ if (["Float", "Number"].includes(range)) {
+ return typeof value === "number";
+ }
+ if (
+ [
+ "CssSelectorType",
+ "Date",
+ "DateTime",
+ "PronounceableText",
+ "Text",
+ "Time",
+ "URL",
+ "XPathType",
+ ].includes(range)
+ ) {
+ return typeof value === "string";
+ }
+};
+
+const hasIncompatiblePrimitiveRange = (
+ ranges: readonly string[],
+ value: unknown
+) => {
+ const results = ranges.map((range) => primitiveRangeMatches(range, value));
+ return (
+ results.length > 0 &&
+ results.every((result) => result !== undefined) &&
+ results.every((result) => result === false)
+ );
+};
+
+const validateNode = (
+ value: unknown,
+ path: string,
+ inheritedState: VocabularyState,
+ diagnostics: SchemaOrgDiagnostic[]
+) => {
+ if (Array.isArray(value)) {
+ value.forEach((item, index) =>
+ validateNode(
+ item,
+ appendJsonPath(path, index),
+ inheritedState,
+ diagnostics
+ )
+ );
+ return;
+ }
+ if (isJsonObject(value) === false) {
+ return;
+ }
+ const state = applyContext(inheritedState, value["@context"]);
+ const types = getJsonLdTypes(value["@type"])
+ .map((type) => expandTerm(type, state))
+ .filter((type): type is string => type !== undefined);
+
+ for (const type of types) {
+ const definition = typeByName.get(type);
+ if (definition === undefined) {
+ diagnostics.push({
+ severity: "warning",
+ code: "unknown-schema-org-type",
+ path: appendJsonPath(path, "@type"),
+ message: `${JSON.stringify(type)} is not a known Schema.org type.`,
+ });
+ } else if (definition.supersededBy !== "") {
+ diagnostics.push({
+ severity: "warning",
+ code: "deprecated-schema-org-type",
+ path: appendJsonPath(path, "@type"),
+ message: `${type} is superseded by ${definition.supersededBy}.`,
+ });
+ }
+ }
+
+ for (const [property, propertyValue] of Object.entries(value)) {
+ const propertyPath = appendJsonPath(path, property);
+ if (property.startsWith("@")) {
+ if (
+ ["@graph", "@included", "@list", "@nest", "@set", "@reverse"].includes(
+ property
+ )
+ ) {
+ validateNode(propertyValue, propertyPath, state, diagnostics);
+ }
+ continue;
+ }
+ const schemaOrgProperty = expandTerm(property, state);
+ if (schemaOrgProperty !== undefined) {
+ const definition = propertyByName.get(schemaOrgProperty);
+ if (definition === undefined) {
+ diagnostics.push({
+ severity: "warning",
+ code: "unknown-schema-org-property",
+ path: propertyPath,
+ message: `${JSON.stringify(schemaOrgProperty)} is not a known Schema.org property.`,
+ });
+ } else {
+ if (definition.supersededBy !== "") {
+ diagnostics.push({
+ severity: "warning",
+ code: "deprecated-schema-org-property",
+ path: propertyPath,
+ message: `${schemaOrgProperty} is superseded by ${definition.supersededBy}.`,
+ });
+ }
+ if (
+ types.length > 0 &&
+ definition.domains.length > 0 &&
+ types.every((type) =>
+ definition.domains.every(
+ (domain) => isTypeOrSubtypeOf(type, domain) === false
+ )
+ )
+ ) {
+ diagnostics.push({
+ severity: "warning",
+ code: "unsupported-schema-org-property",
+ path: propertyPath,
+ message: `${schemaOrgProperty} is not declared for ${types.join(", ")}.`,
+ });
+ }
+ const values = Array.isArray(propertyValue)
+ ? propertyValue
+ : [propertyValue];
+ if (
+ values.some((item) =>
+ hasIncompatiblePrimitiveRange(definition.ranges, item)
+ )
+ ) {
+ diagnostics.push({
+ severity: "warning",
+ code: "incompatible-schema-org-value",
+ path: propertyPath,
+ message: `${schemaOrgProperty} expects ${definition.ranges.join(" or ")}.`,
+ });
+ }
+ }
+ }
+ if (isJsonObject(propertyValue) || Array.isArray(propertyValue)) {
+ validateNode(propertyValue, propertyPath, state, diagnostics);
+ }
+ }
+};
+
+export const validateJsonLdWithSchemaOrg = (
+ input: unknown
+): JsonLdSchemaOrgValidationResult => {
+ const result = validateJsonLd(input);
+ if (result.success === false) {
+ return result;
+ }
+ const diagnostics: SchemaOrgDiagnostic[] = [];
+ validateNode(
+ result.value,
+ "$",
+ { vocabulary: undefined, terms: new Map() },
+ diagnostics
+ );
+ return {
+ success: true,
+ value: result.value,
+ diagnostics: [...result.diagnostics, ...diagnostics],
+ };
+};
diff --git a/packages/sdk/src/schema/pages.test.ts b/packages/sdk/src/schema/pages.test.ts
index c0a8c2c7bf..0a6ed9ec97 100644
--- a/packages/sdk/src/schema/pages.test.ts
+++ b/packages/sdk/src/schema/pages.test.ts
@@ -5,6 +5,7 @@ import {
pageAuth,
pagePath,
pages,
+ projectMeta,
projectNewRedirectPath,
} from "./pages";
@@ -130,6 +131,17 @@ test("supports text document type", () => {
).toBe(true);
});
+test("supports project agent instructions", () => {
+ expect(
+ projectMeta.parse({
+ agentInstructions:
+ "Use the existing design tokens and keep copy concise.",
+ })
+ ).toEqual({
+ agentInstructions: "Use the existing design tokens and keep copy concise.",
+ });
+});
+
test("validates page id matches its record key", () => {
expect(
pages.safeParse({
diff --git a/packages/sdk/src/schema/pages.ts b/packages/sdk/src/schema/pages.ts
index 481fc24304..90f70b6669 100644
--- a/packages/sdk/src/schema/pages.ts
+++ b/packages/sdk/src/schema/pages.ts
@@ -216,6 +216,7 @@ export const projectMeta = z.object({
contactEmail: z.string().optional(),
faviconAssetId: z.string().optional(),
code: z.string().optional(),
+ agentInstructions: z.string().optional(),
auth: z.string().optional(),
});
export type ProjectMeta = z.infer<typeof projectMeta>;
diff --git a/packages/sdk/src/schema/prop-meta.ts b/packages/sdk/src/schema/prop-meta.ts
index d68dc1123b..e3b78574c1 100644
--- a/packages/sdk/src/schema/prop-meta.ts
+++ b/packages/sdk/src/schema/prop-meta.ts
@@ -62,7 +62,11 @@ const code = z.object({
...common,
control: z.literal("code"),
type: z.literal("string"),
- language: z.union([z.literal("html"), z.literal("markdown")]),
+ language: z.union([
+ z.literal("html"),
+ z.literal("json"),
+ z.literal("markdown"),
+ ]),
defaultValue: z.string().optional(),
});
@@ -73,6 +77,13 @@ const codeText = z.object({
defaultValue: z.string().optional(),
});
+const jsonCode = z.object({
+ ...common,
+ control: z.literal("json-code"),
+ type: z.literal("string"),
+ defaultValue: z.string().optional(),
+});
+
const color = z.object({
...common,
control: z.literal("color"),
@@ -206,6 +217,7 @@ export const propMeta = z.union([
resource,
code,
codeText,
+ jsonCode,
color,
boolean,
radio,
diff --git a/packages/trpc-interface/src/api-compatibility.ts b/packages/trpc-interface/src/api-compatibility.ts
index b51b26bcdc..b55bac77dc 100644
--- a/packages/trpc-interface/src/api-compatibility.ts
+++ b/packages/trpc-interface/src/api-compatibility.ts
@@ -22,7 +22,11 @@ const apiCompatibilityAction = z.discriminatedUnion("type", [
export const apiCompatibilityPayload = z.object({
type: z.literal(apiCompatibilityErrorType),
- reason: z.enum(["apiRouteNotFound", "apiProcedureNotFound"]),
+ reason: z.enum([
+ "apiRouteNotFound",
+ "apiProcedureNotFound",
+ "clientVersionUnsupported",
+ ]),
target: apiCompatibilityTarget,
message: z.string(),
action: apiCompatibilityAction,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 04efd12285..c6c12aefa7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -229,7 +229,7 @@ importers:
version: 66.6.8
'@vercel/remix':
specifier: 2.15.3
'@webstudio-is/asset-uploader':
specifier: workspace:*
version: link:../../packages/asset-uploader
@@ -446,7 +446,7 @@ importers:
devDependencies:
'@remix-run/dev':
specifier: ^2.16.5
'@types/debug':
specifier: ^4.1.12
version: 4.1.12
@@ -499,8 +499,8 @@ importers:
specifier: 7.0.2
version: 7.0.2
vite:
- specifier: npm:rolldown-vite@^7.3.1
+ specifier: 6.3.4
vitest:
specifier: ^3.1.2
@@ -1195,6 +1195,9 @@ importers:
env-paths:
specifier: ^3.0.0
version: 3.0.0
+ esbuild:
+ specifier: ^0.25.3
+ version: 0.25.3
fast-deep-equal:
specifier: ^3.1.3
version: 3.1.3
@@ -1982,6 +1985,9 @@ importers:
'@webstudio-is/css-engine':
specifier: workspace:*
version: link:../css-engine
+ '@webstudio-is/fonts':
+ specifier: workspace:*
+ version: link:../fonts
'@webstudio-is/html-data':
specifier: workspace:*
version: link:../html-data
@@ -2236,6 +2242,9 @@ importers:
specifier: ^4.4.3
version: 4.4.3
devDependencies:
+ '@types/papaparse':
+ specifier: ^5.5.2
+ version: 5.5.2
'@webstudio-is/css-data':
specifier: workspace:*
version: link:../css-data
@@ -2248,6 +2257,9 @@ importers:
html-tags:
specifier: ^4.0.0
version: 4.0.0
+ papaparse:
+ specifier: ^5.5.3
+ version: 5.5.3
vitest:
specifier: ^3.1.2
@@ -3320,15 +3332,9 @@ packages:
'@dotenvx/[email protected]':
resolution: {integrity: sha512-VYJy0uhFm9zTJ1TxBaW/pA8bjbOM/OttaNMwZ1RHG4JKyRG7DhSdiqD1ipQoAyoD22olUtxbP78W9xY3Wd11bg==}
- '@emnapi/[email protected]':
- resolution: {integrity: sha512-mukuNALVsoix/w1BJwFzwXBN/dHeejQtuVzcDsfOEsdpCumXb/E9j8w11h5S54tT1xhifGfbbSm/ICrObRb3KA==}
-
'@emnapi/[email protected]':
resolution: {integrity: sha512-kEBmG8KyqtxJZv+ygbEim+KCGtIq1fC22Ms3S4ziXmYKm8uyoLX0MHONVKwp+9opg390VaKRNt4a7A9NwmpNhw==}
- '@emnapi/[email protected]':
- resolution: {integrity: sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg==}
-
'@emotion/[email protected]':
resolution: {integrity: sha512-MyqliTZGuOm3+5ZRSaaBGP3USLw6+EGykkwZns2EPC5g8jJ4z9OrdZY9apkl3+UP9+sdz76YYkwCKP5gh8iY3g==}
@@ -4449,12 +4455,6 @@ packages:
nanostores: ^0.9.0 || ^0.10.0 || ^0.11.0
react: 18.3.0-canary-14898b6a9-20240318
- '@napi-rs/[email protected]':
- resolution: {integrity: sha512-sNXv5oLJ7ob93xkZ1XnxisYhGYXfaG9f65/ZgYuAu3qt7b3NadcOEhLvx28hv31PgX8SZJRYrAIPQilQmFpLVw==}
- peerDependencies:
- '@emnapi/core': ^1.7.1
- '@emnapi/runtime': ^1.7.1
-
'@netlify/[email protected]':
resolution: {integrity: sha512-JE32RJ6PamX6Yf2yyys7NLaKK4ppcDwuL6mk7NDZ7rt4EWUm+5bz/YjMcLz9uXyo1jDPlWjaUcqRC2MUZKt2DA==}
engines: {node: '>=18'}
@@ -4518,13 +4518,6 @@ packages:
'@oslojs/[email protected]':
resolution: {integrity: sha512-t70+e4EgnzTbU4MrUWXzqWN2A6RJrlSSvwwuBv6E0Ap6/nsIXrjsdRWeTcSvvXTcC6fi0YdWaqEWLipcEm2Cgw==}
- '@oxc-project/[email protected]':
- resolution: {integrity: sha512-t3qpfVZIqSiLQ5Kqt/MC4Ge/WCOGrrcagAdzTcDaggupjiGxUx4nJF2v6wUCXWSzWHn5Ns7XLv13fCJEwCOERQ==}
- engines: {node: ^20.19.0 || >=22.12.0}
-
- '@oxc-project/[email protected]':
- resolution: {integrity: sha512-nuFhqlUzJX+gVIPPfuE6xurd4lST3mdcWOhyK/rZO0B9XWMKm79SuszIQEnSMmmDhq1DC8WWVYGVd+6F93o1gQ==}
-
resolution: {integrity: sha512-Uz62sHduGGPftXtILGyxdSW4PX82rUg+rfdNqhsgxe881g4rIoXlIqmZQ6HVKcF4f+F8qMhdD03Bx5u7gmeTdg==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -5805,86 +5798,6 @@ packages:
'@remix-run/[email protected]':
resolution: {integrity: sha512-KRJtwrjRV5Bb+pM7zxcTJkhIqWWSy+MYsIxHK+0m5atcznsf15YwUBWHWulZerV2+vvHH1Lp1DD7pw6qKW8SgA==}
- '@rolldown/[email protected]':
- resolution: {integrity: sha512-Ok9V8o7o6YfSdTTYA/uHH30r3YtOxLD6G3wih/U9DO0ucBBFq8WPt/DslU53OgfteLRHITZny9N/qCUxMf9kjQ==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [android]
-
- '@rolldown/[email protected]':
- resolution: {integrity: sha512-yIsKqMz0CtRnVa6x3Pa+mzTihr4Ty+Z6HfPbZ7RVbk1Uxnco4+CUn7Qbm/5SBol1JD/7nvY8rphAgyAi7Lj6Vg==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [darwin]
-
- '@rolldown/[email protected]':
- resolution: {integrity: sha512-GTXe+mxsCGUnJOFMhfGWmefP7Q9TpYUseHvhAhr21nCTgdS8jPsvirb0tJwM3lN0/u/cg7bpFNa16fQrjKrCjQ==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [x64]
- os: [darwin]
-
- '@rolldown/[email protected]':
- resolution: {integrity: sha512-9Tmp7bBvKqyDkMcL4e089pH3RsjD3SUungjmqWtyhNOxoQMh0fSmINTyYV8KXtE+JkxYMPWvnEt+/mfpVCkk8w==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [x64]
- os: [freebsd]
-
- '@rolldown/[email protected]':
- resolution: {integrity: sha512-a1y5fiB0iovuzdbjUxa7+Zcvgv+mTmlGGC4XydVIsyl48eoxgaYkA3l9079hyTyhECsPq+mbr0gVQsFU11OJAQ==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm]
- os: [linux]
-
- '@rolldown/[email protected]':
- resolution: {integrity: sha512-bpIGX+ov9PhJYV+wHNXl9rzq4F0QvILiURn0y0oepbQx+7stmQsKA0DhPGwmhfvF856wq+gbM8L92SAa/CBcLg==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [linux]
-
- '@rolldown/[email protected]':
- resolution: {integrity: sha512-bGe5EBB8FVjHBR1mOLOPEFg1Lp3//7geqWkU5NIhxe+yH0W8FVrQ6WRYOap4SUTKdklD/dC4qPLREkMMQ855FA==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [linux]
-
- '@rolldown/[email protected]':
- resolution: {integrity: sha512-qL+63WKVQs1CMvFedlPt0U9PiEKJOAL/bsHMKUDS6Vp2Q+YAv/QLPu8rcvkfIMvQ0FPU2WL0aX4eWwF6e/GAnA==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [x64]
- os: [linux]
-
- '@rolldown/[email protected]':
- resolution: {integrity: sha512-VGl9JIGjoJh3H8Mb+7xnVqODajBmrdOOb9lxWXdcmxyI+zjB2sux69br0hZJDTyLJfvBoYm439zPACYbCjGRmw==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [x64]
- os: [linux]
-
- '@rolldown/[email protected]':
- resolution: {integrity: sha512-B4iIserJXuSnNzA5xBLFUIjTfhNy7d9sq4FUMQY3GhQWGVhS2RWWzzDnkSU6MUt7/aHUrep0CdQfXUJI9D3W7A==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [openharmony]
-
- '@rolldown/[email protected]':
- resolution: {integrity: sha512-BUjAEgpABEJXilGq/BPh7jeU3WAJ5o15c1ZEgHaDWSz3LB881LQZnbNJHmUiM4d1JQWMYYyR1Y490IBHi2FPJg==}
- engines: {node: '>=14.0.0'}
- cpu: [wasm32]
-
- '@rolldown/[email protected]':
- resolution: {integrity: sha512-s27uU7tpCWSjHBnxyVXHt3rMrQdJq5MHNv3BzsewCIroIw3DJFjMH1dzCPPMUFxnh1r52Nf9IJ/eWp6LDoyGcw==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [win32]
-
- '@rolldown/[email protected]':
- resolution: {integrity: sha512-cjWL/USPJ1g0en2htb4ssMjIycc36RvdQAx1WlXnS6DpULswiUTVXPDesTifSKYSyvx24E0YqQkEm0K/M2Z/AA==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [x64]
- os: [win32]
-
- '@rolldown/[email protected]':
- resolution: {integrity: sha512-vENRlFU4YbrwVqNDZ7fLvy+JR1CRkyr01jhSiDpE1u6py3OMzQfztQU2jxykW3ALNxO4kSlqIDeYyD0Y9RcQeQ==}
-
'@rollup/[email protected]':
resolution: {integrity: sha512-7QaYCf8bqF04dOy7w/eHmJeNExxTYwvKAmlSAH/EaWWUzbT0h5sbF6bktFoX/0F/0qwng5/dWFMyf3gzaM8DsQ==}
engines: {node: '>=14.0.0'}
@@ -6271,9 +6184,6 @@ packages:
resolution: {integrity: sha512-BPom8lVwR4fkk1EynPeQwuN0e5bH2gBphwt69uF5rS4wRD2N7IyHDPqdjcAY0I7gNEWfUitPyDodywbD4r7dEQ==}
engines: {node: '>=20.19.0'}
- '@tybys/[email protected]':
- resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==}
-
resolution: {integrity: sha512-veQTnWP+1D/xbxVrPC3zHnCZRjSrKfhbMUlEA43iMZLu7EsnTtkJklIuwrCPbOi8YkvDQAiW05VQQFvvz9oieQ==}
@@ -10106,52 +10016,6 @@ packages:
deprecated: Rimraf versions prior to v4 are no longer supported
hasBin: true
- resolution: {integrity: sha512-LYzdNAjRHhF2yA4JUQm/QyARyi216N2rpJ0lJZb8E9FU2y5v6Vk+xq/U4XBOxMefpWixT5H3TslmAHm1rqIq2w==}
- engines: {node: ^20.19.0 || >=22.12.0}
- deprecated: Use this package to migrate from Vite 7 to Vite 8. For the most recent updates, migrate to Vite 8 once you're ready.
- hasBin: true
- peerDependencies:
- '@types/node': ^20.19.0 || >=22.12.0
- esbuild: ^0.27.0
- jiti: '>=1.21.0'
- less: ^4.0.0
- sass: ^1.70.0
- sass-embedded: ^1.70.0
- stylus: '>=0.54.8'
- sugarss: ^5.0.0
- terser: ^5.16.0
- tsx: ^4.8.1
- yaml: ^2.4.2
- peerDependenciesMeta:
- '@types/node':
- optional: true
- esbuild:
- optional: true
- jiti:
- optional: true
- less:
- optional: true
- sass:
- optional: true
- sass-embedded:
- optional: true
- stylus:
- optional: true
- sugarss:
- optional: true
- terser:
- optional: true
- tsx:
- optional: true
- yaml:
- optional: true
-
- resolution: {integrity: sha512-Qd9c2p0XKZdgT5AYd+KgAMggJ8ZmCs3JnS9PTMWkyUfteKlfmKtxJbWTHkVakxwXs1Ub7jrRYVeFeF7N0sQxyw==}
- engines: {node: ^20.19.0 || >=22.12.0}
- hasBin: true
-
resolution: {integrity: sha512-ptg9PQwzs3orn4jkgXJ74bfs5vYz1NCZlSQMBUA0wKcGp5i5pA1AO3fOUEte8enhGUC+iapTCzEWw2jEFFUO/w==}
deprecated: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-inject.
@@ -12296,22 +12160,11 @@ snapshots:
'@dotenvx/[email protected]': {}
- '@emnapi/[email protected]':
- dependencies:
- '@emnapi/wasi-threads': 1.2.0
- tslib: 2.8.1
- optional: true
-
'@emnapi/[email protected]':
dependencies:
tslib: 2.8.1
optional: true
- '@emnapi/[email protected]':
- dependencies:
- tslib: 2.8.1
- optional: true
-
'@emotion/[email protected]': {}
@@ -13217,13 +13070,6 @@ snapshots:
nanostores: 0.11.3
react: 18.3.0-canary-14898b6a9-20240318
- dependencies:
- '@emnapi/core': 1.9.1
- '@emnapi/runtime': 1.3.1
- '@tybys/wasm-util': 0.10.1
- optional: true
-
dependencies:
@@ -13319,10 +13165,6 @@ snapshots:
'@oslojs/[email protected]': {}
- '@oxc-project/[email protected]': {}
-
- '@oxc-project/[email protected]': {}
-
optional: true
@@ -14605,89 +14447,6 @@ snapshots:
- utf-8-validate
- yaml
- dependencies:
- '@babel/core': 7.26.10
- '@babel/generator': 7.27.0
- '@babel/parser': 7.27.0
- '@babel/plugin-syntax-decorators': 7.24.1(@babel/[email protected])
- '@babel/plugin-syntax-jsx': 7.24.1(@babel/[email protected])
- '@babel/preset-typescript': 7.24.1(@babel/[email protected])
- '@babel/traverse': 7.27.0
- '@babel/types': 7.27.0
- '@mdx-js/mdx': 2.3.0
- '@npmcli/package-json': 4.0.1
- '@remix-run/node': 2.16.5([email protected])
- '@remix-run/router': 1.23.0
- '@remix-run/server-runtime': 2.16.5([email protected])
- '@types/mdx': 2.0.13
- '@vanilla-extract/integration': 6.5.0(@types/[email protected])([email protected])([email protected])([email protected])
- arg: 5.0.2
- cacache: 17.1.4
- chalk: 4.1.2
- chokidar: 3.6.0
- cross-spawn: 7.0.6
- dotenv: 16.3.1
- es-module-lexer: 1.6.0
- esbuild: 0.17.6
- esbuild-plugins-node-modules-polyfill: 1.6.3([email protected])
- execa: 5.1.1
- exit-hook: 2.2.1
- express: 4.21.1
- fs-extra: 10.1.0
- get-port: 5.1.1
- gunzip-maybe: 1.4.2
- jsesc: 3.0.2
- json5: 2.2.3
- lodash: 4.17.21
- lodash.debounce: 4.0.8
- minimatch: 9.0.4
- ora: 5.4.1
- pathe: 1.1.2
- picocolors: 1.1.1
- picomatch: 2.3.1
- pidtree: 0.6.0
- postcss: 8.5.3
- postcss-discard-duplicates: 5.1.0([email protected])
- postcss-load-config: 4.0.1([email protected])
- postcss-modules: 6.0.0([email protected])
- prettier: 2.8.7
- pretty-ms: 7.0.1
- react-refresh: 0.14.2
- remark-frontmatter: 4.0.1
- remark-mdx-frontmatter: 1.1.1
- semver: 7.7.1
- set-cookie-parser: 2.6.0
- tar-fs: 2.1.1
- tsconfig-paths: 4.2.0
- valibot: 0.41.0([email protected])
- ws: 7.5.10
- optionalDependencies:
- '@remix-run/serve': 2.16.5([email protected])
- typescript: 7.0.2
- wrangler: 3.63.2(@cloudflare/[email protected])
- transitivePeerDependencies:
- - '@types/node'
- - babel-plugin-macros
- - bluebird
- - bufferutil
- - jiti
- - less
- - lightningcss
- - sass
- - sass-embedded
- - stylus
- - sugarss
- - supports-color
- - terser
- - ts-node
- - tsx
- - utf-8-validate
- - yaml
-
dependencies:
'@babel/core': 7.26.10
@@ -14917,52 +14676,6 @@ snapshots:
dependencies:
web-streams-polyfill: 3.2.1
- '@rolldown/[email protected]':
- optional: true
-
- '@rolldown/[email protected]':
- optional: true
-
- '@rolldown/[email protected]':
- optional: true
-
- '@rolldown/[email protected]':
- optional: true
-
- '@rolldown/[email protected]':
- optional: true
-
- '@rolldown/[email protected]':
- optional: true
-
- '@rolldown/[email protected]':
- optional: true
-
- '@rolldown/[email protected]':
- optional: true
-
- '@rolldown/[email protected]':
- optional: true
-
- '@rolldown/[email protected]':
- optional: true
-
- dependencies:
- '@napi-rs/wasm-runtime': 1.1.2(@emnapi/[email protected])(@emnapi/[email protected])
- transitivePeerDependencies:
- - '@emnapi/core'
- - '@emnapi/runtime'
- optional: true
-
- '@rolldown/[email protected]':
- optional: true
-
- '@rolldown/[email protected]':
- optional: true
-
- '@rolldown/[email protected]': {}
-
dependencies:
'@rollup/pluginutils': 5.1.4([email protected])
@@ -15375,11 +15088,6 @@ snapshots:
'@tus/[email protected]': {}
- '@tybys/[email protected]':
- dependencies:
- tslib: 2.8.1
- optional: true
-
dependencies:
'@types/estree': 1.0.7
@@ -15693,9 +15401,9 @@ snapshots:
react-dom: 18.3.0-canary-14898b6a9-20240318([email protected])
ts-morph: 12.0.0
dependencies:
'@remix-run/node': 2.16.5([email protected])
'@remix-run/server-runtime': 2.16.5([email protected])
'@vercel/static-config': 3.0.0
@@ -15741,26 +15449,6 @@ snapshots:
- vite
optional: true
- dependencies:
- '@testing-library/dom': 10.4.0
- '@testing-library/user-event': 14.6.1(@testing-library/[email protected])
- '@vitest/utils': 3.1.2
- magic-string: 0.30.21
- sirv: 3.0.1
- tinyrainbow: 2.0.0
- ws: 8.21.0
- optionalDependencies:
- playwright: 1.50.1
- transitivePeerDependencies:
- - bufferutil
- - msw
- - utf-8-validate
- - vite
- optional: true
-
dependencies:
'@testing-library/dom': 10.4.0
@@ -15796,7 +15484,7 @@ snapshots:
tinyrainbow: 2.0.0
optionalDependencies:
transitivePeerDependencies:
- supports-color
@@ -15816,16 +15504,6 @@ snapshots:
msw: 2.13.2(@types/[email protected])(@typescript/[email protected])
- dependencies:
- '@vitest/spy': 3.1.2
- estree-walker: 3.0.3
- magic-string: 0.30.17
- optionalDependencies:
- msw: 2.13.2(@types/[email protected])([email protected])
- optional: true
-
dependencies:
'@vitest/spy': 3.1.2
@@ -17998,6 +17676,7 @@ snapshots:
lightningcss-linux-x64-musl: 1.31.1
lightningcss-win32-arm64-msvc: 1.31.1
lightningcss-win32-x64-msvc: 1.31.1
+ optional: true
@@ -19863,47 +19542,6 @@ snapshots:
dependencies:
glob: 7.2.3
- dependencies:
- '@oxc-project/runtime': 0.101.0
- fdir: 6.5.0([email protected])
- lightningcss: 1.31.1
- picomatch: 4.0.5
- postcss: 8.5.16
- rolldown: 1.0.0-beta.53(@emnapi/[email protected])(@emnapi/[email protected])
- tinyglobby: 0.2.17
- optionalDependencies:
- '@types/node': 22.13.10
- esbuild: 0.17.6
- fsevents: 2.3.3
- jiti: 2.4.2
- tsx: 4.19.3
- transitivePeerDependencies:
- - '@emnapi/core'
- - '@emnapi/runtime'
-
- dependencies:
- '@oxc-project/types': 0.101.0
- '@rolldown/pluginutils': 1.0.0-beta.53
- optionalDependencies:
- '@rolldown/binding-android-arm64': 1.0.0-beta.53
- '@rolldown/binding-darwin-arm64': 1.0.0-beta.53
- '@rolldown/binding-darwin-x64': 1.0.0-beta.53
- '@rolldown/binding-freebsd-x64': 1.0.0-beta.53
- '@rolldown/binding-linux-arm-gnueabihf': 1.0.0-beta.53
- '@rolldown/binding-linux-arm64-gnu': 1.0.0-beta.53
- '@rolldown/binding-linux-arm64-musl': 1.0.0-beta.53
- '@rolldown/binding-linux-x64-gnu': 1.0.0-beta.53
- '@rolldown/binding-linux-x64-musl': 1.0.0-beta.53
- '@rolldown/binding-openharmony-arm64': 1.0.0-beta.53
- '@rolldown/binding-wasm32-wasi': 1.0.0-beta.53(@emnapi/[email protected])(@emnapi/[email protected])
- '@rolldown/binding-win32-arm64-msvc': 1.0.0-beta.53
- '@rolldown/binding-win32-x64-msvc': 1.0.0-beta.53
- transitivePeerDependencies:
- - '@emnapi/core'
- - '@emnapi/runtime'
-
dependencies:
estree-walker: 0.6.1
@@ -21003,7 +20641,7 @@ snapshots:
optionalDependencies:
'@types/debug': 4.1.12
'@types/node': 22.13.10
jsdom: 20.0.3
transitivePeerDependencies:
- jiti