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: validate published MDX before publish (#6468)

Oleg Isonena6a904939935
diff --git a/apps/builder/app/builder/features/publish/content-database-publish-warning-view.tsx b/apps/builder/app/builder/features/publish/content-database-publish-warning-view.tsx
index 7462210e44..6d43a0ad1d 100644
--- a/apps/builder/app/builder/features/publish/content-database-publish-warning-view.tsx
+++ b/apps/builder/app/builder/features/publish/content-database-publish-warning-view.tsx
@@ -10,10 +10,10 @@ export const ContentDatabasePublishWarning = ({
stats.includedDocumentCount + stats.omittedDocumentCount;
const omittedFileLabel = stats.omittedDocumentCount === 1 ? "file" : "files";
const dynamicResourceNames = diagnostics.affectedResources.flatMap(
- ({ name, kind }) => (kind === "dynamic" ? [name] : [])
+ ({ name, id, kind }) => (kind === "dynamic" ? [`${name} (ID: ${id})`] : [])
);
const staticResourceNames = diagnostics.affectedResources.flatMap(
- ({ name, kind }) => (kind === "static" ? [name] : [])
+ ({ name, id, kind }) => (kind === "static" ? [`${name} (ID: ${id})`] : [])
);
return (
<>
diff --git a/apps/builder/app/builder/features/publish/content-database-publish-warning.test.tsx b/apps/builder/app/builder/features/publish/content-database-publish-warning.test.tsx
index c655c9af24..be61d0d034 100644
--- a/apps/builder/app/builder/features/publish/content-database-publish-warning.test.tsx
+++ b/apps/builder/app/builder/features/publish/content-database-publish-warning.test.tsx
@@ -1,69 +1,116 @@
import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, test, vi } from "vitest";
-import {
- getContentDatabasePublishWarning,
- showContentDatabasePublishWarning,
-} from "./content-database-publish-warning";
+import { describe, expect, test } from "vitest";
+import { getContentDatabasePublishFindings } from "./content-database-publish-warning";
-const mdxDiagnostics = (count: number) => ({
- stats: undefined,
- affectedResources: [],
- mdxOmissions: Array.from({ length: count }, (_, index) => ({
- assetId: `asset-${index}`,
- blockInstanceId: `block-${index}`,
- filename: `post-${index}.mdx`,
- templateName: `Post ${index}`,
- })),
-});
+const createDiagnostics = (overrides: Record<string, unknown> = {}) =>
+ ({
+ stats: undefined,
+ affectedResources: [],
+ mdxOmissions: [],
+ mdxErrors: [],
+ ...overrides,
+ }) as never;
-describe("content database publish warning", () => {
- test("returns no warning when diagnostics are clean", () => {
- expect(getContentDatabasePublishWarning(mdxDiagnostics(0))).toBeUndefined();
+describe("content database publish findings", () => {
+ test("returns no findings when diagnostics are clean", () => {
+ expect(getContentDatabasePublishFindings(createDiagnostics())).toEqual([]);
});
- test("lists ten omitted templates and reports the remaining count", () => {
- const warning = getContentDatabasePublishWarning(mdxDiagnostics(11));
- const markup = renderToStaticMarkup(warning);
+ test("reports every MDX error with source location, context, and a fix", () => {
+ const findings = getContentDatabasePublishFindings(
+ createDiagnostics({
+ mdxErrors: [
+ {
+ filename: "article.mdx",
+ diagnostic: {
+ code: "invalid-mdx",
+ severity: "error",
+ blockInstanceId: "block-1",
+ assetId: "asset-1",
+ contentRef: "article-revision.mdx",
+ renderScope: "route:/blog/article:block:block-1",
+ message: "Placing <a> inside <a> violates HTML spec.",
+ sourceRange: {
+ start: { line: 4, column: 3 },
+ end: { line: 4, column: 12 },
+ },
+ },
+ },
+ {
+ filename: "missing.mdx",
+ diagnostic: {
+ code: "invalid-mdx",
+ severity: "error",
+ blockInstanceId: "block-2",
+ assetId: "missing-asset",
+ message:
+ 'Published Content Block "block-2" requires unavailable MDX Asset "missing-asset"',
+ },
+ },
+ ],
+ })
+ );
- expect(markup).toContain("post-0.mdx: Post 0");
- expect(markup).toContain("post-9.mdx: Post 9");
- expect(markup).not.toContain("post-10.mdx");
- expect(markup).toContain("And 1 more template references.");
+ expect(findings).toHaveLength(2);
+ expect(findings[0]).toMatchObject({
+ severity: "error",
+ title: "article.mdx:4:3",
+ relatedInstanceId: "block-1",
+ });
+ expect(findings[0].reportText).toContain(
+ "Content reference: article-revision.mdx"
+ );
+ expect(findings[0].reportText).toContain(
+ "Edit the MDX element nesting to satisfy the HTML content model"
+ );
+ expect(findings[1].reportText).toContain(
+ "Choose an available MDX asset in this Content Block's source settings"
+ );
});
- test("does not wait for advisory diagnostics", () => {
- const diagnostics = new Promise<never>(() => {});
-
- expect(
- showContentDatabasePublishWarning({
- diagnostics,
- setWarning: vi.fn(),
+ test("includes every missing template warning and its identifying IDs", () => {
+ const findings = getContentDatabasePublishFindings(
+ createDiagnostics({
+ mdxOmissions: Array.from({ length: 11 }, (_, index) => ({
+ assetId: `asset-${index}`,
+ blockInstanceId: `block-${index}`,
+ filename: `article-${index}.mdx`,
+ templateName: `Template ${index}`,
+ })),
})
- ).toBeUndefined();
- });
-
- test("shows a warning when diagnostics finish", async () => {
- const setWarning = vi.fn();
- showContentDatabasePublishWarning({
- diagnostics: Promise.resolve(mdxDiagnostics(1)),
- setWarning,
- });
+ );
- await vi.waitFor(() => expect(setWarning).toHaveBeenCalledOnce());
- expect(renderToStaticMarkup(setWarning.mock.calls[0][0])).toContain(
- "post-0.mdx: Post 0"
+ expect(findings).toHaveLength(11);
+ expect(findings[10].reportText).toContain("article-10.mdx: Template 10");
+ expect(findings[10].reportText).toContain(
+ "Content Block instance ID: block-10"
);
+ expect(findings[10].reportText).toContain("Asset ID: asset-10");
});
- test("swallows an advisory diagnostics failure", async () => {
- const setWarning = vi.fn();
- showContentDatabasePublishWarning({
- diagnostics: Promise.reject(new Error("diagnostics unavailable")),
- setWarning,
- });
+ test("reports database omissions and affected resource IDs", () => {
+ const findings = getContentDatabasePublishFindings(
+ createDiagnostics({
+ stats: {
+ truncated: true,
+ includedDocumentCount: 8,
+ omittedDocumentCount: 3,
+ omissionReason: "size",
+ },
+ affectedResources: [
+ { id: "resource-1", name: "Blog posts", kind: "dynamic" },
+ ],
+ })
+ );
- await Promise.resolve();
- await Promise.resolve();
- expect(setWarning).not.toHaveBeenCalled();
+ expect(findings).toHaveLength(1);
+ expect(findings[0].severity).toBe("warning");
+ expect(findings[0].reportText).toContain("Omitted documents: 3");
+ expect(findings[0].reportText).toContain(
+ "Affected resources:\ndynamic resource: Blog posts (ID: resource-1)"
+ );
+ expect(renderToStaticMarkup(findings[0].details as never)).toContain(
+ "resource-1"
+ );
});
});
diff --git a/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx b/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx
index 742c48018f..fee699377f 100644
--- a/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx
+++ b/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx
@@ -1,70 +1,143 @@
+import { Flex, Text } from "@webstudio-is/design-system";
import type { nativeClient } from "~/shared/trpc/trpc-client";
import { ContentDatabasePublishWarning } from "./content-database-publish-warning-view";
-import { showPublishWarning } from "./publish-warning";
+import type { PublishValidationFinding } from "./publish-validation-results";
type ContentDatabasePublishDiagnostics = Awaited<
ReturnType<typeof nativeClient.build.contentDatabasePublishDiagnostics.query>
>;
-export const getContentDatabasePublishWarning = (
+export const getContentDatabasePublishFindings = (
diagnostics: ContentDatabasePublishDiagnostics
) => {
+ const findings: PublishValidationFinding[] = diagnostics.mdxErrors.map(
+ ({ filename, diagnostic }) => {
+ const start =
+ "sourceRange" in diagnostic ? diagnostic.sourceRange?.start : undefined;
+ const location =
+ start === undefined ? "" : `:${start.line}:${start.column}`;
+ const message =
+ "message" in diagnostic ? diagnostic.message : diagnostic.code;
+ const fix =
+ message.includes("requires unavailable MDX Asset") ||
+ message.includes("content is unavailable")
+ ? "Choose an available MDX asset in this Content Block's source settings, or restore the missing asset."
+ : message.includes("Linked document")
+ ? "Restore or reconnect the referenced document in Content Assets, then run validation again."
+ : message.includes("violates HTML spec")
+ ? "Edit the MDX element nesting to satisfy the HTML content model. For nested links, remove one of the links."
+ : message.includes(
+ "Dynamic MDX selected by a Collection item cannot contain Resources"
+ ) ||
+ message.includes(
+ "Dynamic MDX cannot contain action Resources"
+ )
+ ? "Use a static MDX source for this Content Block, or remove Resource-dependent content from the MDX file."
+ : "Open this MDX source and fix the reported error.";
+ const context = [
+ `Diagnostic code: ${diagnostic.code}`,
+ `Content Block instance ID: ${diagnostic.blockInstanceId}`,
+ diagnostic.assetId === undefined
+ ? undefined
+ : `Asset ID: ${diagnostic.assetId}`,
+ diagnostic.contentRef === undefined
+ ? undefined
+ : `Content reference: ${diagnostic.contentRef}`,
+ diagnostic.renderScope === undefined
+ ? undefined
+ : `Render scope: ${diagnostic.renderScope}`,
+ ].filter((item): item is string => item !== undefined);
+ const sourcePosition =
+ start === undefined
+ ? undefined
+ : `Source position: ${start.line}:${start.column}`;
+ return {
+ severity: "error" as const,
+ title: `${filename}${location}`,
+ relatedInstanceId: diagnostic.blockInstanceId,
+ details: (
+ <Flex direction="column" gap={2}>
+ <Text userSelect="text">{message}</Text>
+ <Text userSelect="text">Fix: {fix}</Text>
+ {sourcePosition !== undefined && (
+ <Text userSelect="text">{sourcePosition}</Text>
+ )}
+ {context.map((item) => (
+ <Text userSelect="text" key={item}>
+ {item}
+ </Text>
+ ))}
+ </Flex>
+ ),
+ reportText: [
+ `ERROR: ${filename}${location}`,
+ message,
+ `Fix: ${fix}`,
+ ...(sourcePosition === undefined ? [] : [sourcePosition]),
+ ...context,
+ ].join("\n"),
+ };
+ }
+ );
const databaseWarning =
diagnostics.stats?.truncated &&
diagnostics.stats.omissionReason !== undefined;
- if (!databaseWarning && diagnostics.mdxOmissions.length === 0) {
- return;
- }
- return (
- <>
- {diagnostics.mdxOmissions.length > 0 && (
- <div>
- Some MDX content cannot render because its custom template is missing
- or ambiguous. Add or repair the template in the Content Block:
- <ul>
- {diagnostics.mdxOmissions.slice(0, 10).map((issue) => (
- <li key={JSON.stringify(issue)}>
- {issue.filename}: {issue.templateName}
- </li>
- ))}
- </ul>
- {diagnostics.mdxOmissions.length > 10 && (
- <div>
- And {diagnostics.mdxOmissions.length - 10} more template
- references.
- </div>
- )}
- </div>
- )}
- {databaseWarning &&
- diagnostics.stats !== undefined &&
- diagnostics.affectedResources !== undefined && (
- <ContentDatabasePublishWarning
- diagnostics={{
- stats: diagnostics.stats,
- affectedResources: diagnostics.affectedResources,
- }}
- />
- )}
- </>
+ findings.push(
+ ...diagnostics.mdxOmissions.map((issue) => ({
+ severity: "warning" as const,
+ title: `${issue.filename}: ${issue.templateName}`,
+ relatedInstanceId: issue.blockInstanceId,
+ details: (
+ <Flex direction="column" gap={2}>
+ <Text userSelect="text">
+ This MDX content cannot render because its custom template is
+ missing or ambiguous. Add or repair the template in the Content
+ Block.
+ </Text>
+ <Text userSelect="text">
+ Content Block instance ID: {issue.blockInstanceId}
+ </Text>
+ <Text userSelect="text">Asset ID: {issue.assetId}</Text>
+ </Flex>
+ ),
+ reportText: [
+ `WARNING: ${issue.filename}: ${issue.templateName}`,
+ "This MDX content cannot render because its custom template is missing or ambiguous. Add or repair the template in the Content Block.",
+ `Content Block instance ID: ${issue.blockInstanceId}`,
+ `Asset ID: ${issue.assetId}`,
+ ].join("\n"),
+ }))
);
-};
-
-export const showContentDatabasePublishWarning = ({
- diagnostics,
- setWarning,
-}: {
- diagnostics: Promise<ContentDatabasePublishDiagnostics>;
- setWarning: (warning: JSX.Element) => void;
-}) => {
- void diagnostics
- .then((diagnostics) => {
- const warning = getContentDatabasePublishWarning(diagnostics);
- if (warning !== undefined) {
- showPublishWarning({ message: warning, setWarning });
- }
- })
- .catch(() => {
- // Content warnings are advisory and must not block publishing.
+ if (
+ databaseWarning &&
+ diagnostics.stats !== undefined &&
+ diagnostics.affectedResources !== undefined
+ ) {
+ const affectedResources = diagnostics.affectedResources
+ .map(({ id, name, kind }) => `${kind} resource: ${name} (ID: ${id})`)
+ .join("\n");
+ const warningReport = [
+ "WARNING: Some content database files will be omitted.",
+ `Included documents: ${diagnostics.stats.includedDocumentCount}`,
+ `Omitted documents: ${diagnostics.stats.omittedDocumentCount}`,
+ `Omission reason: ${diagnostics.stats.omissionReason}`,
+ ...(affectedResources.length === 0
+ ? []
+ : [`Affected resources:\n${affectedResources}`]),
+ ].join("\n");
+ findings.push({
+ severity: "warning",
+ title: "Some content database files will be omitted",
+ reportText: warningReport,
+ details: (
+ <ContentDatabasePublishWarning
+ diagnostics={{
+ stats: diagnostics.stats,
+ affectedResources: diagnostics.affectedResources,
+ }}
+ />
+ ),
});
+ }
+ return findings;
};
diff --git a/apps/builder/app/builder/features/publish/publish-error.test.ts b/apps/builder/app/builder/features/publish/publish-error.test.ts
index 9e435a8e16..f836f1559a 100644
--- a/apps/builder/app/builder/features/publish/publish-error.test.ts
+++ b/apps/builder/app/builder/features/publish/publish-error.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, test } from "vitest";
import { TRPCClientError } from "@trpc/client";
import {
- getPrePublishErrorMessage,
- prePublishTimeoutMessage,
+ getPublishValidationErrorMessage,
+ publishValidationTimeoutMessage,
} from "./publish-error";
-describe("getPrePublishErrorMessage", () => {
+describe("getPublishValidationErrorMessage", () => {
test("describes a gateway timeout in terms of the publish flow", () => {
const response = new Response("<!DOCTYPE html>", {
status: 504,
@@ -16,7 +16,9 @@ describe("getPrePublishErrorMessage", () => {
{ meta: { response } }
);
- expect(getPrePublishErrorMessage(error)).toBe(prePublishTimeoutMessage);
+ expect(getPublishValidationErrorMessage(error)).toBe(
+ publishValidationTimeoutMessage
+ );
});
test("recognizes the Vercel timeout code", () => {
@@ -30,6 +32,63 @@ describe("getPrePublishErrorMessage", () => {
},
});
- expect(getPrePublishErrorMessage(error)).toBe(prePublishTimeoutMessage);
+ expect(getPublishValidationErrorMessage(error)).toBe(
+ publishValidationTimeoutMessage
+ );
+ });
+
+ test("locates a linked asset and points users to Webstudio MCP", () => {
+ const error = new Error("Document asset-id could not be loaded");
+ const asset = {
+ id: "asset-id",
+ filename: "article",
+ format: "md",
+ name: "article-storage.md",
+ folderId: "authors",
+ };
+ const folder = {
+ id: "authors",
+ name: "authors",
+ parentId: "blog",
+ projectId: "project-id",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ };
+ const parentFolder = {
+ id: "blog",
+ name: "blog",
+ projectId: "project-id",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ };
+
+ expect(
+ getPublishValidationErrorMessage(error, {
+ assets: new Map([[asset.id, asset]]) as never,
+ assetFolders: new Map([
+ [folder.id, folder],
+ [parentFolder.id, parentFolder],
+ ]) as never,
+ })
+ ).toContain(
+ "Publish validation couldn’t read “article.md” in Content Assets > blog > authors."
+ );
+ const message = getPublishValidationErrorMessage(error, {
+ assets: new Map([[asset.id, asset]]) as never,
+ assetFolders: new Map([
+ [folder.id, folder],
+ [parentFolder.id, parentFolder],
+ ]) as never,
+ });
+ expect(message).toContain("https://wstd.us/mcp");
+ expect(message).toContain("Document ID: asset-id");
+ expect(message).not.toContain("contact Webstudio support");
+ });
+
+ test("includes the document ID and MCP link when asset metadata is unavailable", () => {
+ const message = getPublishValidationErrorMessage(
+ new Error("Document asset-id could not be loaded")
+ );
+
+ expect(message).toContain("https://wstd.us/mcp");
+ expect(message).toContain("Document ID: asset-id");
});
});
diff --git a/apps/builder/app/builder/features/publish/publish-error.ts b/apps/builder/app/builder/features/publish/publish-error.ts
index 4849df780b..b115e54fc2 100644
--- a/apps/builder/app/builder/features/publish/publish-error.ts
+++ b/apps/builder/app/builder/features/publish/publish-error.ts
@@ -1,9 +1,25 @@
import { TRPCClientError } from "@trpc/client";
+import {
+ createAssetFolderHierarchy,
+ formatAssetName,
+ type AssetFolders,
+ type Assets,
+} from "@webstudio-is/sdk";
+import { formatAssetFolderPath } from "~/builder/shared/asset-manager/asset-folder-utils";
-export const prePublishTimeoutMessage =
- "Pre-publish checks timed out. Publishing was not started. Please try again.";
+export const publishValidationTimeoutMessage =
+ "Publish validation timed out. Publishing was not started. Please try again.";
-export const getPrePublishErrorMessage = (error: unknown) => {
+export const getPublishValidationErrorMessage = (
+ error: unknown,
+ {
+ assets,
+ assetFolders,
+ }: {
+ assets?: Assets;
+ assetFolders?: AssetFolders;
+ } = {}
+) => {
const response =
error instanceof TRPCClientError && error.meta?.response instanceof Response
? error.meta.response
@@ -13,9 +29,34 @@ export const getPrePublishErrorMessage = (error: unknown) => {
(response.status === 504 ||
response.headers.get("x-vercel-error") === "FUNCTION_INVOCATION_TIMEOUT")
) {
- return prePublishTimeoutMessage;
+ return publishValidationTimeoutMessage;
}
- return error instanceof Error
- ? error.message
- : "Content database validation failed";
+ const message = error instanceof Error ? error.message : undefined;
+ const unloadedDocument = /^Document (.+) could not be loaded$/.exec(
+ message ?? ""
+ );
+ if (unloadedDocument !== null) {
+ const documentId = unloadedDocument[1];
+ const asset = assets?.get(documentId);
+ if (asset !== undefined) {
+ const folderPath = formatAssetFolderPath(
+ createAssetFolderHierarchy(assetFolders ?? new Map()),
+ asset.folderId
+ );
+ const location =
+ folderPath === "Root"
+ ? "Content Assets root"
+ : `Content Assets > ${folderPath
+ .replace("Root / ", "")
+ .replaceAll(" / ", " > ")}`;
+ return [
+ `Publish validation couldn’t read “${formatAssetName(asset)}” in ${location}.`,
+ "Try again. If it continues, investigate this document with Webstudio MCP:",
+ "https://wstd.us/mcp",
+ `Document ID: ${documentId}.`,
+ ].join(" ");
+ }
+ return `Publish validation couldn’t read a linked file in Content Assets. Try again. If it continues, investigate this document with Webstudio MCP: https://wstd.us/mcp. Document ID: ${documentId}.`;
+ }
+ return message ?? "Publish validation failed";
};
diff --git a/apps/builder/app/builder/features/publish/publish-validation-results.test.tsx b/apps/builder/app/builder/features/publish/publish-validation-results.test.tsx
new file mode 100644
index 0000000000..8df0ef7fb2
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/publish-validation-results.test.tsx
@@ -0,0 +1,126 @@
+import { createRoot, type Root } from "react-dom/client";
+import { act } from "react-dom/test-utils";
+import { afterEach, expect, test, vi } from "vitest";
+import { userEvent } from "@vitest/browser/context";
+import { TooltipProvider } from "@webstudio-is/design-system";
+import {
+ PublishValidationResults,
+ type PublishValidationFinding,
+} from "./publish-validation-results";
+
+let root: Root | undefined;
+let container: HTMLDivElement | undefined;
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = undefined;
+ container?.remove();
+ container = undefined;
+ vi.restoreAllMocks();
+});
+
+const render = (findings: PublishValidationFinding[]) => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ act(() => {
+ root?.render(
+ <TooltipProvider>
+ <PublishValidationResults findings={findings} />
+ </TooltipProvider>
+ );
+ });
+ return container;
+};
+
+const createFinding = (
+ severity: PublishValidationFinding["severity"],
+ index: number
+): PublishValidationFinding => ({
+ severity,
+ title: `${severity}-${index}`,
+ details: `details-${severity}-${index}`,
+ reportText: `${severity.toUpperCase()} report-${index}`,
+});
+
+const openDetails = (element: HTMLElement) => {
+ const button = Array.from(element.querySelectorAll("button")).find(
+ (candidate) => candidate.textContent === "See issues"
+ );
+ expect(button).toBeDefined();
+ act(() => button?.click());
+};
+
+test("renders no publish summary when there are no findings", () => {
+ expect(render([]).textContent).toBe("");
+});
+
+test("shows all mixed findings, counted tabs, selectable text, and copy-all", async () => {
+ const findings = [
+ ...Array.from({ length: 6 }, (_, index) => createFinding("error", index)),
+ ...Array.from({ length: 11 }, (_, index) =>
+ createFinding("warning", index)
+ ),
+ ];
+ const writeText = vi.fn(async (_text: string) => {});
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: { writeText },
+ });
+
+ const element = render(findings);
+ expect(element.textContent).toContain("6 errors · 11 warnings");
+ openDetails(element);
+
+ expect(document.body.textContent).toContain("Diagnostics");
+ expect(document.body.textContent).toContain("Errors (6)");
+ expect(document.body.textContent).toContain("Warnings (11)");
+ expect(document.body.textContent).toContain("error-5");
+ expect(document.body.textContent).not.toContain("warning-0");
+ expect(document.body.querySelectorAll('[role="tab"]')).toHaveLength(2);
+ expect(
+ getComputedStyle(document.body.querySelector('[role="dialog"]')!).resize
+ ).toBe("both");
+ expect(document.body.querySelector('[draggable="true"]')).not.toBeNull();
+ const selectableText = Array.from(document.body.querySelectorAll("div")).find(
+ (candidate) => candidate.textContent === "details-error-0"
+ );
+ expect(selectableText).toBeDefined();
+ expect(getComputedStyle(selectableText!).userSelect).toBe("text");
+
+ const warningTab = Array.from(
+ document.body.querySelectorAll('[role="tab"]')
+ ).find((tab) => tab.textContent === "Warnings (11)");
+ await act(async () => userEvent.click(warningTab as HTMLElement));
+ expect(document.body.textContent).toContain("warning-10");
+ expect(document.body.textContent).not.toContain("error-0");
+
+ const copyButton = document.body.querySelector<HTMLButtonElement>(
+ 'button[aria-label="Copy all reports"]'
+ );
+ expect(copyButton).not.toBeNull();
+ await act(async () => {
+ copyButton?.click();
+ });
+ expect(writeText).toHaveBeenCalledOnce();
+ const copiedReport = writeText.mock.calls[0][0];
+ expect(copiedReport).toContain("ERROR report-5");
+ expect(copiedReport).toContain("WARNING report-10");
+});
+
+test.each([
+ { severity: "error" as const, otherTab: "Warnings (0)" },
+ { severity: "warning" as const, otherTab: "Errors (0)" },
+])(
+ "hides the empty tab in the $severity-only state",
+ ({ severity, otherTab }) => {
+ const element = render([createFinding(severity, 0)]);
+ openDetails(element);
+
+ expect(document.body.textContent).not.toContain(otherTab);
+ expect(document.body.querySelectorAll('[role="tab"]')).toHaveLength(1);
+ }
+);
diff --git a/apps/builder/app/builder/features/publish/publish-validation-results.tsx b/apps/builder/app/builder/features/publish/publish-validation-results.tsx
new file mode 100644
index 0000000000..67eb131abe
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/publish-validation-results.tsx
@@ -0,0 +1,178 @@
+import { Fragment, useState, type ReactNode } from "react";
+import {
+ Button,
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogTitle,
+ DialogTitleActions,
+ Flex,
+ IconButton,
+ PanelBanner,
+ PanelContent,
+ PanelTabs,
+ PanelTabsContent,
+ PanelTabsList,
+ PanelTabsTrigger,
+ ScrollArea,
+ Separator,
+ Text,
+} from "@webstudio-is/design-system";
+import { CopyIcon } from "@webstudio-is/icons";
+import { CopyToClipboard } from "~/shared/copy-to-clipboard";
+
+export type PublishValidationFinding = {
+ severity: "error" | "warning";
+ title: ReactNode;
+ details?: ReactNode;
+ link?: ReactNode;
+ relatedInstanceId?: string;
+ reportText: string;
+};
+
+export const PublishValidationResults = ({
+ findings,
+}: {
+ findings: PublishValidationFinding[];
+}) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const errors = findings.filter(({ severity }) => severity === "error");
+ const warnings = findings.filter(({ severity }) => severity === "warning");
+
+ if (findings.length === 0) {
+ return null;
+ }
+
+ const countLabel = [
+ errors.length > 0 &&
+ `${errors.length} ${errors.length === 1 ? "error" : "errors"}`,
+ warnings.length > 0 &&
+ `${warnings.length} ${warnings.length === 1 ? "warning" : "warnings"}`,
+ ]
+ .filter(Boolean)
+ .join(" · ");
+ const defaultTab = errors.length > 0 ? "errors" : "warnings";
+ const reportText = [
+ `Publish validation report: ${countLabel}`,
+ errors.length > 0 &&
+ [
+ `Errors (${errors.length})`,
+ ...errors.map(({ reportText }) => reportText),
+ ].join("\n\n"),
+ warnings.length > 0 &&
+ [
+ `Warnings (${warnings.length})`,
+ ...warnings.map(({ reportText }) => reportText),
+ ].join("\n\n"),
+ ]
+ .filter(Boolean)
+ .join("\n\n");
+
+ return (
+ <>
+ <PanelBanner variant={errors.length > 0 ? "error" : "warning"}>
+ <Flex align="center" justify="between" gap={2}>
+ <Text css={{ flex: 1, minWidth: 0 }}>
+ Publish check found {countLabel}.{" "}
+ {errors.length > 0 && "Fix the errors before publishing."}
+ </Text>
+ <Button
+ type="button"
+ color="ghost"
+ css={{ flexShrink: 0 }}
+ onClick={() => setIsOpen(true)}
+ >
+ See issues
+ </Button>
+ </Flex>
+ </PanelBanner>
+ <Dialog open={isOpen} onOpenChange={setIsOpen} draggable resize="both">
+ <DialogContent
+ width={640}
+ height={640}
+ aria-describedby={undefined}
+ css={{ display: "flex", flexDirection: "column" }}
+ >
+ <DialogTitle
+ suffix={
+ <DialogTitleActions>
+ <CopyToClipboard text={reportText} copyText="Copy all reports">
+ <IconButton
+ type="button"
+ aria-label="Copy all reports"
+ onPointerDown={(event) => event.stopPropagation()}
+ >
+ <CopyIcon aria-hidden />
+ </IconButton>
+ </CopyToClipboard>
+ <DialogClose />
+ </DialogTitleActions>
+ }
+ >
+ Diagnostics
+ </DialogTitle>
+ <PanelTabs
+ key={`${errors.length}-${warnings.length}`}
+ defaultValue={defaultTab}
+ css={{ flex: 1, minHeight: 0, overflow: "hidden" }}
+ >
+ <PanelTabsList aria-label="Publish check severity">
+ {errors.length > 0 && (
+ <PanelTabsTrigger value="errors">
+ Errors ({errors.length})
+ </PanelTabsTrigger>
+ )}
+ {warnings.length > 0 && (
+ <PanelTabsTrigger value="warnings">
+ Warnings ({warnings.length})
+ </PanelTabsTrigger>
+ )}
+ </PanelTabsList>
+ {errors.length > 0 && (
+ <PanelTabsContent
+ value="errors"
+ css={{ flex: 1, minHeight: 0, overflow: "hidden" }}
+ >
+ <FindingList findings={errors} />
+ </PanelTabsContent>
+ )}
+ {warnings.length > 0 && (
+ <PanelTabsContent
+ value="warnings"
+ css={{ flex: 1, minHeight: 0, overflow: "hidden" }}
+ >
+ <FindingList findings={warnings} />
+ </PanelTabsContent>
+ )}
+ </PanelTabs>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+};
+
+const FindingList = ({
+ findings,
+}: {
+ findings: PublishValidationFinding[];
+}) => (
+ <ScrollArea css={{ height: "100%" }}>
+ <PanelContent as={Flex} direction="column" gap={3}>
+ {findings.map((finding, index) => (
+ <Fragment key={`${finding.severity}-${index}`}>
+ <Flex direction="column" gap={2}>
+ <Text variant="labels" userSelect="text">
+ {finding.title} {finding.link}
+ </Text>
+ {finding.details !== undefined && (
+ <Text userSelect="text" color="subtle">
+ {finding.details}
+ </Text>
+ )}
+ </Flex>
+ {index < findings.length - 1 && <Separator />}
+ </Fragment>
+ ))}
+ </PanelContent>
+ </ScrollArea>
+);
diff --git a/apps/builder/app/builder/features/publish/publish-warning.test.tsx b/apps/builder/app/builder/features/publish/publish-warning.test.tsx
deleted file mode 100644
index 955ca0917b..0000000000
--- a/apps/builder/app/builder/features/publish/publish-warning.test.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { afterEach, describe, expect, test, vi } from "vitest";
-import { toast } from "@webstudio-is/design-system";
-import { $publishDialog } from "../../shared/nano-states";
-import { showPublishWarning } from "./publish-warning";
-
-describe("publish warning", () => {
- afterEach(() => {
- $publishDialog.set("none");
- vi.restoreAllMocks();
- });
-
- test.each(["publish", "export"] as const)(
- "shows the warning inline without a duplicate toast while the %s popover is open",
- (publishDialog) => {
- const toastWarn = vi.spyOn(toast, "warn").mockImplementation(() => "");
- const setWarning = vi.fn();
- const message = <span>Invalid HTML</span>;
- $publishDialog.set(publishDialog);
-
- showPublishWarning({ message, setWarning });
-
- expect(setWarning).toHaveBeenCalledWith(message);
- expect(toastWarn).not.toHaveBeenCalled();
- }
- );
-
- test("shows a toast when the publish popover is closed", () => {
- const toastWarn = vi.spyOn(toast, "warn").mockImplementation(() => "");
- const setWarning = vi.fn();
- const message = <span>Invalid HTML</span>;
-
- showPublishWarning({ message, setWarning });
-
- expect(setWarning).toHaveBeenCalledWith(message);
- expect(toastWarn).toHaveBeenCalledWith(message);
- });
-});
diff --git a/apps/builder/app/builder/features/publish/publish-warning.tsx b/apps/builder/app/builder/features/publish/publish-warning.tsx
deleted file mode 100644
index ef979d3c02..0000000000
--- a/apps/builder/app/builder/features/publish/publish-warning.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-import { toast } from "@webstudio-is/design-system";
-import { $publishDialog } from "../../shared/nano-states";
-
-export const showPublishWarning = ({
- message,
- setWarning,
-}: {
- message: JSX.Element;
- setWarning: (warning: JSX.Element) => void;
-}) => {
- if ($publishDialog.get() === "none") {
- toast.warn(message);
- }
- setWarning(message);
-};
diff --git a/apps/builder/app/builder/features/publish/publish.tsx b/apps/builder/app/builder/features/publish/publish.tsx
index 039d93db1c..b652ccdb84 100644
--- a/apps/builder/app/builder/features/publish/publish.tsx
+++ b/apps/builder/app/builder/features/publish/publish.tsx
@@ -8,6 +8,7 @@ import {
startTransition,
useRef,
useId,
+ type ReactNode,
} from "react";
import { useStore } from "@nanostores/react";
import {
@@ -60,7 +61,11 @@ import {
$stagingUsername,
$stagingPassword,
} from "~/shared/nano-states";
-import { $assets, $publisherHost } from "~/shared/sync/data-stores";
+import {
+ $assetFolders,
+ $assets,
+ $publisherHost,
+} from "~/shared/sync/data-stores";
import {
$publishDialog,
setActiveSidebarPanel,
@@ -112,18 +117,18 @@ import {
runPrePublishAudit,
type PrePublishAuditFinding,
} from "@webstudio-is/project-build/runtime";
+import { getContentDatabasePublishFindings } from "./content-database-publish-warning";
import {
- getContentDatabasePublishWarning,
- showContentDatabasePublishWarning,
-} from "./content-database-publish-warning";
+ PublishValidationResults,
+ type PublishValidationFinding,
+} from "./publish-validation-results";
import {
PublishActions,
usePublishValidationState,
type PublishValidationState,
} from "./publish-actions";
-import { showPublishWarning } from "./publish-warning";
import { flushExternalContentProject } from "~/shared/external-content-roots";
-import { getPrePublishErrorMessage } from "./publish-error";
+import { getPublishValidationErrorMessage } from "./publish-error";
const PrePublishAuditMessage = ({
finding,
@@ -131,18 +136,26 @@ const PrePublishAuditMessage = ({
finding: PrePublishAuditFinding;
}) => {
const message = formatPrePublishAuditFinding(finding);
- const { instanceId } = finding.location;
- const pages = $pages.get();
- const instances = $instances.get();
-
- if (
- instanceId === undefined ||
- pages === undefined ||
- instances.has(instanceId) === false
- ) {
+ const instanceId = finding.location.instanceId;
+ if (instanceId === undefined) {
return message;
}
+ return (
+ <>
+ {message}{" "}
+ <PrePublishInstanceLink instanceId={instanceId}>
+ Show element
+ </PrePublishInstanceLink>
+ </>
+ );
+};
+const getPrePublishInstanceTarget = (instanceId: string) => {
+ const pages = $pages.get();
+ const instances = $instances.get();
+ if (pages === undefined || instances.has(instanceId) === false) {
+ return;
+ }
const { pageId, instanceSelector } = findPageAndSelectorByInstanceId(
pages,
instances,
@@ -150,37 +163,47 @@ const PrePublishAuditMessage = ({
);
const href = getInstanceLink(instanceSelector);
if (href === undefined) {
- return message;
+ return;
}
+ return { pageId, instanceSelector, href };
+};
+const PrePublishInstanceLink = ({
+ instanceId,
+ children,
+}: {
+ instanceId: string;
+ children: ReactNode;
+}) => {
+ const target = getPrePublishInstanceTarget(instanceId);
+ if (target === undefined) {
+ return null;
+ }
return (
- <>
- {message}{" "}
- <Link
- href={href}
- onClick={(event) => {
- if (
- event.button !== 0 ||
- event.metaKey ||
- event.ctrlKey ||
- event.shiftKey ||
- event.altKey
- ) {
- return;
- }
- event.preventDefault();
- $selectedPageId.set(pageId);
- selectInstance(instanceSelector);
- $publishDialog.set("none");
- }}
- >
- Show element
- </Link>
- </>
+ <Link
+ href={target.href}
+ onClick={(event) => {
+ if (
+ event.button !== 0 ||
+ event.metaKey ||
+ event.ctrlKey ||
+ event.shiftKey ||
+ event.altKey
+ ) {
+ return;
+ }
+ event.preventDefault();
+ $selectedPageId.set(target.pageId);
+ selectInstance(target.instanceSelector);
+ $publishDialog.set("none");
+ }}
+ >
+ {children}
+ </Link>
);
};
-const getPrePublishAuditMessages = () => {
+const getPrePublishAuditFindings = (): PublishValidationFinding[] => {
const findings = runPrePublishAudit({
pages: $pages.get(),
instances: $instances.get(),
@@ -190,16 +213,98 @@ const getPrePublishAuditMessages = () => {
assets: $assets.get(),
metas: $registeredComponentMetas.get(),
});
- const getMessage = (severity: PrePublishAuditFinding["severity"]) => {
- const finding = findings.find((item) => item.severity === severity);
- return finding && <PrePublishAuditMessage finding={finding} />;
- };
+ return findings.flatMap((finding) => {
+ if (finding.severity !== "error" && finding.severity !== "warning") {
+ return [];
+ }
+ const context = Object.entries(finding.location)
+ .filter(([, value]) => value !== undefined)
+ .map(([key, value]) => `${key}: ${value}`);
+ const reportText = [
+ `${finding.severity.toUpperCase()}: ${formatPrePublishAuditFinding(
+ finding
+ )}`,
+ `Rule: ${finding.ruleId}`,
+ ...context,
+ ].join("\n");
+ return [
+ {
+ severity: finding.severity,
+ title: <PrePublishAuditMessage finding={finding} />,
+ details: context.length === 0 ? undefined : context.join(" · "),
+ reportText,
+ },
+ ];
+ });
+};
+
+const runPublishValidation = async (
+ projectId: Project["id"],
+ checkPermission = false
+) => {
+ if (checkPermission) {
+ await nativeClient.build.checkProjectBuildPermission.query({ projectId });
+ }
+ await flushExternalContentProject({ projectId });
+ const auditFindings = getPrePublishAuditFindings();
+ const diagnostics =
+ await nativeClient.build.contentDatabasePublishDiagnostics.query({
+ projectId,
+ });
+ const contentFindings = getContentDatabasePublishFindings(diagnostics).map(
+ (finding) => ({
+ ...finding,
+ link:
+ finding.relatedInstanceId === undefined ? undefined : (
+ <PrePublishInstanceLink instanceId={finding.relatedInstanceId}>
+ Open Content Block
+ </PrePublishInstanceLink>
+ ),
+ })
+ );
+ const findings = [...auditFindings, ...contentFindings];
return {
- error: getMessage("error"),
- warning: getMessage("warning"),
+ passed: findings.every(({ severity }) => severity !== "error"),
+ findings,
};
};
+const reportPublishValidationFailure = (
+ error: unknown,
+ setFindings: (findings: PublishValidationFinding[]) => void
+) => {
+ const message = getPublishValidationErrorMessage(error, {
+ assets: $assets.get(),
+ assetFolders: $assetFolders.get(),
+ });
+ if ($publishDialog.get() === "none") {
+ toast.error(message);
+ return;
+ }
+ const mcpUrl = "https://wstd.us/mcp";
+ const mcpUrlIndex = message.indexOf(mcpUrl);
+ const details =
+ mcpUrlIndex === -1 ? (
+ message
+ ) : (
+ <>
+ {message.slice(0, mcpUrlIndex)}
+ <Link href={mcpUrl} target="_blank" rel="noreferrer">
+ Webstudio MCP
+ </Link>
+ {message.slice(mcpUrlIndex + mcpUrl.length)}
+ </>
+ );
+ setFindings([
+ {
+ severity: "error",
+ title: "Unable to complete publish validation",
+ details,
+ reportText: `ERROR: Unable to complete publish validation\n${message}`,
+ },
+ ]);
+};
+
type ChangeProjectDomainProps = {
project: Project;
projectState: "idle" | "submitting";
@@ -500,9 +605,9 @@ const Publish = ({
const [publishError, setPublishError] = useState<
undefined | JSX.Element | string
>();
- const [publishWarning, setPublishWarning] = useState<
- undefined | JSX.Element | string
- >();
+ const [publishFindings, setPublishFindings] = useState<
+ PublishValidationFinding[]
+ >([]);
const buttonRef = useRef<HTMLButtonElement>(null);
const [hasSelectedDomains, setHasSelectedDomains] = useState(false);
const [hasCustomDomainsSelected, setHasCustomDomainsSelected] =
@@ -659,29 +764,6 @@ const Publish = ({
}
};
- const runPrePublishChecks = async (): Promise<boolean> => {
- await nativeClient.build.checkProjectBuildPermission.query({
- projectId: project.id,
- });
- await flushExternalContentProject({ projectId: project.id });
-
- const { error: auditError, warning: auditWarning } =
- getPrePublishAuditMessages();
- if (auditError !== undefined) {
- toast.error(auditError);
- setPublishError(auditError);
- return false;
- }
- if (auditWarning !== undefined) {
- showPublishWarning({
- message: auditWarning,
- setWarning: setPublishWarning,
- });
- }
-
- return true;
- };
-
const getDomainsFromForm = (formData: FormData) =>
formData
.getAll(domainToPublishName)
@@ -689,7 +771,7 @@ const Publish = ({
const handleValidate = async (formData: FormData) => {
setPublishError(undefined);
- setPublishWarning(undefined);
+ setPublishFindings([]);
const domains = getDomainsFromForm(formData);
if (domains.length === 0) {
toast.error("Please select at least one domain to publish");
@@ -697,37 +779,25 @@ const Publish = ({
}
try {
- const passed = await runPrePublishChecks();
- if (!passed) {
+ const checks = await runPublishValidation(project.id, true);
+ setPublishFindings(checks.findings);
+ if (checks.passed === false) {
onValidationStateChange("idle");
return;
}
- const diagnostics =
- await nativeClient.build.contentDatabasePublishDiagnostics.query({
- projectId: project.id,
- });
- const contentWarning = getContentDatabasePublishWarning(diagnostics);
- if (contentWarning !== undefined) {
- showPublishWarning({
- message: contentWarning,
- setWarning: setPublishWarning,
- });
- }
onValidationStateChange("passed");
toast.success("Validation passed. Ready to publish.", {
duration: Number.POSITIVE_INFINITY,
});
} catch (error) {
onValidationStateChange("idle");
- const message = getPrePublishErrorMessage(error);
- toast.error(message);
- setPublishError(message);
+ reportPublishValidationFailure(error, setPublishFindings);
}
};
const handlePublish = (formData: FormData) => {
setPublishError(undefined);
- setPublishWarning(undefined);
+ setPublishFindings([]);
// Custom domain checkboxes are disabled on free plan so they are never
// submitted — only the staging (wstd.io) domain can appear in formData.
@@ -742,22 +812,15 @@ const Publish = ({
setIsPublishing(true);
try {
- const passed = await runPrePublishChecks();
- if (!passed) {
+ const checks = await runPublishValidation(project.id, true);
+ setPublishFindings(checks.findings);
+ if (checks.passed === false) {
return;
}
} catch (error) {
- const message = getPrePublishErrorMessage(error);
- toast.error(message);
- setPublishError(message);
+ reportPublishValidationFailure(error, setPublishFindings);
return;
}
- showContentDatabasePublishWarning({
- diagnostics: nativeClient.build.contentDatabasePublishDiagnostics.query(
- { projectId: project.id }
- ),
- setWarning: setPublishWarning,
- });
await publish(domains);
});
};
@@ -766,13 +829,8 @@ const Publish = ({
return (
<Flex gap={2} shrink={false} direction={"column"}>
+ <PublishValidationResults findings={publishFindings} />
{publishError && <Text color="destructive">{publishError}</Text>}
- {publishWarning && (
- <PanelBanner variant="warning">
- <Text>{publishWarning}</Text>
- </PanelBanner>
- )}
-
<PublishActions
publishButtonRef={buttonRef}
validationState={validationState}
@@ -852,7 +910,9 @@ const PublishStatic = ({
const project = useStore($project);
const [_, startTransition] = useTransition();
const [publishError, setPublishError] = useState<JSX.Element | string>();
- const [publishWarning, setPublishWarning] = useState<JSX.Element | string>();
+ const [publishFindings, setPublishFindings] = useState<
+ PublishValidationFinding[]
+ >([]);
if (project == null) {
throw new Error("Project not found");
@@ -869,12 +929,8 @@ const PublishStatic = ({
return (
<Flex gap={2} shrink={false} direction={"column"}>
+ <PublishValidationResults findings={publishFindings} />
{publishError && <Text color="destructive">{publishError}</Text>}
- {publishWarning && (
- <PanelBanner variant="warning">
- <Text>{publishWarning}</Text>
- </PanelBanner>
- )}
{status === "FAILED" && <Text color="destructive">{statusText}</Text>}
<Tooltip
@@ -886,32 +942,22 @@ const PublishStatic = ({
state={isPublishInProgress ? "pending" : undefined}
onClick={() => {
setPublishError(undefined);
- setPublishWarning(undefined);
- const { error: auditError, warning: auditWarning } =
- getPrePublishAuditMessages();
- if (auditError !== undefined) {
- toast.error(auditError);
- setPublishError(auditError);
- return;
- }
- if (auditWarning !== undefined) {
- showPublishWarning({
- message: auditWarning,
- setWarning: setPublishWarning,
- });
- }
+ setPublishFindings([]);
startTransition(async () => {
try {
setIsPendingOptimistic(true);
-
- showContentDatabasePublishWarning({
- diagnostics:
- nativeClient.build.contentDatabasePublishDiagnostics.query({
- projectId,
- }),
- setWarning: setPublishWarning,
- });
+ let checks: Awaited<ReturnType<typeof runPublishValidation>>;
+ try {
+ checks = await runPublishValidation(projectId);
+ } catch (error) {
+ reportPublishValidationFailure(error, setPublishFindings);
+ return;
+ }
+ setPublishFindings(checks.findings);
+ if (checks.passed === false) {
+ return;
+ }
const result = await nativeClient.domain.publish.mutate({
projectId,
diff --git a/apps/builder/app/services/api-router.server.test.ts b/apps/builder/app/services/api-router.server.test.ts
index 421524e364..4d915043b6 100644
--- a/apps/builder/app/services/api-router.server.test.ts
+++ b/apps/builder/app/services/api-router.server.test.ts
@@ -921,7 +921,7 @@ describe("api router permits", () => {
valid: true,
target,
domains: expected,
- diagnostics: { mdxOmissions: [] },
+ diagnostics: { mdxOmissions: [], mdxErrors: [] },
});
expect(loadBuild).toHaveBeenCalledWith(expect.anything(), "project-1");
expect(loadBundle).toHaveBeenCalledWith(
diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.ts
index 19291b5874..20ad824f0a 100644
--- a/apps/builder/app/services/api-router.server.ts
+++ b/apps/builder/app/services/api-router.server.ts
@@ -1106,7 +1106,7 @@ export const apiRouter = router({
diagnostics,
};
},
- { command: "check-publish-readiness", client: "checkPublishReadiness" }
+ { command: "validate-publish", client: "validatePublish" }
),
list: projectQuery(
diff --git a/apps/builder/app/services/build-router.server.test.ts b/apps/builder/app/services/build-router.server.test.ts
index de19b0f95e..ff370a7f3e 100644
--- a/apps/builder/app/services/build-router.server.test.ts
+++ b/apps/builder/app/services/build-router.server.test.ts
@@ -4,6 +4,10 @@ import { createPublishedProjectBundleFixture } from "@webstudio-is/protocol/fixt
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";
+import {
+ createAssetIndex,
+ createCanonicalAssetFileEntry,
+} from "@webstudio-is/content-engine/compiler";
const {
assertCliBundleVersion,
@@ -162,6 +166,105 @@ describe("content database publish diagnostics", () => {
expect(loadProjectBundle).toHaveBeenCalledOnce();
});
+ test("reports publish-time MDX errors with the user-facing asset filename", async () => {
+ const bundle = createPublishedProjectBundleFixture();
+ const blockId = bundle.build.pages.pages[0].rootInstanceId;
+ const source = `1. item\n\n <ws.element ws:tag="li">nested item</ws.element>`;
+ bundle.build.instances = [
+ [
+ blockId,
+ {
+ id: blockId,
+ type: "instance",
+ component: "ws:block",
+ children: [{ type: "id", value: "templates" }],
+ },
+ ],
+ [
+ "templates",
+ {
+ id: "templates",
+ type: "instance",
+ component: "ws:block-template",
+ children: [],
+ },
+ ],
+ ];
+ bundle.build.props = [
+ [
+ "content-source",
+ {
+ id: "content-source",
+ instanceId: blockId,
+ name: "src",
+ type: "asset",
+ value: "article",
+ },
+ ],
+ ];
+ bundle.assets = [
+ {
+ id: "article",
+ projectId: bundle.build.projectId,
+ name: "article-storage.mdx",
+ filename: "article",
+ type: "file",
+ format: "mdx",
+ size: new TextEncoder().encode(source).byteLength,
+ meta: {},
+ createdAt: "2026-09-17T00:00:00.000Z",
+ },
+ ];
+ bundle.assetIndex = {
+ ...(await createAssetIndex({
+ projectId: bundle.build.projectId,
+ entries: [
+ createCanonicalAssetFileEntry({
+ projectId: bundle.build.projectId,
+ document: {
+ _id: "article",
+ _type: "asset.file",
+ name: "article.mdx",
+ path: "blog/article.mdx",
+ key: "article",
+ extension: "mdx",
+ mimeType: "text/mdx",
+ size: new TextEncoder().encode(source).byteLength,
+ revision: "revision",
+ contentRef: "article-storage.mdx",
+ properties: {},
+ },
+ }),
+ ],
+ maxBytes: 5000,
+ })),
+ contents: { "article-storage.mdx": source },
+ };
+ const loadProjectBundle = vi.fn(async (_projectId, _ctx, options) => {
+ options.onMdxBlockInstanceId(blockId);
+ return bundle;
+ });
+
+ const result = await loadContentDatabasePublishDiagnostics(
+ "project-id",
+ {} as never,
+ { loadProjectBundleByProjectId: loadProjectBundle as never }
+ );
+
+ expect(result.mdxErrors).toEqual([
+ expect.objectContaining({
+ filename: "article.mdx",
+ diagnostic: expect.objectContaining({
+ code: "invalid-mdx",
+ severity: "error",
+ blockInstanceId: blockId,
+ assetId: "article",
+ message: "Placing <li> element inside a <li> violates HTML spec.",
+ }),
+ }),
+ ]);
+ });
+
test("uses the same edit permit as publishing", async () => {
const hasProjectPermit = vi
.spyOn(authorizeProject, "hasProjectPermit")
diff --git a/apps/builder/app/services/content-database-publish-diagnostics.server.ts b/apps/builder/app/services/content-database-publish-diagnostics.server.ts
index efaa4fb946..1ac27805a5 100644
--- a/apps/builder/app/services/content-database-publish-diagnostics.server.ts
+++ b/apps/builder/app/services/content-database-publish-diagnostics.server.ts
@@ -3,8 +3,24 @@ import {
formatMdxTemplatePublishDiagnostics,
getContentDatabasePublishDiagnostics,
} from "./content-database.server";
-import type { PublishedMdxTemplateOmission } from "@webstudio-is/project-build";
+import {
+ resolvePublishedMdxAssetCandidates,
+ type PublishedMdxTemplateOmission,
+} from "@webstudio-is/project-build";
+import {
+ getUnsafeDynamicPublishedMdxDiagnostic,
+ materializePublishedMdx,
+} from "@webstudio-is/project-build/runtime";
+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";
+import { formatAssetName } from "@webstudio-is/sdk";
+import { migratePages } from "@webstudio-is/project-migrations/pages";
+import { contentEngineLimits } from "@webstudio-is/content-engine";
+import {
+ decodeUtf8,
+ readBoundedBytes,
+} from "@webstudio-is/content-engine/compiler";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import { createAssetClient } from "~/shared/asset-client";
export const loadContentDatabasePublishDiagnostics = async (
projectId: string,
@@ -14,6 +30,7 @@ export const loadContentDatabasePublishDiagnostics = async (
} = { loadProjectBundleByProjectId }
) => {
let mdxTemplateOmissions: readonly PublishedMdxTemplateOmission[] = [];
+ const mdxBlockInstanceIds = new Set<string>();
const bundle = await dependencies.loadProjectBundleByProjectId(
projectId,
ctx,
@@ -21,13 +38,95 @@ export const loadContentDatabasePublishDiagnostics = async (
onMdxTemplateOmissions: (issues) => {
mdxTemplateOmissions = issues;
},
+ onMdxBlockInstanceId: (blockInstanceId) =>
+ mdxBlockInstanceIds.add(blockInstanceId),
}
);
+ const mdxErrors: Array<{
+ filename: string;
+ diagnostic: Awaited<
+ ReturnType<typeof materializePublishedMdx>
+ >["warnings"][number]["diagnostic"];
+ }> = [];
+ if (bundle.assetIndex !== undefined) {
+ const assetStore = createAssetClient();
+ const data = {
+ instances: new Map(bundle.build.instances),
+ props: new Map(bundle.build.props),
+ dataSources: new Map(bundle.build.dataSources),
+ resources: new Map(bundle.build.resources),
+ styleSources: new Map(bundle.build.styleSources),
+ styleSourceSelections: new Map(bundle.build.styleSourceSelections),
+ styles: new Map(bundle.build.styles),
+ breakpoints: new Map(bundle.build.breakpoints),
+ assets: new Map(bundle.assets.map((asset) => [asset.id, asset])),
+ ...(bundle.assetFolders === undefined
+ ? {}
+ : {
+ assetFolders: new Map(
+ bundle.assetFolders.map((folder) => [folder.id, folder])
+ ),
+ }),
+ };
+ const dynamicAssetIdsByBlock = resolvePublishedMdxAssetCandidates({
+ build: { ...bundle.build, pages: migratePages(bundle.build.pages) },
+ artifact: bundle.assetIndex,
+ blockInstanceIds: mdxBlockInstanceIds,
+ });
+ const materialized = await materializePublishedMdx({
+ route: "prepublish",
+ data,
+ artifact: bundle.assetIndex,
+ metas: componentMetas,
+ projectId: bundle.build.projectId,
+ blockInstanceIds: mdxBlockInstanceIds,
+ dynamicAssetIdsByBlock,
+ loadDocumentSource: async ({ contentRef }) => {
+ const { data } = await assetStore.readFile(contentRef);
+ return decodeUtf8(
+ await readBoundedBytes(data, contentEngineLimits.hydratedFileBytes)
+ );
+ },
+ });
+ const assets = new Map(bundle.assets.map((asset) => [asset.id, asset]));
+ const getFilename = (assetId: string, fallback: string) => {
+ const asset = assets.get(assetId);
+ return asset === undefined ? fallback : formatAssetName(asset);
+ };
+ for (const root of materialized.roots) {
+ const diagnostic = getUnsafeDynamicPublishedMdxDiagnostic({
+ root,
+ route: "prepublish",
+ dataSources: data.dataSources,
+ props: data.props,
+ });
+ if (diagnostic !== undefined) {
+ mdxErrors.push({
+ filename: getFilename(
+ root.identity.assetId,
+ root.identity.contentRef
+ ),
+ diagnostic,
+ });
+ }
+ }
+ for (const { diagnostic } of materialized.warnings) {
+ if (diagnostic.severity !== "error") {
+ continue;
+ }
+ const assetId = diagnostic.assetId ?? "";
+ mdxErrors.push({
+ filename: getFilename(assetId, diagnostic.contentRef ?? "MDX content"),
+ diagnostic,
+ });
+ }
+ }
return {
...getContentDatabasePublishDiagnostics(bundle),
mdxOmissions: formatMdxTemplatePublishDiagnostics(
bundle,
mdxTemplateOmissions
),
+ mdxErrors,
};
};
diff --git a/apps/builder/app/services/content-database.server.ts b/apps/builder/app/services/content-database.server.ts
index 5212ae6bad..4bf346fa4f 100644
--- a/apps/builder/app/services/content-database.server.ts
+++ b/apps/builder/app/services/content-database.server.ts
@@ -51,6 +51,7 @@ export const getContentDatabaseMaxBytes = () =>
export type ContentDatabasePublishDiagnostics = {
stats: NonNullable<ReturnType<typeof analyzeContentDatabasePublish>>["stats"];
affectedResources: Array<{
+ id: string;
name: string;
kind: "dynamic" | "static";
}>;
@@ -72,6 +73,7 @@ export const getContentDatabasePublishDiagnostics = (
return {
stats: diagnostics.stats,
affectedResources: diagnostics.queries.map(({ id, kind }) => ({
+ id,
name: resourceNameById.get(id) ?? id,
kind,
})),
diff --git a/apps/builder/app/shared/db/canvas.server.ts b/apps/builder/app/shared/db/canvas.server.ts
index 99bd197e17..9a145c22ce 100644
--- a/apps/builder/app/shared/db/canvas.server.ts
+++ b/apps/builder/app/shared/db/canvas.server.ts
@@ -178,6 +178,7 @@ const addProjectMetadata = async (
onMdxTemplateOmissions?: (
issues: readonly PublishedMdxTemplateOmission[]
) => void;
+ onMdxBlockInstanceId?: (blockInstanceId: string) => void;
contentIndex?: "client";
} = {}
): Promise<PublishedProjectBundle> => {
@@ -253,6 +254,7 @@ const addProjectMetadata = async (
build: publicationBuild,
artifact,
onTemplateOmission: (issue) => nextOmissions.push(issue),
+ onMdxBlockInstanceId: options.onMdxBlockInstanceId,
});
mdxTemplateOmissions = nextOmissions;
return plan!;
@@ -381,6 +383,7 @@ export const loadProjectBundleByProjectId = async (
onMdxTemplateOmissions?: (
issues: readonly PublishedMdxTemplateOmission[]
) => void;
+ onMdxBlockInstanceId?: (blockInstanceId: string) => void;
} = {}
): Promise<PublishedProjectBundle> => {
const project = await loadById(projectId, context);
diff --git a/docs/university/foundations/publishing-and-custom-domains.md b/docs/university/foundations/publishing-and-custom-domains.md
index dce12094d3..178d8c128c 100644
--- a/docs/university/foundations/publishing-and-custom-domains.md
+++ b/docs/university/foundations/publishing-and-custom-domains.md
@@ -8,10 +8,10 @@ description: Learn how to connect a custom domain to your Project.
Many DNS providers do not allow adding a CNAME at the root/apex. If yours doesn’t, jump to [this section](publishing-and-custom-domains.md#dns-provider-doesnt-allow-cname-flattening) for alternate options.
{% endhint %}
-## Pre-publish checks
+## Publish validation
-Webstudio checks publishable pages before starting a cloud publish or static
-export. These checks detect broken Resource references and invalid HTML nesting
+Choose **Validate** in the publish dialog before publishing or exporting. Webstudio
+checks publishable pages for broken Resource references and invalid HTML nesting
that could make the generated site fail or behave unexpectedly.
- **Errors** stop publishing until you resolve them.
diff --git a/packages/cli/src/commands/api-command-metadata.ts b/packages/cli/src/commands/api-command-metadata.ts
index 43a5670fa0..74bff2516d 100644
--- a/packages/cli/src/commands/api-command-metadata.ts
+++ b/packages/cli/src/commands/api-command-metadata.ts
@@ -214,7 +214,7 @@ const apiCommandOptionsByCommand: Partial<
"delete-resource": apiCommand.deleteResourceCommandOptions,
"list-domains": apiCommand.paginatedListCommandOptions,
publish: apiCommand.publishCommandOptions,
- "check-publish-readiness": apiCommand.checkPublishReadinessCommandOptions,
+ "validate-publish": apiCommand.validatePublishCommandOptions,
"get-publish-job": apiCommand.publishJobCommandOptions,
unpublish: apiCommand.unpublishCommandOptions,
"create-domain": apiCommand.createDomainCommandOptions,
@@ -251,8 +251,8 @@ export const apiCommandMetadata = publicApiOperations.map((operation) => ({
export const highLevelCliCommands = [
{ command: "audit", operation: "audit" },
{
- command: "check-publish-readiness",
- operation: "check-publish-readiness",
+ command: "validate-publish",
+ operation: "validate-publish",
},
{ command: "permissions", operation: "permissions" },
{ command: "get-assets-resource", operation: "get-assets-resource" },
diff --git a/packages/cli/src/commands/api-command.test.ts b/packages/cli/src/commands/api-command.test.ts
index 3b770b626a..7de623166d 100644
--- a/packages/cli/src/commands/api-command.test.ts
+++ b/packages/cli/src/commands/api-command.test.ts
@@ -1852,14 +1852,14 @@ test("publishes project", async () => {
});
});
-test("checks publish readiness without publishing", async () => {
+test("validates publishing without publishing", async () => {
await expectCommandCall({
options: {
- command: "check-publish-readiness",
+ command: "validate-publish",
target: "production",
domain: ["example.com,www.example.com"],
},
- call: apiCalls.checkPublishReadiness,
+ call: apiCalls.validatePublish,
connection: {
target: "production",
domains: ["example.com", "www.example.com"],
diff --git a/packages/cli/src/commands/api-command.ts b/packages/cli/src/commands/api-command.ts
index a71440796c..b6f17fb5e4 100644
--- a/packages/cli/src/commands/api-command.ts
+++ b/packages/cli/src/commands/api-command.ts
@@ -1160,7 +1160,7 @@ export const publishCommandOptions = (yargs: CommonYargsArgv) =>
describe: "Optional idempotency key for retrying the same publish",
});
-export const checkPublishReadinessCommandOptions = (yargs: CommonYargsArgv) =>
+export const validatePublishCommandOptions = (yargs: CommonYargsArgv) =>
publishDomainsOption(publishTargetOption(apiCommandOptions(yargs)));
export const publishJobCommandOptions = (yargs: CommonYargsArgv) =>
@@ -3032,13 +3032,13 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
};
return runProjectSessionCommand("publish", input, connection, dependencies);
},
- "check-publish-readiness": async (options, connection, dependencies) => {
+ "validate-publish": async (options, connection, dependencies) => {
const input = {
target: publishTargetValue(options.target),
domains: listStringOption(options.domain),
};
return runProjectSessionCommand(
- "check-publish-readiness",
+ "validate-publish",
input,
connection,
dependencies
diff --git a/packages/cli/src/commands/man.ts b/packages/cli/src/commands/man.ts
index 6f497c5bc8..fa9cf31297 100644
--- a/packages/cli/src/commands/man.ts
+++ b/packages/cli/src/commands/man.ts
@@ -497,7 +497,7 @@ const apiCommandsByArea = {
publishAndDomains: cliCommandMetadata
.filter(
({ cliCommand }) =>
- cliCommand === "check-publish-readiness" ||
+ cliCommand === "validate-publish" ||
cliCommand.startsWith("publish ") ||
cliCommand.startsWith("domains ")
)
diff --git a/packages/cli/src/commands/schema.test.ts b/packages/cli/src/commands/schema.test.ts
index a109aca38d..f460ddeed5 100644
--- a/packages/cli/src/commands/schema.test.ts
+++ b/packages/cli/src/commands/schema.test.ts
@@ -169,7 +169,7 @@ test("prints compact mcp tool summaries as json by default", () => {
method: "mutation",
}),
expect.objectContaining({
- name: "check-publish-readiness",
+ name: "validate-publish",
operationId: "publish.validate",
method: "query",
}),
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index 1633b1017a..3b4f6faed3 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -7,7 +7,7 @@ import {
relative,
sep,
} from "node:path";
-import { existsSync } from "node:fs";
+import { createReadStream, existsSync } from "node:fs";
import { rm, cp, readFile, writeFile, readdir } from "node:fs/promises";
import { cwd, exit } from "node:process";
import { fileURLToPath } from "node:url";
@@ -96,6 +96,10 @@ import {
verifyContentArtifact,
} from "@webstudio-is/content-engine";
import { contentEngineLimits } from "@webstudio-is/content-engine/limits";
+import {
+ decodeUtf8,
+ readBoundedBytes,
+} from "@webstudio-is/content-engine/compiler";
import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";
import {
parseJsonExpression,
@@ -1355,6 +1359,21 @@ export const prebuild = async (options: {
dynamicAssetIdsByBlock: pageDynamicCandidates,
blockInstanceIds: pendingBlockIds,
runtimeAssets: runtimeAssetsById,
+ loadDocumentSource: async ({ contentRef }) => {
+ const source = createReadStream(
+ getLocalAssetPath(
+ contentRef,
+ options.sourceAssetsDirectory ??
+ join(buildRoot, LOCAL_ASSETS_DIR)
+ )
+ );
+ return decodeUtf8(
+ await readBoundedBytes(
+ source,
+ contentEngineLimits.hydratedFileBytes
+ )
+ );
+ },
});
for (const root of materialized.roots) {
const diagnostic = getUnsafeDynamicPublishedMdxDiagnostic({
diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.ts
index 83972b5aab..f183fe6bb1 100644
--- a/packages/http-client/src/index.test.ts
+++ b/packages/http-client/src/index.test.ts
@@ -93,7 +93,7 @@ import {
loadProjectBundleByProjectId,
moveInstance,
publish,
- checkPublishReadiness,
+ validatePublish,
readProjectAssetContent,
parseBuildPatchTransactions,
parseBuilderUrl,
@@ -800,7 +800,7 @@ test("wraps project api trpc calls in named functions", async () => {
scopeInstanceId: "body-id",
});
await listPublishes(params);
- await checkPublishReadiness({
+ await validatePublish({
...params,
target: "production",
domains: ["example.com"],
diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.ts
index bb8bbda11f..7731156a56 100644
--- a/packages/http-client/src/index.ts
+++ b/packages/http-client/src/index.ts
@@ -2256,12 +2256,12 @@ export const listPublishes = projectQueryInput<
AuthProjectParams & PaginatedQueryInput
>("list-publishes");
-export const checkPublishReadiness = projectQueryInput<
+export const validatePublish = projectQueryInput<
AuthProjectParams & {
target: "staging" | "production";
domains?: string[];
}
->("check-publish-readiness");
+>("validate-publish");
export const publish = projectMutationInput<
AuthProjectParams & {
diff --git a/packages/project-build/src/content-database.ts b/packages/project-build/src/content-database.ts
index 151bb69311..7e2e845cde 100644
--- a/packages/project-build/src/content-database.ts
+++ b/packages/project-build/src/content-database.ts
@@ -231,6 +231,7 @@ type ResolvePublishedMdxDependencyClosureOptions = {
build: PublishedContentDatabaseBuild;
artifact: ContentArtifactV1;
onTemplateOmission?: (issue: PublishedMdxTemplateOmission) => void;
+ onMdxBlockInstanceId?: (blockInstanceId: string) => void;
allMdxAssetIds?: ReadonlySet<string>;
};
@@ -238,6 +239,7 @@ const resolvePublishedMdxDependencyClosureWithParser = async ({
build,
artifact,
onTemplateOmission,
+ onMdxBlockInstanceId,
allMdxAssetIds,
parseDocument,
}: ResolvePublishedMdxDependencyClosureOptions & {
@@ -293,6 +295,7 @@ const resolvePublishedMdxDependencyClosureWithParser = async ({
if (source === undefined) {
continue;
}
+ onMdxBlockInstanceId?.(blockId);
const staticValue = getStaticContentBlockSourceAssetId(source);
const assetIds =
typeof staticValue === "string"
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index 0af6164ec9..46c8cb9422 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -4352,8 +4352,9 @@ const capabilityAreas = [
},
{
area: "publish",
- goal: "Publish, unpublish, inspect publish jobs, and manage domains.",
+ goal: "Validate and publish projects, inspect publish jobs, and manage domains.",
tools: [
+ "validate-publish",
"publish",
"list-publishes",
"get-publish-job",
diff --git a/packages/project-build/src/runtime/published-mdx.test.ts b/packages/project-build/src/runtime/published-mdx.test.ts
index eac1648f97..0cd0167e01 100644
--- a/packages/project-build/src/runtime/published-mdx.test.ts
+++ b/packages/project-build/src/runtime/published-mdx.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from "vitest";
+import { describe, expect, test, vi } from "vitest";
import type { ContentArtifactV1 } from "@webstudio-is/content-engine";
import {
discoverMdxBodyAssetReferences,
@@ -908,6 +908,62 @@ featureImage:
})
).rejects.toThrow("Document graph source missing does not exist");
});
+
+ test("loads a referenced author when only the MDX source is embedded", async () => {
+ const source =
+ "---\nauthor:\n $ref: ./author.md#frontmatter\n---\n# Published";
+ const artifact = createArtifact([{ id: "article", source }]);
+ artifact.documentGraph = {
+ format: "webstudio-document-graph",
+ version: 1,
+ nodes: [
+ {
+ id: "article",
+ revision: revision("b"),
+ contentRef: "article.mdx",
+ format: "mdx",
+ },
+ {
+ id: "author",
+ revision: revision("c"),
+ contentRef: "author.md",
+ format: "markdown",
+ },
+ ],
+ edges: [
+ {
+ sourceId: "article",
+ referenceId: "#frontmatter/author",
+ reference: {
+ documentId: "author",
+ revision: revision("c"),
+ representation: { type: "markdown-frontmatter" },
+ },
+ },
+ ],
+ integrity: { algorithm: "sha256", checksum: revision("d") },
+ };
+ const loadDocumentSource = vi.fn(async () => "---\nname: Oleg\n---\n");
+
+ const result = await materializePublishedMdx({
+ route: "/",
+ data: createData({}),
+ artifact,
+ metas: new Map(),
+ projectId: "project",
+ loadDocumentSource,
+ });
+
+ expect(result.roots[0].resolvedFrontmatter.author).toEqual({
+ name: "Oleg",
+ });
+ expect(loadDocumentSource).toHaveBeenCalledExactlyOnceWith({
+ id: "author",
+ revision: revision("c"),
+ contentRef: "author.md",
+ format: "markdown",
+ });
+ });
});
describe("getUnsafeDynamicPublishedMdxDiagnostic", () => {
diff --git a/packages/project-build/src/runtime/published-mdx.ts b/packages/project-build/src/runtime/published-mdx.ts
index de2bd319a5..ba7fe9e1c7 100644
--- a/packages/project-build/src/runtime/published-mdx.ts
+++ b/packages/project-build/src/runtime/published-mdx.ts
@@ -14,6 +14,7 @@ import type {
import {
contentEngineLimits,
createDocumentGraph,
+ DocumentGraphResolutionError,
getDocumentGraphClosure,
resolveAssetValueReferences,
resolveDocumentGraphProperties,
@@ -215,6 +216,7 @@ export const materializePublishedMdx = async ({
dynamicAssetIdsByBlock = new Map(),
blockInstanceIds,
runtimeAssets: providedRuntimeAssets,
+ loadDocumentSource,
}: {
route: string;
data: Omit<WebstudioData, "pages">;
@@ -225,6 +227,10 @@ export const materializePublishedMdx = async ({
dynamicAssetIdsByBlock?: ReadonlyMap<string, readonly string[]>;
blockInstanceIds?: ReadonlySet<string>;
runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>;
+ loadDocumentSource?: (node: {
+ id: string;
+ contentRef: string;
+ }) => Promise<string>;
}): Promise<{
roots: readonly PublishedMdxRoot[];
warnings: readonly PublishedMdxWarning[];
@@ -267,7 +273,9 @@ export const materializePublishedMdx = async ({
assetValueReferences: artifact.assetValueReferences,
runtimeAssets,
load: async (node) => {
- const source = artifact.contents?.[node.contentRef];
+ const source =
+ artifact.contents?.[node.contentRef] ??
+ (await loadDocumentSource?.(node));
if (source === undefined || node.format === undefined) {
throw new Error(`Published document ${node.id} is unavailable`);
}
@@ -442,6 +450,38 @@ export const materializePublishedMdx = async ({
resolution.references.map((reference) => reference.templateName)
)
);
+ let resolvedFrontmatter = document.frontmatter.properties;
+ try {
+ resolvedFrontmatter = await resolveFrontmatter(candidate._id, document);
+ } catch (error) {
+ if (
+ error instanceof DocumentGraphResolutionError &&
+ error.code === "REQUEST_CANCELLED"
+ ) {
+ throw error;
+ }
+ if (error instanceof DocumentGraphResolutionError) {
+ const linkedDocument =
+ error.documentId === undefined
+ ? "Linked document"
+ : `Linked document "${error.documentId}"`;
+ const reference =
+ error.referenceId === undefined
+ ? ""
+ : ` (reference "${error.referenceId}")`;
+ const failure =
+ error.code === "DOCUMENT_LOAD_FAILED"
+ ? "could not be loaded"
+ : `could not be resolved: ${error.message}`;
+ warnUnavailableSource({
+ blockInstanceId: block.id,
+ assetId: candidate._id,
+ message: `${linkedDocument} ${failure}${reference} while resolving frontmatter for published MDX Asset "${candidate._id}".`,
+ });
+ } else {
+ throw error;
+ }
+ }
const materialized = materializeMdxAuthoredContent({
identity,
document,
@@ -477,7 +517,7 @@ export const materializePublishedMdx = async ({
dynamic: isDynamicSource,
identity,
document,
- resolvedFrontmatter: await resolveFrontmatter(candidate._id, document),
+ resolvedFrontmatter,
fragment: materialized.fragment,
templateDependencies: templates.dependencies.templates,
templateNames: referencedTemplateNames,
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 17fd103999..cd16877ea8 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
@@ -1529,10 +1529,10 @@ export const serverOnlyRouterOperationMetadata = {
},
"publish.validate": {
id: "publish.validate",
- command: "check-publish-readiness",
+ command: "validate-publish",
method: "query",
path: "api.publish.validate",
- client: "checkPublishReadiness",
+ client: "validatePublish",
permit: "edit",
inputSchema: {
type: "object",
diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.ts
index 2c09316687..e37635a623 100644
--- a/packages/protocol/src/builder-api/operation-docs.ts
+++ b/packages/protocol/src/builder-api/operation-docs.ts
@@ -716,13 +716,13 @@ const curatedPublicApiOperationDocumentation = [
examples: ["webstudio delete-resource --resource resource-id --json"],
},
{
- command: "check-publish-readiness",
+ command: "validate-publish",
description:
- "Check publish access, selected domains, and content diagnostics without starting a publish. Use audit for project-wide quality checks.",
+ "Validate publish access, selected domains, and content diagnostics without starting a publish. Use audit for project-wide quality checks.",
requiredOptions: ["target", "json"],
examples: [
- "webstudio check-publish-readiness --target production --json",
- 'MCP tool: check-publish-readiness {"target":"production"}',
+ "webstudio validate-publish --target production --json",
+ 'MCP tool: validate-publish {"target":"production"}',
],
},
{