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.

fix: allow dynamic JSON-LD values (#5873)

Oleg Isonen11114fe85de3
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
index 3bc08b5ecf..95bd54808f 100644
--- 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
@@ -3,6 +3,7 @@ import {
formatJsonCode,
getFixedJsonCodeValue,
parseJsonCode,
+ processJsonCodeValue,
serializeJsonCode,
validateJsonCode,
validateJsonCodeValue,
@@ -57,10 +58,41 @@ test.each(["", "invalid", '"text"', "1", "null"])(
}
);
-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("warns when JSON-LD binding values have no top-level context", () => {
+ expect(validateJsonCodeValue({ a: 1 }, "Code")).toBe(
+ "Code: $ JSON-LD has no top-level @context."
+ );
+ expect(validateJsonCodeValue([{ a: 1 }], "Code")).toBe(
+ "Code: $ JSON-LD has no top-level @context."
+ );
+ expect(validateJsonCodeValue('{"a":1}', "Code")).toBe(
+ "Code: $ JSON-LD has no top-level @context."
+ );
+ expect(
+ validateJsonCodeValue(
+ { "@context": "https://schema.org", "@type": "Organization" },
+ "Code"
+ )
+ ).toBeUndefined();
+});
+
+test("surfaces Schema.org warnings for JSON-LD binding values", () => {
+ expect(
+ validateJsonCodeValue(
+ { "@context": "https://schema.org", "@type": "MadeUpType" },
+ "Code"
+ )
+ ).toContain('"MadeUpType" is not a known Schema.org type.');
+});
+
+test("warns about missing context in fixed JSON-LD code", () => {
+ expect(processJsonCodeValue('{"a":1}')).toMatchObject({
+ success: true,
+ issue: {
+ severity: "warning",
+ message: "$ JSON-LD has no top-level @context.",
+ },
+ });
});
test("rejects non-JSON binding values", () => {
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
index 382bc2c668..582b8b5b92 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/json-code.ts
+++ b/apps/builder/app/builder/features/settings-panel/controls/json-code.ts
@@ -1,5 +1,8 @@
import { createElement } from "react";
-import { parseJsonLd } from "@webstudio-is/sdk/runtime";
+import {
+ hasTopLevelJsonLdContext,
+ 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";
@@ -27,56 +30,67 @@ export const serializeJsonCode = (value: object) => JSON.stringify(value);
export const validateJsonCode = (value: unknown) =>
validateJsonLdWithSchemaOrg(value);
+const getJsonCodeError = (
+ result: Extract<ReturnType<typeof validateJsonCode>, { success: false }>
+) => {
+ const [error] = result.diagnostics;
+ return `${error.path} ${error.message}`;
+};
+
+const getJsonCodeWarnings = (
+ result: Extract<ReturnType<typeof validateJsonCode>, { success: true }>
+) => {
+ const warnings = result.diagnostics
+ .filter(({ severity }) => severity === "warning")
+ .map(({ path, message }) => `${path} ${message}`);
+ if (hasTopLevelJsonLdContext(result.value) === false) {
+ warnings.unshift("$ JSON-LD has no top-level @context.");
+ }
+ return warnings;
+};
+
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}`,
+ message: `${label}: ${getJsonCodeError(result)}`,
};
};
export const validateJsonCodeValue = (value: unknown, label: string) => {
- const result = getFixedJsonCodeValue(value, label);
- return result.success ? undefined : result.message;
+ const result = validateJsonCode(value);
+ if (result.success === false) {
+ return `${label}: ${getJsonCodeError(result)}`;
+ }
+ const warnings = getJsonCodeWarnings(result).map(
+ (message) => `${label}: ${message}`
+ );
+ return warnings.length === 0 ? undefined : warnings.join("\n");
};
-const processJsonCodeValue = (
+export 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) {
+ if (result.success === false) {
return {
success: false,
issue: {
- message:
- structuralError === undefined
- ? "Enter a JSON object or array."
- : `${structuralError.path} ${structuralError.message}`,
+ message: getJsonCodeError(result),
value,
},
};
}
- const warnings = result.diagnostics.filter(
- ({ severity }) => severity === "warning"
- );
+ const warnings = getJsonCodeWarnings(result);
const issue: CodeIssue | undefined =
warnings.length === 0
? undefined
: {
severity: "warning",
- message: warnings
- .map(({ path, message }) => `${path} ${message}`)
- .join("\n"),
+ message: warnings.join("\n"),
value,
};
return {
diff --git a/apps/builder/app/shared/sync-client.test.ts b/apps/builder/app/shared/sync-client.test.ts
index ca1bbf4877..5f9c23e6a7 100644
--- a/apps/builder/app/shared/sync-client.test.ts
+++ b/apps/builder/app/shared/sync-client.test.ts
@@ -156,6 +156,30 @@ test("exchange transactions between leader and follower", async () => {
);
});
+test("recreates transaction values in the receiving realm", () => {
+ const store = createFollowerStore();
+ const object = new ImmerhinSyncObject("my-data", store);
+ const foreignValue = Object.assign(Object.create({}), {
+ "@context": "https://schema.org",
+ });
+
+ object.applyTransaction({
+ id: "transaction-id",
+ object: "my-data",
+ payload: [
+ {
+ namespace: "users",
+ patches: [{ op: "add", path: ["jsonLd"], value: foreignValue }],
+ revisePatches: [{ op: "remove", path: ["jsonLd"] }],
+ },
+ ],
+ });
+
+ const receivedValue = store.containers.get("users")?.get().get("jsonLd");
+ expect(receivedValue).toEqual({ "@context": "https://schema.org" });
+ expect(Object.getPrototypeOf(receivedValue)).toBe(Object.prototype);
+});
+
test("exchange transactions between followers", async () => {
const emitter = new NanoEventsSyncEmitter();
const follower1Store = createFollowerStore();
diff --git a/apps/builder/app/shared/sync-client.ts b/apps/builder/app/shared/sync-client.ts
index 227229128c..a75ac46c92 100644
--- a/apps/builder/app/shared/sync-client.ts
+++ b/apps/builder/app/shared/sync-client.ts
@@ -85,9 +85,12 @@ export class ImmerhinSyncObject implements SyncObject {
}
}
applyTransaction(transaction: Transaction<Change[]>) {
+ // Immer cannot handle values whose prototypes come from another realm.
+ // Recreate received patches with the current realm's classes before applying them.
+ const receivedPayload = structuredClone(transaction.payload);
const payload = this.transformOnReceive
- ? this.transformOnReceive(transaction.payload)
- : transaction.payload;
+ ? this.transformOnReceive(receivedPayload)
+ : receivedPayload;
this.store.addTransaction(transaction.id, payload, "remote");
}
revertTransaction(transaction: RevertedTransaction) {
diff --git a/packages/project-build/src/runtime/props.test.ts b/packages/project-build/src/runtime/props.test.ts
index f4de0f753a..af06e3dad9 100644
--- a/packages/project-build/src/runtime/props.test.ts
+++ b/packages/project-build/src/runtime/props.test.ts
@@ -593,6 +593,23 @@ describe("updateProps", () => {
)
).toThrow('JSON-LD code must use prop type "string".');
+ expect(() =>
+ updateProps(
+ state,
+ {
+ updates: [
+ {
+ instanceId: jsonLd.id,
+ name: "code",
+ type: "expression",
+ value: "jsonLdData",
+ },
+ ],
+ },
+ { createId: () => "code-prop-id" }
+ )
+ ).not.toThrow();
+
expect(() =>
updateProps(
state,
diff --git a/packages/project-build/src/runtime/props.ts b/packages/project-build/src/runtime/props.ts
index 8c4edc5c0f..64e17c1bc9 100644
--- a/packages/project-build/src/runtime/props.ts
+++ b/packages/project-build/src/runtime/props.ts
@@ -13,6 +13,7 @@ import { getExpressionErrors } from "./expression-validation";
import { runtimeGeneratedIdInput } from "./generated-id-input";
import { validateHtmlEmbedCode } from "./html";
import { createRuntimeMutation } from "./mutation";
+import { isDynamicPropType } from "./accessibility-analysis";
export const showAttributeMeta: PropMeta = {
label: "Show",
@@ -767,6 +768,9 @@ const getJsonLdCodeErrors = (instance: Instance, update: PropValueInput) => {
if (instance.component !== "JsonLd" || update.name !== "code") {
return [];
}
+ if (isDynamicPropType(update.type)) {
+ return [];
+ }
if (update.type !== "string") {
return ['JSON-LD code must use prop type "string".'];
}
diff --git a/packages/sdk-components-react/src/json-ld.test.tsx b/packages/sdk-components-react/src/json-ld.test.tsx
index 117d09f5c0..3638e79484 100644
--- a/packages/sdk-components-react/src/json-ld.test.tsx
+++ b/packages/sdk-components-react/src/json-ld.test.tsx
@@ -54,7 +54,7 @@ test("omits structurally invalid JSON-LD from published output", () => {
).toBe("");
});
-test("renders a real script element on canvas", () => {
+test("renders visible JSON-LD code on canvas", () => {
const markup = renderToStaticMarkup(
<ReactSdkContext.Provider
value={{
@@ -66,14 +66,20 @@ test("renders a real script element on canvas", () => {
onError: console.error,
}}
>
- <JsonLd code='{"a":1}' />
+ <JsonLd code={{ "@context": "https://schema.org", name: "Acme" }} />
</ReactSdkContext.Provider>
);
- expect(markup).toBe('<script type="application/ld+json">{"a":1}</script>');
+ expect(markup).toContain("&lt;script");
+ expect(markup).toContain("application/ld+json");
+ expect(markup).toContain(
+ "{&quot;@context&quot;:&quot;https://schema.org&quot;,&quot;name&quot;:&quot;Acme&quot;}"
+ );
+ expect(markup).toContain("&lt;/script&gt;");
+ expect(markup).not.toContain('<script type="application/ld+json">');
});
-test("keeps invalid canvas drafts inside the JSON-LD script element", () => {
+test("renders an invalid dynamic JSON-LD placeholder on canvas", () => {
const markup = renderToStaticMarkup(
<ReactSdkContext.Provider
value={{
@@ -85,13 +91,12 @@ test("keeps invalid canvas drafts inside the JSON-LD script element", () => {
onError: console.error,
}}
>
- <JsonLd code={'</script><script data-unsafe="true">unsafe()</script>'} />
+ <JsonLd code={undefined} />
</ReactSdkContext.Provider>
);
- expect(markup).toContain("\\u003c/script>");
- expect(markup).not.toContain("<script data-unsafe");
- expect(markup.match(/<script/g)).toHaveLength(1);
+ expect(markup).toContain("JSON-LD value is unavailable or invalid.");
+ expect(markup).not.toContain('<script type="application/ld+json">');
});
test("keeps Schema.org vocabulary data out of the published component bundle", async () => {
diff --git a/packages/sdk-components-react/src/json-ld.tsx b/packages/sdk-components-react/src/json-ld.tsx
index 7788171a83..8aaafdf2b0 100644
--- a/packages/sdk-components-react/src/json-ld.tsx
+++ b/packages/sdk-components-react/src/json-ld.tsx
@@ -3,7 +3,8 @@ import {
escapeJsonLdScriptText,
validateJsonLd,
} from "@webstudio-is/sdk/runtime";
-import { forwardRef, type ElementRef, useContext } from "react";
+import { forwardRef, type ElementRef, type Ref, useContext } from "react";
+import { XmlNode } from "./xml-node";
export const defaultTag = "script";
@@ -19,6 +20,19 @@ export const JsonLd = forwardRef<ElementRef<"script">, { code?: unknown }>(
({ code = "" }, ref) => {
const { renderer } = useContext(ReactSdkContext);
const serialized = serializeJsonLd(code);
+
+ if (renderer === "canvas") {
+ return (
+ <XmlNode
+ tag={defaultTag}
+ {...{ type: "application/ld+json" }}
+ ref={ref as Ref<HTMLDivElement>}
+ >
+ {serialized ?? "JSON-LD value is unavailable or invalid."}
+ </XmlNode>
+ );
+ }
+
const content =
renderer === undefined
? serialized