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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: report missing JSON prop values during publish (#6506)
Oleg Isonen7767d281f31f
diff --git a/packages/cli/src/commands/sync.test.ts b/packages/cli/src/commands/sync.test.tsindex 6fa2e95544..aecfe479be 100644--- a/packages/cli/src/commands/sync.test.ts+++ b/packages/cli/src/commands/sync.test.ts@@ -23,6 +23,7 @@ import {createCanonicalAssetFileEntry,} from "@webstudio-is/content-engine/compiler";import { bundleVersion } from "@webstudio-is/protocol";+import { MissingJsonPropValueError } from "@webstudio-is/http-client";import {createImageAssetFixture,createPublishedProjectBundleFixture,@@ -529,7 +530,9 @@ test("hosted sync compiles metadata-only dynamic MDX into a server-rendered pagechildren: [{type: "expression",- value: `${encodeDataSourceVariable("document")}.frontmatter.title`,+ value: `${encodeDataSourceVariable(+ "document"+ )}.frontmatter.title`,},],},@@ -796,6 +799,34 @@ test("explains unpublished project bundle errors when synchronizing by build id");});+test("shows actionable diagnostics for JSON props with no value", async () => {+ loadProjectBundleByBuildId.mockRejectedValue(+ new MissingJsonPropValueError([+ "“Projects” (ws:collection): JSON prop “data” has no value",+ ])+ );++ await expect(+ sync(+ {+ authToken: "token-1",+ buildId: "build-1",+ origin: "https://example.com",+ },+ dependencies+ )+ ).rejects.toThrow("Handled CLI error");++ expect(indicator.stop).toHaveBeenCalledWith(+ [+ "This build cannot be published because it contains JSON props with no value:",+ "- “Projects” (ws:collection): JSON prop “data” has no value",+ "Open the project in Webstudio, set or reset the affected prop, then publish again.",+ ].join("\n"),+ 2+ );+});+test("does not write local data when synchronized asset download fails", async () => {const assets = [createImageAssetFixture()];loadProjectBundleByBuildId.mockResolvedValue(createProjectBundle({ assets }));diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.tsindex 62b0168d24..67ffddb896 100644--- a/packages/cli/src/commands/sync.ts+++ b/packages/cli/src/commands/sync.ts@@ -11,6 +11,7 @@ import {getApiErrorCode,loadProjectBundleByBuildId,loadBuilderDataByProjectId,+ MissingJsonPropValueError,toLocalProjectBundle,} from "@webstudio-is/http-client";import { createFileIfNotExists, isFileExists } from "../fs-utils";@@ -166,6 +167,10 @@ export const sync = async (syncing.stop(unpublishedProjectBundleMessage, 2);throw new HandledCliError();}+ if (error instanceof MissingJsonPropValueError) {+ syncing.stop(error.message, 2);+ throw new HandledCliError();+ }const compatibilityMessage = stopSpinnerWithError(syncing,error,diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.tsindex 13d7b300f1..abec50f12d 100644--- a/packages/http-client/src/index.test.ts+++ b/packages/http-client/src/index.test.ts@@ -1303,6 +1303,54 @@ test("loads project bundle by build id without auth headers", async () => {);});+test("reports json props without a value when loading a published bundle", async () => {+ const project = JSON.parse(+ JSON.stringify(createPublishedProjectBundleFixture())+ );+ project.build.instances = [+ [+ "instance-id",+ {+ id: "instance-id",+ type: "instance",+ component: "ws:collection",+ label: "Projects",+ },+ ],+ ];+ project.build.props = [+ [+ "json-prop-id",+ {+ id: "json-prop-id",+ instanceId: "instance-id",+ name: "data",+ type: "json",+ },+ ],+ ];+ const fetch = vi.fn().mockResolvedValue(+ new Response(JSON.stringify([{ result: { data: project } }]), {+ headers: { "content-type": "application/json" },+ })+ );+ vi.stubGlobal("fetch", fetch);++ await expect(+ loadProjectBundleByBuildId({+ buildId: project.build.id,+ origin: "https://example.com",+ })+ ).rejects.toMatchObject({+ name: "MissingJsonPropValueError",+ message: [+ "This build cannot be published because it contains JSON props with no value:",+ "- “Projects” (ws:collection): JSON prop “data” has no value",+ "Open the project in Webstudio, set or reset the affected prop, then publish again.",+ ].join("\n"),+ });+});+test("requests local content preparation for the publish runner", async () => {const project = createPublishedProjectBundleFixture();const fetch = vi.fn().mockResolvedValue(diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.tsindex 7731156a56..a88f7981d2 100644--- a/packages/http-client/src/index.ts+++ b/packages/http-client/src/index.ts@@ -115,6 +115,42 @@ const createApiResponseErrorMessage = async (.join("\n");};+export class MissingJsonPropValueError extends Error {+ constructor(diagnostics: string[]) {+ super(+ [+ "This build cannot be published because it contains JSON props with no value:",+ ...diagnostics.map((diagnostic) => `- ${diagnostic}`),+ "Open the project in Webstudio, set or reset the affected prop, then publish again.",+ ].join("\n")+ );+ this.name = "MissingJsonPropValueError";+ }+}++const getMissingJsonPropValueDiagnostics = (data: unknown) => {+ const build = (data as { build?: PublishedProjectBundle["build"] } | null)+ ?.build;+ if (!Array.isArray(build?.props)) {+ return;+ }++ const instances = new Map(+ Array.isArray(build.instances) ? build.instances : []+ );+ const diagnostics = build.props.flatMap((entry) => {+ const prop = Array.isArray(entry) ? entry[1] : undefined;+ if (!prop || prop.type !== "json" || prop.value !== undefined) {+ return [];+ }+ const instance = instances.get(prop.instanceId);+ const target = instance?.label ?? `instance ${prop.instanceId}`;+ const component = instance?.component ? ` (${instance.component})` : "";+ return [`“${target}”${component}: JSON prop “${prop.name}” has no value`];+ });+ return diagnostics.length > 0 ? diagnostics : undefined;+};+const fetchJsonResponse: typeof fetch = async (request, init) => {const response = await fetch(request, init);const contentType = response.headers.get("content-type");@@ -443,7 +479,9 @@ class AssetUploadRetryError extends Error {constructor(assetName: string, cause: unknown) {const status = getErrorStatus(cause);super(- `Asset "${assetName}" failed after 2 attempts${status === undefined ? "" : ` (HTTP ${status})`}. Retry this file by itself. If it still fails, verify that it opens and matches its declared format, then report ${assetUploadRetryExhaustedCode} and the HTTP status.`,+ `Asset "${assetName}" failed after 2 attempts${+ status === undefined ? "" : ` (HTTP ${status})`+ }. Retry this file by itself. If it still fails, verify that it opens and matches its declared format, then report ${assetUploadRetryExhaustedCode} and the HTTP status.`,{ cause });this.status = status;@@ -680,7 +718,9 @@ const toUploadAsset = ({descriptor.format === undefined) {throw new Error(- `${descriptor.type === "image" ? "Image" : "Video"} asset "${descriptor.name}" requires format, meta.width, and meta.height.`+ `${descriptor.type === "image" ? "Image" : "Video"} asset "${+ descriptor.name+ }" requires format, meta.width, and meta.height.`);}return {@@ -1238,6 +1278,10 @@ export const loadProjectBundleByBuildId = async (bundleVersion: currentBundleVersion,contentIndex: params.contentIndex,});+ const missingJsonPropValues = getMissingJsonPropValueDiagnostics(data);+ if (missingJsonPropValues !== undefined) {+ throw new MissingJsonPropValueError(missingJsonPropValues);+ }return publishedProjectBundle.parse(data);};@@ -1323,7 +1367,9 @@ const parseRestorePointPatchTransactions = (transactions: unknown) => {const result = restorePointPatchTransaction.array().safeParse(transactions);if (result.success === false) {throw new Error(- `Invalid restore point transaction: ${formatSchemaIssues(result.error.issues)}`+ `Invalid restore point transaction: ${formatSchemaIssues(+ result.error.issues+ )}`);}return result.data;@@ -2407,7 +2453,9 @@ const uploadProjectBundleData = async (const data = JSON.stringify(portableData);if (new TextEncoder().encode(data).byteLength > maxProjectBundleSize) {throw new Error(- `Project bundle is too large to import. Maximum size is ${formatMebibytes(maxProjectBundleSize)}.`+ `Project bundle is too large to import. Maximum size is ${formatMebibytes(+ maxProjectBundleSize+ )}.`);}const file =