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: Support JSON content files in Builder (#6168)

Oleg Isonen5ec3547d361c
diff --git a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.ts b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.ts
index 886a2b64c5..bad6cc92db 100644
--- a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.ts
+++ b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.ts
@@ -1,6 +1,17 @@
import { expect, test } from "vitest";
import type { Asset } from "@webstudio-is/sdk";
-import { getTextFileNameError } from "./create-text-file-dialog";
+import {
+ createTextFileData,
+ getTextFileNameError,
+} from "./create-text-file-dialog";
+
+const readFile = (file: File) =>
+ new Promise<string>((resolve, reject) => {
+ const reader = new FileReader();
+ reader.addEventListener("load", () => resolve(String(reader.result)));
+ reader.addEventListener("error", reject);
+ reader.readAsText(file);
+ });
const existing: Asset = {
id: "existing",
@@ -77,3 +88,22 @@ test("can restrict creation to the requested text format", () => {
})
).toBe("Use a supported editable text extension.");
});
+
+test("creates valid initial content for editable file types", async () => {
+ const jsonFile = createTextFileData("data.json");
+ if (jsonFile === undefined) {
+ throw new Error("Expected JSON file data");
+ }
+ expect(jsonFile.name).toBe("data.json");
+ expect(jsonFile.type).toBe("application/json");
+ await expect(readFile(jsonFile)).resolves.toBe("{}\n");
+
+ const markdownFile = createTextFileData("post.md");
+ if (markdownFile === undefined) {
+ throw new Error("Expected Markdown file data");
+ }
+ expect(markdownFile.type).toBe("text/markdown");
+ await expect(readFile(markdownFile)).resolves.toBe("");
+
+ expect(createTextFileData("image.png")).toBeUndefined();
+});
diff --git a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsx b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsx
index 61839cd890..7b99be8b66 100644
--- a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsx
+++ b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsx
@@ -51,6 +51,16 @@ export const getTextFileNameError = ({
}
};
+export const createTextFileData = (name: string): File | undefined => {
+ const format = getFileExtension(name)?.toLowerCase() ?? "";
+ if (isTextFileAsset({ format }) === false) {
+ return;
+ }
+ return new File([format === "json" ? "{}\n" : ""], name, {
+ type: getMimeTypeByExtension(format),
+ });
+};
+
const createTextFile = async ({
name,
folderId,
@@ -58,13 +68,10 @@ const createTextFile = async ({
name: string;
folderId?: string;
}): Promise<Asset | undefined> => {
- const format = getFileExtension(name)?.toLowerCase() ?? "";
- if (isTextFileAsset({ format }) === false) {
+ const file = createTextFileData(name);
+ if (file === undefined) {
return;
}
- const file = new File([""], name, {
- type: getMimeTypeByExtension(format),
- });
return uploadSingleAsset("file", file, { folderId });
};
diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx b/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx
index 38b858e378..df7698809b 100644
--- a/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx
+++ b/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx
@@ -63,6 +63,7 @@ import {
getTextFileEditorExtensions,
isMarkdownPreviewAsset,
isMarkdownSyntaxAsset,
+ normalizeTextFileContent,
} from "./text-file-utils";
import { MarkdownSplitView } from "./markdown-preview";
@@ -486,7 +487,21 @@ export const TextFileEditor = ({
if (canEdit === false) {
return;
}
- requestedContentRef.current = content;
+ const currentAsset = currentAssetRef.current;
+ if (currentAsset === undefined) {
+ toast.error("Unable to save: asset not found");
+ return;
+ }
+ const normalized = normalizeTextFileContent(currentAsset, content);
+ if ("error" in normalized) {
+ toast.error(normalized.error);
+ return;
+ }
+ const normalizedContent = normalized.content;
+ if (normalizedContent !== content) {
+ setState({ status: "loaded", content: normalizedContent });
+ }
+ requestedContentRef.current = normalizedContent;
saveQueueRef.current = saveQueueRef.current.then(async () => {
const requestedContent = requestedContentRef.current;
if (
@@ -496,15 +511,15 @@ export const TextFileEditor = ({
return;
}
- const currentAsset = currentAssetRef.current;
- if (currentAsset === undefined) {
+ const assetToUpdate = currentAssetRef.current;
+ if (assetToUpdate === undefined) {
toast.error("Unable to save: asset not found");
return;
}
try {
const updatedAsset = await updateAssetContent({
- asset: currentAsset,
+ asset: assetToUpdate,
content: requestedContent,
});
currentAssetRef.current = updatedAsset;
diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts b/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts
index b8cd005fda..7a4ed05c40 100644
--- a/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts
+++ b/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts
@@ -8,6 +8,8 @@ import {
getTextFileEditorExtensions,
isMarkdownPreviewAsset,
isMarkdownSyntaxAsset,
+ normalizeTextFileContent,
+ normalizeTextFileConversion,
} from "./text-file-utils";
describe("text file assets", () => {
@@ -52,4 +54,49 @@ describe("text file assets", () => {
expect(isMarkdownPreviewAsset({ format: "MD" })).toBe(true);
expect(isMarkdownPreviewAsset({ format: "mdx" })).toBe(false);
});
+
+ test("normalizes JSON-compatible object expressions to strict JSON", () => {
+ expect(
+ normalizeTextFileContent(
+ { format: "json" },
+ "{ title: 'Post', tags: ['one', 'two'], }"
+ )
+ ).toEqual({
+ content:
+ '{\n "title": "Post",\n "tags": [\n "one",\n "two"\n ]\n}\n',
+ });
+ });
+
+ test("rejects executable content and accepts every JSON root type", () => {
+ expect(
+ normalizeTextFileContent({ format: "json" }, "{ value: fetch('/') }")
+ ).toEqual({ error: "Enter a JSON-compatible value." });
+ expect(normalizeTextFileContent({ format: "json" }, "[1, 'two']")).toEqual({
+ content: '[\n 1,\n "two"\n]\n',
+ });
+ expect(normalizeTextFileContent({ format: "json" }, "null")).toEqual({
+ content: "null\n",
+ });
+ });
+
+ test("preserves non-JSON text content", () => {
+ expect(normalizeTextFileContent({ format: "md" }, "anything")).toEqual({
+ content: "anything",
+ });
+ });
+
+ test("rejects incomplete object syntax", () => {
+ expect(normalizeTextFileContent({ format: "json" }, "{ title:")).toEqual({
+ error: "Enter a JSON-compatible value.",
+ });
+ });
+
+ test("initializes empty content when converting a text file to JSON", () => {
+ expect(normalizeTextFileConversion({ format: "json" }, " \n")).toEqual({
+ content: "{}\n",
+ });
+ expect(normalizeTextFileConversion({ format: "json" }, "not json")).toEqual(
+ { error: "Enter a JSON-compatible value." }
+ );
+ });
});
diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts b/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts
index b183b5a1a5..faf2c71494 100644
--- a/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts
+++ b/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts
@@ -3,6 +3,7 @@ import { css } from "@codemirror/lang-css";
import { html } from "@codemirror/lang-html";
import { javascript } from "@codemirror/lang-javascript";
import { markdown } from "@codemirror/lang-markdown";
+import { parseJsonExpression } from "@webstudio-is/expression";
import {
getAssetTextEditorLanguage,
type Asset,
@@ -34,3 +35,29 @@ export const isMarkdownSyntaxAsset = (asset: Pick<Asset, "format">) =>
export const isMarkdownPreviewAsset = (asset: Pick<Asset, "format">) =>
asset.format.toLowerCase() === "md";
+
+export const normalizeTextFileContent = (
+ asset: Pick<Asset, "format">,
+ content: string
+): { content: string } | { error: string } => {
+ if (getAssetTextEditorLanguage(asset) !== "json") {
+ return { content };
+ }
+
+ const value = parseJsonExpression(content);
+ if (value === undefined) {
+ return { error: "Enter a JSON-compatible value." };
+ }
+
+ return { content: `${JSON.stringify(value, undefined, 2)}\n` };
+};
+
+export const normalizeTextFileConversion = (
+ asset: Pick<Asset, "format">,
+ content: string
+) => {
+ if (getAssetTextEditorLanguage(asset) === "json" && content.trim() === "") {
+ return { content: "{}\n" };
+ }
+ return normalizeTextFileContent(asset, content);
+};
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx
index 51b4978468..81d5de44a2 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx
@@ -97,6 +97,23 @@ test("uses an auto-growing textarea for the asset description", () => {
).toEqual(["Name", "Folder", "Description", "ID"]);
});
+test("lets users edit the complete asset filename", () => {
+ renderer.render(
+ <TooltipProvider>
+ <AssetSettings open onOpenChange={vi.fn()} asset={createImageAsset()}>
+ <button>Anchor</button>
+ </AssetSettings>
+ </TooltipProvider>
+ );
+
+ expect(
+ document.querySelector<HTMLInputElement>("#asset-manager-filename")?.value
+ ).toBe("image.png");
+ expect(
+ document.querySelector("#asset-manager-filename-extension")
+ ).toBeNull();
+});
+
test("closes asset settings before replacing an asset", () => {
const onOpenChange = vi.fn();
const onReplace = vi.fn();
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx b/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx
index a6eeddc49e..182b4b939a 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx
@@ -4,7 +4,12 @@ import { useDebouncedCallback } from "use-debounce";
import prettyBytes from "pretty-bytes";
import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
-import { getAssetUrl, getMimeTypeByExtension } from "@webstudio-is/sdk";
+import {
+ getAssetUrl,
+ getFileNameParts,
+ getMimeTypeByExtension,
+ isTextFileAsset,
+} from "@webstudio-is/sdk";
import type { Asset, Instance } from "@webstudio-is/sdk";
import {
Box,
@@ -29,6 +34,7 @@ import {
TextArea,
textVariants,
theme,
+ toast,
Tooltip,
} from "@webstudio-is/design-system";
import {
@@ -57,7 +63,8 @@ import { selectPage } from "~/shared/nano-states";
import { findPageAndSelectorByInstanceId } from "@webstudio-is/project-build/runtime";
import { $selectedPageId } from "~/shared/nano-states";
import { executeRuntimeMutation } from "~/shared/instance-utils/data";
-import { deleteAssets } from "~/builder/shared/assets";
+import { deleteAssets, updateAssetContent } from "~/builder/shared/assets";
+import { normalizeTextFileConversion } from "~/builder/features/text-file-editor/text-file-utils";
import {
$activeInspectorPanel,
setActiveSidebarPanel,
@@ -313,33 +320,83 @@ const AssetSettingsContent = ({
}) => {
const { canDownloadAssets } = useStore($permissions);
const { size, meta, id } = asset;
- const { basename, ext } = getAssetDisplayNameParts(asset);
+ const { ext } = getAssetDisplayNameParts(asset);
const [filenameError, setFilenameError] = useState<string>();
- const [filename, setFilename] = useLocalValue(basename, (newFilename) => {
+ const saveFilename = async (newFilename: string) => {
const assetId = asset.id;
- // validate filename
if (!isValidFilename(newFilename)) {
setFilenameError("Invalid filename");
return;
}
- // validate duplicates
- for (const asset of $assets.get().values()) {
- if (asset.id !== assetId) {
- const { basename: filename } = getAssetDisplayNameParts(asset);
- if (newFilename === filename) {
- setFilenameError("Filename already used");
+
+ const currentAsset = $assets.get().get(assetId) ?? asset;
+ const currentExtension = getAssetDisplayNameParts(currentAsset).ext;
+ const { basename, extension } = getFileNameParts(newFilename);
+ if (extension === "" && currentExtension !== "") {
+ setFilenameError("File extension is required");
+ return;
+ }
+
+ for (const candidate of $assets.get().values()) {
+ if (
+ candidate.id !== assetId &&
+ formatAssetName(candidate) === newFilename
+ ) {
+ setFilenameError("Filename already used");
+ return;
+ }
+ }
+
+ if (extension.toLowerCase() !== currentExtension.toLowerCase()) {
+ if (
+ !isTextFileAsset(currentAsset) ||
+ !isTextFileAsset({ format: extension })
+ ) {
+ setFilenameError("Only text file extensions can be changed");
+ return;
+ }
+
+ try {
+ const response = await fetch(
+ getAssetUrl(currentAsset, window.location.origin)
+ );
+ if (response.ok === false) {
+ throw new Error(`Unable to load asset: ${response.status}`);
+ }
+ const normalized = normalizeTextFileConversion(
+ { format: extension },
+ await response.text()
+ );
+ if ("error" in normalized) {
+ setFilenameError(normalized.error);
return;
}
+ await updateAssetContent({
+ asset: currentAsset,
+ content: normalized.content,
+ extension,
+ });
+ } catch (error) {
+ const message =
+ error instanceof Error ? error.message : "Unable to rename file";
+ setFilenameError(message);
+ toast.error(message);
+ return;
}
}
+
executeRuntimeMutation({
id: "assets.update",
input: {
assetId,
- values: { filename: newFilename },
+ values: { filename: basename },
},
});
- });
+ };
+ const [filename, setFilename] = useLocalValue(
+ formatAssetName(asset),
+ (newFilename) => void saveFilename(newFilename)
+ );
const [description, setDescription] = useLocalValue(
asset.description ?? "",
(newDescription) => {
@@ -451,24 +508,10 @@ const AssetSettingsContent = ({
>
<InputField
id="asset-manager-filename"
- aria-describedby={
- ext === "" ? undefined : "asset-manager-filename-extension"
- }
autoFocus={focusName}
readOnly={authPermit === "view"}
color={filenameError ? "error" : undefined}
value={filename}
- suffix={
- ext === "" ? undefined : (
- <Text
- id="asset-manager-filename-extension"
- color="subtle"
- variant="labels"
- >
- .{ext}
- </Text>
- )
- }
onChange={(event) => {
setFilename(event.target.value);
setFilenameError(undefined);
diff --git a/apps/builder/app/builder/shared/assets/update-asset-content.test.ts b/apps/builder/app/builder/shared/assets/update-asset-content.test.ts
index 8be626de7a..2f545f773a 100644
--- a/apps/builder/app/builder/shared/assets/update-asset-content.test.ts
+++ b/apps/builder/app/builder/shared/assets/update-asset-content.test.ts
@@ -44,7 +44,7 @@ test("commits a content revision without changing the asset id", async () => {
requestContentUpdate.mockResolvedValue({ asset: revision });
await expect(
- updateAssetContent({ asset, content: '{"a":1}' })
+ updateAssetContent({ asset, content: '{"a":1}', extension: "json" })
).resolves.toEqual(revision);
expect(requestContentUpdate).toHaveBeenCalledWith(
@@ -52,6 +52,7 @@ test("commits a content revision without changing the asset id", async () => {
assetId: "asset",
projectId: "project",
expectedName: "settings_old.json",
+ extension: "json",
authToken: "token",
requestOrigin: window.location.origin,
})
diff --git a/apps/builder/app/builder/shared/assets/update-asset-content.ts b/apps/builder/app/builder/shared/assets/update-asset-content.ts
index a753e69b98..b1d9b6cec2 100644
--- a/apps/builder/app/builder/shared/assets/update-asset-content.ts
+++ b/apps/builder/app/builder/shared/assets/update-asset-content.ts
@@ -18,9 +18,11 @@ export const createUpdateAssetContent =
async ({
asset,
content,
+ extension,
}: {
asset: Asset;
content: string;
+ extension?: string;
}): Promise<Asset> => {
const projectId = $project.get()?.id;
if (projectId === undefined) {
@@ -32,6 +34,7 @@ export const createUpdateAssetContent =
assetId: asset.id,
projectId,
expectedName: asset.name,
+ extension,
origin,
authToken: $authToken.get(),
readAssetData: async () => content,
diff --git a/apps/builder/app/builder/shared/assets/upload-assets.test.ts b/apps/builder/app/builder/shared/assets/upload-assets.test.ts
index e969424aab..e604f16ea2 100644
--- a/apps/builder/app/builder/shared/assets/upload-assets.test.ts
+++ b/apps/builder/app/builder/shared/assets/upload-assets.test.ts
@@ -130,6 +130,24 @@ describe("upload-assets", () => {
expect(onError).toHaveBeenCalledWith("network down");
});
+ test("marks URL uploads separately from JSON file uploads", async () => {
+ request.mockResolvedValue(
+ Response.json({ uploadedAssets: [{ id: "asset" }] })
+ );
+
+ await submitAssetUpload({
+ authToken: undefined,
+ uploadName: "upload-name",
+ fileOrUrl: new URL("https://example.com/image.png"),
+ onCompleted: vi.fn(),
+ onError: vi.fn(),
+ request,
+ });
+
+ const [, init] = request.mock.calls[0] as [string, { headers: Headers }];
+ expect(init.headers.get("x-webstudio-asset-source")).toBe("url");
+ });
+
test("keeps the selected folder throughout upload preparation", async () => {
const [fileData] = await getFilesData(
"image",
diff --git a/apps/builder/app/builder/shared/assets/upload-assets.tsx b/apps/builder/app/builder/shared/assets/upload-assets.tsx
index 4b748204fa..c1f04c4e4a 100644
--- a/apps/builder/app/builder/shared/assets/upload-assets.tsx
+++ b/apps/builder/app/builder/shared/assets/upload-assets.tsx
@@ -255,6 +255,7 @@ const submitAssetUpload = async ({
if (fileOrUrl instanceof URL) {
headers.set("Content-Type", "application/json");
+ headers.set("x-webstudio-asset-source", "url");
}
let width = undefined;
diff --git a/apps/builder/app/routes/rest.assets.$assetId.content.tsx b/apps/builder/app/routes/rest.assets.$assetId.content.tsx
index 72d141923b..5e56356460 100644
--- a/apps/builder/app/routes/rest.assets.$assetId.content.tsx
+++ b/apps/builder/app/routes/rest.assets.$assetId.content.tsx
@@ -34,12 +34,18 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
const expectedName = parseAssetRestFilename(
url.searchParams.get("expectedName")
);
+ const extensionValue = url.searchParams.get("extension");
+ const extension =
+ extensionValue === null
+ ? undefined
+ : parseAssetRestFilename(extensionValue);
const asset = await (
await createAssetRestRepository(request, "edit")
).updateContent({
assetId,
expectedName,
+ extension,
data: requireAssetRestBody(request),
});
return json(
diff --git a/apps/builder/app/services/asset-upload.server.test.ts b/apps/builder/app/services/asset-upload.server.test.ts
index 162c4b7e5a..44988375ea 100644
--- a/apps/builder/app/services/asset-upload.server.test.ts
+++ b/apps/builder/app/services/asset-upload.server.test.ts
@@ -39,6 +39,22 @@ test("keeps browser JSON file uploads as JSON file content", async () => {
).resolves.toBe(JSON.stringify({ value: 1 }));
});
+test("keeps JSON files with a root URL field as file content", async () => {
+ const content = JSON.stringify({ url: "https://example.com/page" });
+ const request = new Request(
+ "https://webstudio.is/rest/assets/uploads/data.json",
+ {
+ method: "POST",
+ body: content,
+ headers: { "Content-Type": "application/json" },
+ }
+ );
+
+ await expect(
+ new Response(await getBrowserUploadBody(request, "application/json")).text()
+ ).resolves.toBe(content);
+});
+
test("keeps browser URL image uploads by fetching the remote image body", async () => {
const fetch = vi.fn(async () => new Response("remote image"));
vi.stubGlobal("fetch", fetch);
@@ -47,7 +63,10 @@ test("keeps browser URL image uploads by fetching the remote image body", async
{
method: "POST",
body: JSON.stringify({ url: "https://example.com/image.png" }),
- headers: { "Content-Type": "application/json" },
+ headers: {
+ "Content-Type": "application/json",
+ "x-webstudio-asset-source": "url",
+ },
}
);
@@ -70,7 +89,10 @@ test("reports browser URL image fetch failures", async () => {
{
method: "POST",
body: JSON.stringify({ url: "https://example.com/image.png" }),
- headers: { "Content-Type": "application/json" },
+ headers: {
+ "Content-Type": "application/json",
+ "x-webstudio-asset-source": "url",
+ },
}
);
diff --git a/apps/builder/app/services/asset-upload.server.ts b/apps/builder/app/services/asset-upload.server.ts
index 6301d6118e..40a8ebe09f 100644
--- a/apps/builder/app/services/asset-upload.server.ts
+++ b/apps/builder/app/services/asset-upload.server.ts
@@ -9,44 +9,42 @@ export const getBrowserUploadBody = async (
request: Request,
contentType: string | null
) => {
- let body = request.body;
+ const body = request.body;
if (body === null) {
throw new Error("Asset body is empty");
}
- if (contentType?.includes("application/json")) {
- const jsonBody = await request.json();
- const urlParse = urlBody.safeParse(jsonBody);
-
- if (urlParse.success) {
- const { url } = urlParse.data;
- const imageRequest = await fetch(url, {
- method: "GET",
- headers: {
- Accept: RESIZABLE_IMAGE_MIME_TYPES.join(","),
- },
- });
-
- if (imageRequest.ok === false) {
- const error = await imageRequest.text();
- throw new Error(
- `An error occurred while fetching the image at ${url}: ${error.slice(0, 500)}`
- );
- }
+ if (request.headers.get("x-webstudio-asset-source") !== "url") {
+ return body;
+ }
+ if (contentType?.includes("application/json") !== true) {
+ throw new Error("Invalid URL asset upload content type");
+ }
- if (imageRequest.body === null) {
- throw new Error(
- `An error occurred while fetching the image at ${url}: Image body is null`
- );
- }
+ const urlParse = urlBody.safeParse(await request.json());
+ if (urlParse.success === false) {
+ throw new Error("Invalid URL asset upload body");
+ }
- body = imageRequest.body;
- } else {
- body = new Blob([JSON.stringify(jsonBody)], {
- type: "application/json",
- }).stream();
- }
+ const { url } = urlParse.data;
+ const imageRequest = await fetch(url, {
+ method: "GET",
+ headers: {
+ Accept: RESIZABLE_IMAGE_MIME_TYPES.join(","),
+ },
+ });
+
+ if (imageRequest.ok === false) {
+ const error = await imageRequest.text();
+ throw new Error(
+ `An error occurred while fetching the image at ${url}: ${error.slice(0, 500)}`
+ );
}
- return body;
+ if (imageRequest.body === null) {
+ throw new Error(
+ `An error occurred while fetching the image at ${url}: Image body is null`
+ );
+ }
+ return imageRequest.body;
};
diff --git a/docs/university/foundations/assets.md b/docs/university/foundations/assets.md
index 834786668e..cdbebc1693 100644
--- a/docs/university/foundations/assets.md
+++ b/docs/university/foundations/assets.md
@@ -41,9 +41,10 @@ multiple selected assets does not insert multiple Image components.
Open the add menu in the Assets panel and choose **Create text file**. Enter a
supported filename, such as `notes.md`, `article.mdx`, or `data.json`.
-Webstudio creates the blank file in the current folder and opens it in the code
-editor. You can also choose **Create MDX file** from a Content Block's
-**Content source** control.
+Webstudio creates the file in the current folder and opens it in the code
+editor. New JSON files start with an empty object so the Content Engine can
+index them immediately. You can also choose **Create MDX file** from a Content
+Block's **Content source** control.
You can open uploaded `txt`, `csv`, `md`, `mdx`, `js`, `css`, `json`, `html`,
`xml`, and `svg` assets in the same editor. Syntax highlighting follows the
@@ -52,8 +53,14 @@ formatting controls. The file editor previews `.md`; connect `.mdx` to a Content
Block to see its materialized result on the canvas.
Edits save when the editor loses focus or when you press `Command + S` on
-macOS, `Ctrl + S` on Windows, or `Command/Ctrl + Enter`. The file extension is
-fixed, but you can rename its basename in Asset settings.
+macOS, `Ctrl + S` on Windows, or `Command/Ctrl + Enter`. Edit the complete
+filename in Asset settings to rename a text file or change its format. When you
+change the extension to `.json`, Webstudio validates the existing content and
+converts JSON-compatible syntax to strict JSON before saving the new
+file revision. JSON files can contain any JSON value, including arrays and
+scalars. The editor accepts unquoted object keys, single-quoted strings, and
+trailing commas. It reports unsupported syntax instead of saving the file.
+Converting an empty text file to `.json` initializes it with an empty object.
### Use assets as content
diff --git a/docs/university/foundations/content-engine.md b/docs/university/foundations/content-engine.md
index ebcf83df35..4cace36924 100644
--- a/docs/university/foundations/content-engine.md
+++ b/docs/university/foundations/content-engine.md
@@ -165,8 +165,9 @@ asset ID or generated filename. This is what makes the content portable.
### JSON files
-The Content Engine can query JSON files as well as Markdown. A JSON file must
-contain an object at its root:
+The Content Engine can query JSON files as well as Markdown. JSON files can
+contain objects, arrays, or scalar values. A root object exposes its fields for
+structured queries:
```json
{
@@ -176,9 +177,16 @@ contain an object at its root:
}
```
-Its fields are also exposed under `properties`, such as `properties.name` and
-`properties.avatar`. Use JSON when the file contains structured data without a
-Markdown body.
+The object's fields are exposed under `properties`, such as `properties.name`
+and `properties.avatar`. Root arrays and scalars remain valid JSON content but
+do not expose top-level `properties` fields. Use JSON when the file contains
+structured data without a Markdown body. Name the file with a `.json` extension
+in the **Create text file** dialog. A new file starts with an empty object, which
+you can replace with any JSON value. The editor accepts JSON-compatible syntax
+and formats it as strict JSON when saving. Unsupported or incomplete syntax is
+reported without saving the file. You can also change an existing text file's
+extension to `.json` by editing its complete filename in Asset settings;
+Webstudio validates and formats the current content before converting it.
## 3. Query the articles for the overview
diff --git a/packages/asset-uploader/src/asset-repository.ts b/packages/asset-uploader/src/asset-repository.ts
index ca9bd98140..97a644adb9 100644
--- a/packages/asset-uploader/src/asset-repository.ts
+++ b/packages/asset-uploader/src/asset-repository.ts
@@ -254,6 +254,7 @@ export interface AssetRepository {
updateContent(input: {
assetId: Asset["id"];
expectedName: string;
+ extension?: string;
data: ReadableStream<Uint8Array>;
}): Promise<Asset>;
updateMetadata(
@@ -518,6 +519,7 @@ export class PostgresAssetRepository implements AssetRepository {
async updateContent({
assetId,
expectedName,
+ extension,
data,
}: Parameters<AssetRepository["updateContent"]>[0]) {
await this.assertCanEdit();
@@ -526,6 +528,7 @@ export class PostgresAssetRepository implements AssetRepository {
assetId,
projectId: this.projectId,
expectedName,
+ extension,
data,
},
this.getWritableStore(),
diff --git a/packages/asset-uploader/src/revision.test.ts b/packages/asset-uploader/src/revision.test.ts
index 72c8d508be..3e4fe73212 100644
--- a/packages/asset-uploader/src/revision.test.ts
+++ b/packages/asset-uploader/src/revision.test.ts
@@ -82,6 +82,13 @@ describe("asset content revisions", () => {
filename: null,
})
).toBe("test.md");
+ expect(
+ getRevisionFilename({
+ name: "settings_old-revision.md",
+ filename: "configuration",
+ extension: "json",
+ })
+ ).toBe("configuration.json");
});
test("uploads an immutable revision and keeps the asset id", async () => {
diff --git a/packages/asset-uploader/src/revision.ts b/packages/asset-uploader/src/revision.ts
index 6e45b58c6c..6074d718ac 100644
--- a/packages/asset-uploader/src/revision.ts
+++ b/packages/asset-uploader/src/revision.ts
@@ -1,5 +1,6 @@
import {
formatAssetName,
+ getFileNameParts,
isTextFileAsset,
type Asset,
} from "@webstudio-is/sdk";
@@ -21,11 +22,18 @@ import { AssetRevisionConflictError } from "./content-repository";
const getRevisionFilename = ({
name,
filename,
+ extension,
}: {
name: string;
filename: string | null;
+ extension?: string;
}) => {
- return sanitizeS3Key(formatAssetName({ name, filename }));
+ const displayName = formatAssetName({ name, filename });
+ if (extension === undefined) {
+ return sanitizeS3Key(displayName);
+ }
+ const { basename } = getFileNameParts(displayName);
+ return sanitizeS3Key(`${basename}.${extension}`);
};
export const swapAssetFileWithClient = async (
@@ -96,11 +104,13 @@ export const updateAssetContent = async (
assetId,
projectId,
expectedName,
+ extension,
data,
}: {
assetId: Asset["id"];
projectId: string;
expectedName: string;
+ extension?: string;
data: ReadableStream<Uint8Array>;
},
assetClient: AssetObjectStore,
@@ -129,11 +139,18 @@ export const updateAssetContent = async (
if (isTextFileAsset({ format: currentAsset.file.format }) === false) {
throw new Error("This asset is not an editable text file");
}
+ if (
+ extension !== undefined &&
+ isTextFileAsset({ format: extension }) === false
+ ) {
+ throw new Error("The new extension must be an editable text file format");
+ }
const revisionName = createUniqueAssetFilename(
getRevisionFilename({
name: currentAsset.name,
filename: currentAsset.filename,
+ extension: extension?.toLowerCase(),
})
);
const insertedFile = await context.postgrest.client.from("File").insert({
diff --git a/packages/cli/evaluations/high-impact/fixture-api.test.ts b/packages/cli/evaluations/high-impact/fixture-api.test.ts
index b7abdc0b2f..2a3da44639 100644
--- a/packages/cli/evaluations/high-impact/fixture-api.test.ts
+++ b/packages/cli/evaluations/high-impact/fixture-api.test.ts
@@ -145,7 +145,7 @@ describe("high-impact fixture API", () => {
await fixtureApi.close();
await rm(directory, { recursive: true, force: true });
}
- }, 60_000);
+ }, 120_000);
test("creates a folder and uploads the Markdown blog files through the local CLI", async () => {
const fixtureApi = await startHighImpactFixtureApi(markdownBlogFixture);
diff --git a/packages/cli/src/asset-files.test.ts b/packages/cli/src/asset-files.test.ts
index 01f96a1790..ba17b2defa 100644
--- a/packages/cli/src/asset-files.test.ts
+++ b/packages/cli/src/asset-files.test.ts
@@ -68,6 +68,7 @@ test("creates asset content readers from inline content or a file", async () =>
const fromContent = createLocalUpdateAssetContentInput({
assetId: "asset",
expectedName: "content_old.json",
+ extension: "json",
content: '{"source":"inline"}',
readFile,
});
@@ -81,6 +82,7 @@ test("creates asset content readers from inline content or a file", async () =>
await expect(fromContent.readAssetData()).resolves.toBe(
'{"source":"inline"}'
);
+ expect(fromContent.extension).toBe("json");
await expect(fromPath.readAssetData()).resolves.toEqual(
Buffer.from('{"source":"file"}')
);
diff --git a/packages/cli/src/asset-files.ts b/packages/cli/src/asset-files.ts
index af1def5e94..d1538c6132 100644
--- a/packages/cli/src/asset-files.ts
+++ b/packages/cli/src/asset-files.ts
@@ -96,12 +96,14 @@ export const createLocalUploadAssetsInput = <Asset extends { name: string }>({
export const createLocalUpdateAssetContentInput = ({
assetId,
expectedName,
+ extension,
path,
content,
readFile,
}: {
assetId: string;
expectedName: string;
+ extension?: string;
path?: string;
content?: string;
readFile: (path: string) => Promise<unknown>;
@@ -114,6 +116,7 @@ export const createLocalUpdateAssetContentInput = ({
return {
assetId,
expectedName,
+ extension,
readAssetData: async () =>
path === undefined ? content : await readFile(resolve(path)),
};
diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.ts
index 468191c833..63a4d31c6b 100644
--- a/packages/cli/src/commands/mcp.test.ts
+++ b/packages/cli/src/commands/mcp.test.ts
@@ -1126,16 +1126,19 @@ test("adapts MCP asset content input to the shared revision client", async () =>
const input = getMcpOperationInput("update-asset-content", {
assetId: "asset-id",
expectedName: "settings_hash.json",
+ extension: "json",
content: '{"theme":"dark"}',
}) as {
assetId: string;
expectedName: string;
+ extension?: string;
readAssetData: () => Promise<unknown>;
};
expect(input).toMatchObject({
assetId: "asset-id",
expectedName: "settings_hash.json",
+ extension: "json",
});
await expect(input.readAssetData()).resolves.toBe('{"theme":"dark"}');
});
@@ -1152,6 +1155,7 @@ test("exposes asset content editing through MCP discovery", () => {
properties: {
assetId: expect.any(Object),
expectedName: expect.any(Object),
+ extension: expect.any(Object),
path: expect.any(Object),
content: expect.any(Object),
},
diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.ts
index 3ac89d6b88..04f408c594 100644
--- a/packages/cli/src/commands/mcp.ts
+++ b/packages/cli/src/commands/mcp.ts
@@ -211,6 +211,8 @@ const getMcpUpdateAssetContentInput = (input: unknown) => {
return createLocalUpdateAssetContentInput({
assetId: input.assetId,
expectedName: input.expectedName,
+ extension:
+ typeof input.extension === "string" ? input.extension : undefined,
path: typeof input.path === "string" ? input.path : undefined,
content: typeof input.content === "string" ? input.content : undefined,
readFile,
diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.ts
index 15fd65fdbb..4a801d174f 100644
--- a/packages/http-client/src/index.test.ts
+++ b/packages/http-client/src/index.test.ts
@@ -1538,6 +1538,7 @@ test("updates asset content through the stable asset revision endpoint", async (
...apiParams,
assetId: "asset/id",
expectedName: "old_hash.json",
+ extension: "json",
readAssetData: async () => '{"theme":"dark"}',
request,
})
@@ -1547,6 +1548,7 @@ test("updates asset content through the stable asset revision endpoint", async (
expect(url.pathname).toBe("/rest/assets/asset%2Fid/content");
expect(url.searchParams.get("projectId")).toBe(apiParams.projectId);
expect(url.searchParams.get("expectedName")).toBe("old_hash.json");
+ expect(url.searchParams.get("extension")).toBe("json");
expect(init).toMatchObject({ method: "PUT", body: '{"theme":"dark"}' });
expect(new Headers(init.headers).get("x-auth-token")).toBe(
apiParams.authToken
diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.ts
index 2ef52e8e72..7691dd2636 100644
--- a/packages/http-client/src/index.ts
+++ b/packages/http-client/src/index.ts
@@ -752,6 +752,7 @@ export const updateProjectAssetContent = async (
authToken?: string;
assetId: string;
expectedName: string;
+ extension?: string;
readAssetData: () => Promise<AssetContentData>;
request?: typeof fetch;
requestOrigin?: string;
@@ -764,6 +765,9 @@ export const updateProjectAssetContent = async (
path: getAssetContentApiUrl(params.assetId),
});
url.searchParams.set("expectedName", params.expectedName);
+ if (params.extension !== undefined) {
+ url.searchParams.set("extension", params.extension);
+ }
try {
return await requestAssetRestJson(request, url, {
method: "PUT",
diff --git a/packages/protocol/src/asset-resource-api.ts b/packages/protocol/src/asset-resource-api.ts
index 4b34466eef..e05324def1 100644
--- a/packages/protocol/src/asset-resource-api.ts
+++ b/packages/protocol/src/asset-resource-api.ts
@@ -1158,6 +1158,12 @@ export const createAssetResourceOpenApi = ({
true,
assetResourceLimits.assetFilenameCharacters
),
+ queryParameter(
+ "extension",
+ "Optional editable text format for the replacement revision",
+ false,
+ assetResourceLimits.assetFilenameCharacters
+ ),
],
requestBody: {
required: true,
diff --git a/packages/protocol/src/builder-api/local-operation-inputs.ts b/packages/protocol/src/builder-api/local-operation-inputs.ts
index f77c9aa362..9728f3abda 100644
--- a/packages/protocol/src/builder-api/local-operation-inputs.ts
+++ b/packages/protocol/src/builder-api/local-operation-inputs.ts
@@ -26,6 +26,7 @@ const localUploadAssetsInput = z.object({
const localUpdateAssetContentInput = z.object({
assetId: z.string().min(1),
expectedName: z.string().min(1),
+ extension: z.string().min(1).optional(),
path: z.string().min(1).optional(),
content: z.string().optional(),
});
diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.ts
index e070134a13..6744aaeb44 100644
--- a/packages/protocol/src/builder-api/operation-docs.ts
+++ b/packages/protocol/src/builder-api/operation-docs.ts
@@ -831,9 +831,10 @@ const curatedPublicApiOperationDocumentation = [
{
command: "update-asset-content",
description:
- "Replace a text asset's content while preserving its stable asset id; provide exactly one of path or content and use the current asset name as expectedName",
+ "Replace a text asset's content or extension while preserving its stable asset id; provide exactly one of path or content and use the current asset name as expectedName",
examples: [
- 'MCP/API: update-asset-content {"assetId":"asset-id","expectedName":"settings_hash.json","content":"{\\"theme\\":\\"dark\\"}"}',
+ `MCP/API: update-asset-content {"assetId":"asset-id","expectedName":"settings_hash.json","content":"{theme:'dark'}"}`,
+ `MCP/API: update-asset-content {"assetId":"asset-id","expectedName":"settings_hash.md","extension":"json","content":"{theme:'dark'}"}`,
'MCP/API: update-asset-content {"assetId":"asset-id","expectedName":"styles_hash.css","path":"./styles.css"}',
],
},