feat: Copy and paste tokens across projects (#6660)

Closes #5727

Copy a design token from its menu and paste it into another project or
the style source input. Paste creates and attaches a new numbered token
(for example, `Button copy 1`). It carries all breakpoint styles,
referenced CSS variables, images, and fonts, and creates missing
breakpoints. MCP offers the same copy and paste commands; `instanceId`
attaches the token when supplied.

The clipboard format is CSS with one `@webstudio/token-css/v1` comment.
The old JSON format is removed. HTML and CSS use the same Webstudio
pragma parser, and token CSS reuses the existing CSS declaration parser.
Builder and MCP share token copy, parsing, paste, fragment asset import,
and asset reference remapping. The latest cleanup also reuses the
existing copy-name helper.

Repeated Builder pastes reuse the existing content-hash asset
deduplication path, including SVG and fonts. The source bytes still
download and hash on each paste. MCP downloads and uploads asset bytes
on each paste, using the upload path's deduplication; both projects must
use the same Webstudio origin for assets.

- [x] Implement CSS token copy and paste in Builder and MCP, including
selection attachment and numbered names.
- [x] Preserve breakpoint styles, variable dependencies, image and font
assets, and missing breakpoints.
- [x] Detect token CSS pasted into the style source input.
- [x] Remove the JSON transfer format and update Builder and MCP
documentation.
- [x] Reuse CSS parsing, asset transfer, naming, and existing upload
deduplication paths.
- [x] Resolve review findings, including shorthand variables and
selector state positions.
- [x] Verify focused tests, typechecks, lint, formatting, package
boundaries, and the approved Storybook visual check.
- [x] Trace existing CSS editor and HTML paste flows; reuse their
parser, declaration mapper, and CSS variable reference collector.
- [x] Preserve breakpoint cascade order when copying equal media
conditions; add a regression and resolve the review thread.
- [x] Share CSS variable traversal between collection and renaming;
preserve nested fallbacks and resolve the review comment.
- [x] Discover and remap image URLs inside raw variable fallbacks; share
the CSS value traversal and resolve the review comment.
- [x] Preserve fallback variables in mixed shorthands and custom
non-pixel breakpoint styles; add regressions and resolve review threads.
- [x] Preserve combined width and custom media conditions in token CSS;
add a regression and resolve the review thread.
- [x] Preserve range-syntax custom breakpoints in token CSS; add a
regression and resolve the review thread.
- [x] Preserve negated custom and width media conditions; add
regressions and resolve the review thread.
- [x] Preserve boolean operators between width conditions; add a
regression and resolve the review thread.
- [x] Monitor required CI checks for the latest commit.
- [x] Reuse the existing asset usage collector for copied token image
and font dependencies; verify token and asset usage tests.
- [x] Review documentation impact of this internal refactor (none; no
user-facing behavior or contract changed).

The reuse audit traced CSS editor, HTML paste, instance/page paste,
asset usage, and MCP from input to state change. Token copy now uses the
existing asset usage collector for image and variable-backed font
dependencies. CSS parsing, declaration mapping, variable traversal,
breakpoint matching, asset import/remapping, copy naming, and
Builder/MCP token mutation also have shared owners. Fragment insertion
may reuse tokens and merge overflow breakpoints; token paste must always
create a numbered copy and report overflow. The regex-based rename path
remains for arbitrary authored text; token transfer uses syntax-aware
rewriting to avoid changing text outside `var()`. The asset collector
refactor changes no user-facing behavior. The follow-up parser fixes
keep fallback variables, non-pixel breakpoint styles, and combined media
conditions, range syntax, negation, and width-condition operators intact
when copied. No documentation or fixture inputs changed. Focused token,
asset usage, HTML, and CSS parser tests, affected typechecks, lint,
formatting, package boundaries, and `git diff --check` passed. Agent
evaluations were offered and declined.
This commit is contained in:
Oleg Isonen authored and GitHub committed 2026-11-09 15:10:49 +01:00
1 parent ee277769ff
commit 1b9ae61fa1
51 files changed
+3825 -267

No files matched your search

@@ -34,6 +34,8 @@ import { executeRuntimeMutation } from "~/shared/instance-utils/data";
import { subscribe } from "~/shared/pubsub";
import { $selectedInstance } from "~/shared/nano-states";
import { $instanceTags } from "./shared/model";
import { copyToken, pasteToken } from "~/shared/copy-paste/copy-paste";
import { builderApi } from "~/shared/builder-api";
// Declare command for this module
declare module "~/shared/pubsub" {
@@ -367,6 +369,14 @@ export const StyleSourcesSection = () => {
setEditingItem(newId);
}
}}
onCopyItem={(id) => {
copyToken(id).catch(() => {
builderApi.toast.error(
"Could not prepare the selected content for copying."
);
});
}}
onPasteToken={pasteToken}
onConvertToToken={(id) => {
convertLocalStyleSourceToToken(id);
setEditingItem(id);
@@ -1,4 +1,5 @@
import { createId } from "@webstudio-is/sdk";
import type { StoryFn } from "@storybook/react";
import { useState } from "react";
import { Flex, StorySection, Text, theme } from "@webstudio-is/design-system";
import {
@@ -6,6 +7,7 @@ import {
type ItemSource,
StyleSourceInput as StyleSourceInputComponent,
} from ".";
import { StyleSourceMenu as StyleSourceMenuComponent } from "./style-source-menu";
const createNanoId = () => createId("nano");
@@ -181,3 +183,21 @@ export const StyleSourceInput = () => {
</StorySection>
);
};
export const TokenMenu: StoryFn<typeof StyleSourceMenuComponent> = () => (
<StyleSourceMenuComponent
open
onOpenChange={() => {}}
selectedItemSelector={undefined}
item={{
id: "button-token",
label: "Button",
source: "token",
disabled: false,
locked: false,
states: [],
}}
hasStyles
states={[]}
/>
);
@@ -0,0 +1,61 @@
import { createRoot } from "react-dom/client";
import { act } from "react-dom/test-utils";
import { expect, test, vi } from "vitest";
import { copyDesignToken } from "@webstudio-is/project-build/runtime";
import { StyleSourceInput } from "./style-source-input";
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
test("pastes copied tokens through the token flow and leaves ordinary text to the input", () => {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
const onPasteToken = vi.fn();
const tokenData = copyDesignToken(
{
assets: new Map(),
breakpoints: new Map(),
styleSources: new Map([
["token", { type: "token", id: "token", name: "Button" }],
]),
styleSourceSelections: new Map(),
styles: new Map(),
},
{ tokenId: "token" }
).data;
try {
act(() =>
root.render(
<StyleSourceInput
inputRef={() => {}}
selectedItemSelector={undefined}
onPasteToken={onPasteToken}
/>
)
);
const input = container.querySelector("input")!;
const paste = (text: string) => {
const clipboardData = new DataTransfer();
clipboardData.setData("text/plain", text);
const event = new ClipboardEvent("paste", {
bubbles: true,
cancelable: true,
clipboardData,
});
act(() => input.dispatchEvent(event));
return event;
};
expect(paste(tokenData).defaultPrevented).toBe(true);
expect(onPasteToken).toHaveBeenCalledExactlyOnceWith(tokenData);
expect(paste("Button").defaultPrevented).toBe(false);
expect(paste('{"other":"value"}').defaultPrevented).toBe(false);
expect(onPasteToken).toHaveBeenCalledTimes(1);
} finally {
act(() => root.unmount());
container.remove();
}
});
@@ -31,6 +31,7 @@ import {
ComboboxScrollArea,
} from "@webstudio-is/design-system";
import type { StyleSource } from "@webstudio-is/sdk";
import { parseWebstudioPragma } from "@webstudio-is/project-build/transfer";
import {
forwardRef,
useState,
@@ -312,6 +313,8 @@ type StyleSourceInputProps<Item extends IntermediateItem> = {
onDeleteItem?: (id: Item["id"]) => void;
onClearStyles?: (id: Item["id"]) => void;
onDuplicateItem?: (id: Item["id"]) => void;
onCopyItem?: (id: Item["id"]) => void;
onPasteToken?: (data: string) => void;
onToggleLockItem?: (id: Item["id"], locked: boolean) => void;
onConvertToToken?: (id: Item["id"]) => void;
onCreateItem?: (label: string) => void;
@@ -439,6 +442,20 @@ export const StyleSourceInput = (
<TextField
// @todo inputProps is any which breaks all types passed to TextField
{...inputProps}
onPaste={(event) => {
const data = event.clipboardData.getData("text/plain");
if (
props.onPasteToken !== undefined &&
parseWebstudioPragma({
source: data,
syntax: "css",
namespace: "token-css",
}).owned
) {
event.preventDefault();
props.onPasteToken(data);
}
}}
inputRef={props.inputRef}
error={props.error}
renderMenu={({ item, hasStyles, open, onOpenChange }) => (
@@ -457,6 +474,7 @@ export const StyleSourceInput = (
}}
onSelect={props.onSelectItem}
onDuplicate={props.onDuplicateItem}
onCopy={props.onCopyItem}
onToggleLock={props.onToggleLockItem}
onConvertToToken={props.onConvertToToken}
onEnable={props.onEnableItem}
@@ -241,6 +241,7 @@ type StyleSourceMenuProps = {
onSelect?: (itemSelector: ItemSelector) => void;
onEdit?: (itemId: IntermediateItem["id"]) => void;
onDuplicate?: (itemId: IntermediateItem["id"]) => void;
onCopy?: (itemId: IntermediateItem["id"]) => void;
onToggleLock?: (itemId: IntermediateItem["id"], locked: boolean) => void;
onConvertToToken?: (itemId: IntermediateItem["id"]) => void;
onDisable?: (itemId: IntermediateItem["id"]) => void;
@@ -340,6 +341,17 @@ export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
Duplicate
</DropdownMenuItem>
)}
{props.item.source === "token" && (
<DropdownMenuItem
onFocus={() => {
setHighlightedSelector(undefined);
setHighlightedAction(undefined);
}}
onSelect={() => props.onCopy?.(props.item.id)}
>
Copy
</DropdownMenuItem>
)}
{props.item.source === "token" && (
<DropdownMenuItem
onFocus={() => {
@@ -2,6 +2,8 @@ import { expect, test, describe } from "vitest";
import type { Asset } from "@webstudio-is/sdk";
import {
getImageNameAndType,
getFileName,
getMimeType,
getSha256Hash,
getFileUploadFingerprint,
isAssetFilenameUsed,
@@ -53,6 +55,20 @@ test("matches full asset filenames only in the requested folder", () => {
).toBe(false);
});
test("keeps the filename and MIME type of a font asset URL", () => {
const url = new URL(
"https://source.example.com/cgi/asset/brand.woff2?format=raw"
);
expect(getFileName(url)).toBe("brand.woff2");
expect(getMimeType(url)).toBe("font/woff2");
});
test("keeps a font filename from any supported URL path", () => {
const url = new URL("https://source.example.com/fonts/brand.woff2");
expect(getFileName(url)).toBe("brand.woff2");
expect(getMimeType(url)).toBe("font/woff2");
});
test("distinguishes upload fingerprints by filename and content", async () => {
const first = new File([""], "first.md");
const renamed = new File([""], "renamed.md");
@@ -13,6 +13,8 @@ import {
IMAGE_EXTENSIONS,
detectAssetType,
getAssetContentHash,
decodePathFragment,
validateFileName,
} from "@webstudio-is/sdk";
import type { UploadingFileData } from "~/shared/nano-states";
@@ -54,7 +56,14 @@ export const getImageNameAndType = (fileName: string) => {
return [getMimeTypeByExtension(extractedExt)!, fileName] as const;
};
const extractImageNameAndMimeTypeFromUrl = (url: URL) => {
const extractNameAndMimeTypeFromUrl = (url: URL) => {
try {
const filename = decodePathFragment(url.pathname.split("/").at(-1) ?? "");
const { mimeType } = validateFileName(filename);
return [mimeType, filename] as const;
} catch {
// Try the image name in the rest of the URL.
}
const nameFromPath = url.pathname
.split("/")
.map(getImageNameAndType)
@@ -107,7 +116,7 @@ export const getMimeType = (file: File | URL) => {
return file.type;
}
return extractImageNameAndMimeTypeFromUrl(file)[0];
return extractNameAndMimeTypeFromUrl(file)[0];
};
export const getFileName = (file: File | URL) => {
@@ -115,7 +124,7 @@ export const getFileName = (file: File | URL) => {
return file.name;
}
return extractImageNameAndMimeTypeFromUrl(file)[1];
return extractNameAndMimeTypeFromUrl(file)[1];
};
export const uploadingFileDataToAsset = (
@@ -285,7 +285,7 @@ describe("upload-assets", () => {
1,
"font",
[new URL("https://source.example.com/brand.woff2")],
{}
{ preserveFilename: true }
);
expect(upload).toHaveBeenNthCalledWith(
2,
@@ -418,6 +418,50 @@ describe("upload-assets", () => {
expect(waitForUpload).not.toHaveBeenCalled();
});
test("requests content deduplication when importing an image again", async () => {
$project.set({ id: "target-project" } as Project);
const sourceAsset = {
id: "source-image",
projectId: "source-project",
name: "hero.png",
type: "image",
format: "png",
size: 4,
createdAt: "2026-01-01",
description: null,
meta: { width: 100, height: 100 },
} satisfies Asset;
const targetAsset = {
...sourceAsset,
id: "target-image",
projectId: "target-project",
name: "stored-hero.png",
} satisfies Asset;
$assets.set(new Map([[targetAsset.id, targetAsset]]));
const url = "https://source.example.com/cgi/image/hero.png?format=raw";
const upload = vi.fn(
async (
_type: string,
[sourceUrl]: URL[],
_options?: { preserveFilename?: boolean }
) => new Map([[sourceUrl, targetAsset.id]])
);
const waitForUpload = vi.fn(async () => targetAsset);
const imported = await importAssets(
"target-project",
[{ asset: sourceAsset, url }],
{ upload, waitForUpload }
);
expect(imported.get(sourceAsset.id)).toEqual(targetAsset);
expect(upload).toHaveBeenCalledOnce();
const [type, [sourceUrl], options] = upload.mock.calls[0];
expect(type).toBe("image");
expect(sourceUrl.href).toBe(url);
expect(options).toEqual({ preserveFilename: true });
});
test("passes the existing browser content hash to the shared upload ticket", async () => {
request.mockResolvedValue(
new Response(
@@ -561,6 +605,49 @@ describe("upload-assets", () => {
});
});
test("sends the source URL and stable filename for server content deduplication", async () => {
$assets.set(
new Map([
[
"existing",
{
id: "existing",
projectId: "target-project",
name: "hero.svg",
type: "image",
format: "svg",
size: 4,
createdAt: "2026-01-01",
description: null,
meta: { width: 100, height: 100 },
} satisfies Asset,
],
])
);
request.mockResolvedValue(
Response.json({
assetId: "existing",
name: "hero.svg",
deduplicated: true,
})
);
await createUploadTicket({
authToken: "token",
projectId: "target-project",
fileOrUrl: new URL(
"https://source.example.com/cgi/asset/hero.svg?format=raw"
),
preserveFilename: true,
assetType: "image",
request,
});
const [_url, init] = request.mock.calls[0] as [string, { body: FormData }];
expect(init.body.get("filename")).toBe("hero.svg");
expect(init.body.get("sourceUrl")).toBe(
"https://source.example.com/cgi/asset/hero.svg?format=raw"
);
});
test("preserves identical file content with different filenames", async () => {
const filesData = await getFilesData(
"image",
@@ -41,6 +41,7 @@ type UploadAssetsOptions = {
folderId?: string;
dimensions?: { width: number; height: number };
deduplicate?: boolean;
preserveFilename?: boolean;
};
const safeDeleteAssets = (assetIds: Asset["id"][], projectId: string) => {
@@ -320,6 +321,7 @@ const createUploadTicket = async ({
fileOrUrl,
contentHash,
deduplicate = true,
preserveFilename = false,
assetType,
request = fetch,
}: {
@@ -329,6 +331,7 @@ const createUploadTicket = async ({
fileOrUrl: File | URL;
contentHash?: string;
deduplicate?: boolean;
preserveFilename?: boolean;
assetType: AssetType;
request?: typeof fetch;
}): Promise<UploadTicket> => {
@@ -342,13 +345,18 @@ const createUploadTicket = async ({
if (contentHash !== undefined && deduplicate) {
metaFormData.append("contentHash", contentHash);
}
if (fileOrUrl instanceof URL && deduplicate && preserveFilename) {
metaFormData.append("sourceUrl", fileOrUrl.href);
}
const existingNames = new Set<string>();
for (const asset of $assets.get().values()) {
if (asset.folderId === folderId) {
existingNames.add(formatAssetName(asset));
}
}
const deduplicatedFilename = deduplicateAssetName(fileName, existingNames);
const deduplicatedFilename = preserveFilename
? fileName
: deduplicateAssetName(fileName, existingNames);
// sanitizeS3Key here is just because of https://github.com/remix-run/remix/issues/4443
// should be removed after fix
metaFormData.append("filename", sanitizeS3Key(deduplicatedFilename));
@@ -549,6 +557,7 @@ export const uploadAssets = async <T extends File | URL>(
contentHash:
fileData.source === "file" ? fileData.contentHash : undefined,
deduplicate: options.deduplicate,
preserveFilename: options.preserveFilename,
assetType: fileData.type,
});
fileData.assetId = ticket.assetId;
@@ -659,6 +668,9 @@ export const importAssets = async (
// never modify an existing target Asset that upload deduplication reused.
options = { deduplicate: false };
}
if (source.asset.type === "image" || source.asset.type === "font") {
options = { ...options, preserveFilename: true };
}
const assetId = (await upload(source.asset.type, [url], options)).get(url);
if (assetId === undefined) {
throw new Error("Failed to import asset");
@@ -15,6 +15,7 @@ import {
readAssetRestFormData,
readAssetRestJson,
} from "~/services/asset-rest.server";
import { getUrlAssetContentHash } from "~/services/asset-upload.server";
// Keep upload commands under an explicit collection so read-only Assets API
// operations can use stable names without colliding with uploaded filenames.
@@ -56,13 +57,18 @@ export const action = async (props: ActionFunctionArgs) => {
input.projectId,
"edit"
);
const contentHash =
input.contentHash ??
(input.sourceUrl === undefined
? undefined
: await getUrlAssetContentHash(input.sourceUrl, input.filename));
const ticket = await repository.createUploadTicket({
type: input.type,
filename: input.filename,
displayFilename: input.displayFilename,
description: input.description,
folderId: input.folderId,
contentHash: input.contentHash,
contentHash,
});
return json(ticket, { headers: privateNoStoreResponseHeaders });
} catch (error) {
@@ -1,6 +1,12 @@
import { afterEach, expect, test, vi } from "vitest";
import { RESIZABLE_IMAGE_MIME_TYPES } from "@webstudio-is/sdk";
import { getBrowserUploadBody } from "./asset-upload.server";
import {
getAssetContentHash,
RESIZABLE_IMAGE_MIME_TYPES,
} from "@webstudio-is/sdk";
import {
getBrowserUploadBody,
getUrlAssetContentHash,
} from "./asset-upload.server";
afterEach(() => {
vi.unstubAllGlobals();
@@ -100,3 +106,17 @@ test("reports browser URL image fetch failures", async () => {
"An error occurred while fetching the image at https://example.com/image.png: not found"
);
});
test("hashes remote SVG bytes for upload deduplication", async () => {
const svg = '<svg xmlns="http://www.w3.org/2000/svg"></svg>';
const fetch = vi.fn(async () => new Response(svg));
vi.stubGlobal("fetch", fetch);
await expect(
getUrlAssetContentHash(
"https://source.example.com/cgi/image/logo.svg?format=raw",
"logo.svg"
)
).resolves.toBe(await getAssetContentHash(new TextEncoder().encode(svg)));
expect(fetch).toHaveBeenCalledOnce();
});
@@ -1,10 +1,52 @@
import { z } from "zod";
import { RESIZABLE_IMAGE_MIME_TYPES } from "@webstudio-is/sdk";
import { arrayBuffer } from "node:stream/consumers";
import { createSizeLimiter } from "@webstudio-is/asset-uploader/server";
import {
getAssetContentHash,
RESIZABLE_IMAGE_MIME_TYPES,
} from "@webstudio-is/sdk";
import { getMaxAssetUploadSize } from "~/shared/asset-client";
const urlBody = z.object({
url: z.string(),
});
export const getUrlAssetBody = async (url: string) => {
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 (imageRequest.body === null) {
throw new Error(
`An error occurred while fetching the image at ${url}: Image body is null`
);
}
return imageRequest.body;
};
export const getUrlAssetContentHash = async (url: string, filename: string) => {
const body = await getUrlAssetBody(url);
const bytes = new Uint8Array(
await arrayBuffer(
createSizeLimiter(
getMaxAssetUploadSize(),
filename
)(body as unknown as AsyncIterable<Uint8Array>)
)
);
return getAssetContentHash(bytes);
};
export const getBrowserUploadBody = async (
request: Request,
contentType: string | null
@@ -26,25 +68,5 @@ export const getBrowserUploadBody = async (
throw new Error("Invalid URL asset upload body");
}
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 (imageRequest.body === null) {
throw new Error(
`An error occurred while fetching the image at ${url}: Image body is null`
);
}
return imageRequest.body;
return getUrlAssetBody(urlParse.data.url);
};
@@ -1,10 +1,5 @@
import {
getAssetUrl,
type Asset,
type WebstudioFragment,
} from "@webstudio-is/sdk";
import { produce } from "immer";
import { traverseStyleValue } from "@webstudio-is/project-build/runtime";
import { getAssetUrl, type WebstudioFragment } from "@webstudio-is/sdk";
import { importFragmentAssets } from "@webstudio-is/project-build/runtime";
import type { builderApi } from "../builder-api";
const assetTransferError =
@@ -21,116 +16,21 @@ export const transferFragmentAssets = async ({
fragments: WebstudioFragment[];
importAssets: typeof builderApi.importAssets;
}) => {
if (fragments.every((fragment) => fragment.assets.length === 0)) {
return {
success: true,
fragments: new Map(fragments.map((fragment) => [fragment, fragment])),
assetIds: new Map<Asset["id"], Asset["id"]>(),
assets: new Map<Asset["id"], Asset>(),
} as const;
}
const assets = new Map(
fragments.flatMap((fragment) =>
fragment.assets.map((asset) => [asset.id, asset] as const)
)
);
let importedAssets: Map<Asset["id"], Asset>;
try {
importedAssets = await importAssets(
projectId,
Array.from(assets.values(), (asset) => ({
asset,
url:
sourceOrigin === undefined
? undefined
: getAssetUrl(asset, sourceOrigin).href,
}))
const result = await importFragmentAssets(fragments, (assets) =>
importAssets(
projectId,
assets.map((asset) => ({
asset,
url:
sourceOrigin === undefined
? undefined
: getAssetUrl(asset, sourceOrigin).href,
}))
)
);
return { success: true, ...result } as const;
} catch {
return { success: false, error: assetTransferError } as const;
}
if (importedAssets.size !== assets.size) {
return { success: false, error: assetTransferError } as const;
}
const assetIds = new Map<Asset["id"], Asset["id"]>();
const transferredFragments = new Map<WebstudioFragment, WebstudioFragment>();
for (const fragment of fragments) {
const replacementIds = new Map<Asset["id"], Asset["id"]>();
const replacementFontFamilies = new Map<string, string>();
for (const sourceAsset of fragment.assets) {
const importedAsset = importedAssets.get(sourceAsset.id);
if (importedAsset === undefined) {
throw new Error("Imported asset is missing");
}
assetIds.set(sourceAsset.id, importedAsset.id);
if (
sourceAsset.id === importedAsset.id &&
(sourceAsset.type !== "font" ||
importedAsset.type !== "font" ||
sourceAsset.meta.family === importedAsset.meta.family)
) {
continue;
}
// Keep the old replacement order if an imported ID is another source ID.
if (sourceAsset.id !== importedAsset.id) {
for (const [sourceId, currentId] of replacementIds) {
if (currentId === sourceAsset.id) {
replacementIds.set(sourceId, importedAsset.id);
}
}
if (replacementIds.has(sourceAsset.id) === false) {
replacementIds.set(sourceAsset.id, importedAsset.id);
}
}
if (sourceAsset.type === "font" && importedAsset.type === "font") {
const from = sourceAsset.meta.family;
const to = importedAsset.meta.family;
if (from === to) {
continue;
}
for (const [original, current] of replacementFontFamilies) {
if (current === from) {
replacementFontFamilies.set(original, to);
}
}
if (replacementFontFamilies.has(from) === false) {
replacementFontFamilies.set(from, to);
}
}
}
const transferredFragment = produce(fragment, (draft) => {
for (const prop of draft.props) {
if (prop.type === "asset") {
prop.value = replacementIds.get(prop.value) ?? prop.value;
}
}
for (const style of draft.styles) {
traverseStyleValue(style.value, (item) => {
if (item.type === "image" && item.value.type === "asset") {
item.value.value =
replacementIds.get(item.value.value) ?? item.value.value;
}
if (item.type === "fontFamily") {
const mapped = item.value.map(
(family) => replacementFontFamilies.get(family) ?? family
);
if (mapped.some((family, index) => family !== item.value[index])) {
item.value = mapped;
}
}
});
}
draft.assets = [];
});
transferredFragments.set(fragment, transferredFragment);
}
return {
success: true,
fragments: transferredFragments,
assetIds,
assets: importedAssets,
} as const;
};
@@ -16,6 +16,7 @@ import { jsx } from "./plugin-jsx";
import { markdown } from "./plugin-markdown";
import { webflow } from "./plugin-webflow/plugin-webflow";
import { designTokens } from "./plugin-design-tokens";
import { token, copyTokenData } from "./plugin-token";
import { builderApi } from "../builder-api";
import { readClipboardText } from "../clipboard";
import { $selectedInstance } from "../nano-states";
@@ -329,6 +330,7 @@ export const initCopyPaste = ({ signal }: { signal: AbortSignal }) => {
initPlugins({
plugins: [
variableClipboard,
token,
pageText,
instanceJson,
instanceText,
@@ -468,6 +470,16 @@ export const copyInstance = () => {
return writeClipboardText(instanceText.onCopy?.());
};
export const copyToken = async (tokenId: string) =>
writeClipboardText(copyTokenData(tokenId));
export const pasteToken = async (data: string) => {
const result = await token.onPaste?.(data);
if (result !== undefined) {
reportPasteResult(result);
}
};
export const copyPage = (pageId: string) => {
return writeClipboardText(copyPageData(pageId));
};
@@ -1,5 +1,6 @@
import type { WebstudioFragment } from "@webstudio-is/sdk";
import { generateFragmentFromHtml } from "@webstudio-is/project-build/runtime";
import { parseWebstudioPragma } from "@webstudio-is/project-build/transfer";
import { generateFragmentFromTailwind } from "../tailwind/tailwind";
import { denormalizeSrcProps } from "./asset-upload";
import { pasteHandled, pasteIgnored, type Plugin } from "./copy-paste";
@@ -9,8 +10,6 @@ import {
insertFragmentWithBreakpointWarning,
} from "./fragment-utils";
const inceptionMark = `<!-- @webstudio/inception/1 -->`;
const handlePasteHtml = async (html: string) => {
const parseResult = generateFragmentFromHtml(html);
const { skippedSelectors } = parseResult;
@@ -19,7 +18,12 @@ const handlePasteHtml = async (html: string) => {
return pasteIgnored;
}
fragment = await denormalizeSrcProps(fragment);
if (html.includes(inceptionMark)) {
const pragma = parseWebstudioPragma({
source: html,
syntax: "html",
namespace: "inception",
});
if (pragma.valid && pragma.version === "1") {
fragment = await generateFragmentFromTailwind(fragment);
}
if ((await insertFragmentWithBreakpointWarning(fragment)) === false) {
@@ -0,0 +1,69 @@
import { copyDesignToken } from "@webstudio-is/project-build/runtime";
import { parseTokenTransferData } from "@webstudio-is/project-build/transfer";
import { $project } from "~/shared/sync/data-stores";
import { $selectedInstance } from "~/shared/nano-states";
import {
executeRuntimeMutation,
getWebstudioData,
} from "../instance-utils/data";
import { builderApi } from "../builder-api";
import { pasteHandled, pasteIgnored, type Plugin } from "./copy-paste";
import { transferFragmentAssets } from "./asset-transfer-utils";
export const copyTokenData = (tokenId: string) =>
copyDesignToken(getWebstudioData(), {
tokenId,
sourceOrigin: window.location.origin,
}).data;
export const token: Plugin = {
name: "token",
mimeType: "text/plain",
onPaste: async (data) => {
const parsed = parseTokenTransferData(data);
if (parsed.owned === false) {
return pasteIgnored;
}
if (parsed.valid === false) {
return { success: false, error: "Invalid token data" };
}
const projectId = $project.get()?.id;
const instanceId = $selectedInstance.get()?.id;
if (projectId === undefined) {
return { success: false, error: "Project is unavailable" };
}
if (instanceId === undefined) {
return { success: false, error: "Token cannot be pasted here" };
}
try {
const transfer = await transferFragmentAssets({
sourceOrigin: parsed.data.sourceOrigin,
projectId,
fragments: [parsed.data.fragment],
importAssets: builderApi.importAssets,
});
if (transfer.success === false) {
return { success: false, error: transfer.error };
}
if (
$project.get()?.id !== projectId ||
$selectedInstance.get()?.id !== instanceId
) {
return { success: false, error: "Project changed while pasting." };
}
const result = executeRuntimeMutation({
id: "designTokens.paste",
input: {
instanceId,
data,
assetIds: [...transfer.assetIds],
},
});
return result === undefined
? { success: false, error: "Token cannot be pasted here" }
: pasteHandled;
} catch {
return { success: false, error: "Token cannot be pasted here" };
}
},
};
@@ -63,6 +63,10 @@ If an imported name conflicts with an existing token, choose how to continue:
Review imported tokens and CSS variables before applying them throughout the
Project, especially when the source contains multiple modes or aliases.
## Copy tokens between projects
Open a token’s menu and choose Copy. Select an instance in another project, then paste. Webstudio attaches a new token named “Button copy 1” (or the next available number) to that instance, with the source token’s breakpoint styles, referenced CSS variables, image assets, and fonts. Missing breakpoints are created.
## How to use tokens <a href="#how-to-use-tokens-in-webstudio" id="how-to-use-tokens-in-webstudio"></a>
The workflow for styling Tokens in Webstudio is nearly the same as styling classes in Webflow, except better.
+4
View File
@@ -62,6 +62,10 @@ While the server is running, stdout is reserved for MCP JSON-RPC messages. Do no
## One-Shot Tool Calls
### Token transfer
Use `copy-design-token` with `tokenId` to get a transfer payload. Pass that payload as `data` to `paste-design-token` in the target project. Set `instanceId` to attach the new token to an instance; without it, paste creates the token without attaching it. Each paste creates the next numbered copy. Image and font assets transfer when both projects use the same Webstudio origin.
### Native Form actions
A native Form (`ResourceForm`) selects Resources through a data source. Create
@@ -0,0 +1,115 @@
import { expect, test } from "vitest";
import { copyDesignToken } from "@webstudio-is/project-build/runtime";
import { getStyleDeclKey, type Asset, type StyleDecl } from "@webstudio-is/sdk";
import { prepareMcpTokenPasteData } from "./mcp-token-transfer";
const image: Asset = {
id: "source-image",
projectId: "source",
name: "image.png",
type: "image",
format: "png",
meta: { width: 100, height: 100 },
size: 3,
description: null,
createdAt: "2026-01-01",
};
const style: StyleDecl = {
styleSourceId: "token",
breakpointId: "base",
property: "backgroundImage",
value: { type: "image", value: { type: "asset", value: image.id } },
};
const data = copyDesignToken(
{
assets: new Map([[image.id, image]]),
breakpoints: new Map([["base", { id: "base", label: "Base" }]]),
styleSources: new Map([
["token", { type: "token", id: "token", name: "Card" }],
]),
styleSourceSelections: new Map(),
styles: new Map([[getStyleDeclKey(style), style]]),
},
{ tokenId: "token", sourceOrigin: "https://builder.example.com" }
).data;
test("MCP paste transfers token assets before passing data to the runtime", async () => {
const steps: string[] = [];
const prepared = await prepareMcpTokenPasteData({
data,
projectOrigin: "https://builder.example.com",
dryRun: false,
download: async (url) => {
steps.push(`download:${url.pathname}`);
return {
ok: true,
url: url.href,
arrayBuffer: async () => new ArrayBuffer(3),
};
},
upload: async (asset, bytes, detectMetadata) => {
steps.push(`upload:${asset.name}:${bytes.byteLength}:${detectMetadata}`);
return [{ ...image, id: "target-image", projectId: "target" }];
},
refreshAssets: async () => {
steps.push("refresh");
},
});
expect(steps).toEqual([
"download:/cgi/image/image.png",
"upload:image.png:3:true",
"refresh",
]);
expect(prepared).toEqual([
[
"https://builder.example.com/cgi/image/image.png?format=raw",
"target-image",
],
]);
});
test("MCP dry runs do not upload token assets", async () => {
let requested = false;
await expect(
prepareMcpTokenPasteData({
data,
projectOrigin: "https://builder.example.com",
dryRun: true,
download: async () => {
requested = true;
throw new Error("Unexpected download");
},
upload: async () => {
requested = true;
throw new Error("Unexpected upload");
},
refreshAssets: async () => {
requested = true;
},
})
).rejects.toThrow();
expect(requested).toBe(false);
});
test("MCP paste rejects assets from another origin before downloading", async () => {
let requested = false;
await expect(
prepareMcpTokenPasteData({
data,
projectOrigin: "https://another-builder.example.com",
dryRun: false,
download: async () => {
requested = true;
throw new Error("Unexpected download");
},
upload: async () => {
requested = true;
throw new Error("Unexpected upload");
},
refreshAssets: async () => {
requested = true;
},
})
).rejects.toThrow();
expect(requested).toBe(false);
});
@@ -0,0 +1,62 @@
import { importFragmentAssets } from "@webstudio-is/project-build/runtime";
import { parseTokenTransferData } from "@webstudio-is/project-build/transfer";
import { getAssetUrl, type Asset } from "@webstudio-is/sdk";
export const prepareMcpTokenPasteData = async ({
data,
projectOrigin,
dryRun,
download,
upload,
refreshAssets,
}: {
data: string;
projectOrigin: string;
dryRun: boolean;
download: (url: URL) => Promise<Pick<Response, "ok" | "url" | "arrayBuffer">>;
upload: (
asset: Asset,
data: ArrayBuffer,
detectMetadata: boolean
) => Promise<Asset[]>;
refreshAssets: () => Promise<unknown>;
}) => {
const parsed = parseTokenTransferData(data);
if (parsed.valid === false || parsed.data.fragment.assets.length === 0) {
return [];
}
if (dryRun) {
throw new Error("Asset transfer is unavailable in dry-run mode");
}
if (parsed.data.sourceOrigin !== projectOrigin) {
throw new Error("Token assets must come from this Webstudio origin");
}
const transfer = await importFragmentAssets(
[parsed.data.fragment],
async (assets) => {
const importedAssets = new Map<Asset["id"], Asset>();
for (const asset of assets) {
const response = await download(getAssetUrl(asset, projectOrigin));
if (
response.ok === false ||
new URL(response.url).origin !== projectOrigin
) {
throw new Error("Token asset could not be downloaded");
}
const uploaded = await upload(
asset,
await response.arrayBuffer(),
true
);
const imported = uploaded.find((item) => item.type === asset.type);
if (imported === undefined) {
throw new Error("Token asset could not be uploaded");
}
importedAssets.set(asset.id, imported);
}
return importedAssets;
}
);
await refreshAssets();
return [...transfer.assetIds];
};
+31 -1
View File
@@ -61,6 +61,7 @@ import {
getPagePath,
} from "@webstudio-is/sdk";
import { matchPathnameRoutes } from "@webstudio-is/wsauth";
import { prepareMcpTokenPasteData } from "./mcp-token-transfer";
import { fontMetaUpdate } from "@webstudio-is/fonts";
import { resolveApiConnection } from "../api-connection";
import {
@@ -2142,7 +2143,36 @@ const createCliMcpHost = async ({
onProjectSessionChange: previewFreshness.markStale,
executeOperation: async ({ command, input, dryRun }) => {
assertMcpToolServerSupport(command, apiContract, dryRun === true);
const operationInput = getMcpOperationInput(command, input);
let operationInput = getMcpOperationInput(command, input);
const projectOrigin = new URL(apiConnection.origin).origin;
if (command === "copy-design-token" && isPlainRecord(operationInput)) {
operationInput = { ...operationInput, sourceOrigin: projectOrigin };
}
if (
command === "paste-design-token" &&
isPlainRecord(operationInput) &&
typeof operationInput.data === "string"
) {
operationInput = {
...operationInput,
assetIds: await prepareMcpTokenPasteData({
data: operationInput.data,
projectOrigin,
dryRun: dryRun === true,
download: (url) => fetch(url),
upload: (asset, data, detectMetadata) =>
httpClient.uploadAsset({
...apiConnection,
upload: {
asset: { ...asset, folderId: undefined },
data,
detectMetadata,
},
}),
refreshAssets: () => session.refresh(["assets"]),
}),
};
}
const textAssetFeedback = await prepareTextAssetWriteFeedback({
command,
input,
+2 -2
View File
@@ -149,8 +149,8 @@ test("prints compact mcp tool summaries as json by default", () => {
inputSchema,
})
);
// Includes Form simulation, custom response headers, and screenshot schemas.
expect(JSON.stringify(handshakePayload).length).toBeLessThan(222_000);
// Includes Form simulation, custom response headers, screenshot, and token transfer schemas.
expect(JSON.stringify(handshakePayload).length).toBeLessThan(224_000);
const screenshotTool = expectedTools.find(
({ name }) => name === "screenshot"
);
+1 -1
View File
@@ -8,7 +8,7 @@ export const cliDocs = {
"manual-llm":
'# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get-more-tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call m Line truncated
"manual-mcp":
'# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\n### Native Form actions\n\nA native Form (`ResourceForm`) selects Resources through a data source. Create\nthe Resource with `scopeInstanceId` on the Form or an ancestor and\n`exposeAsDataSource:true`; use the returned `dataSourceId` in the Form\'s `action`\nJSON array with `update-props`. Scope it to the Form when the request needs\n`formData`. Do not bind a resource prop or set `exposeAsDataSource:false` for a\nnative Form action. The selected Resource runs on submission unless page\ncontent also reads it.\n\n### Server-side Form simulation\n\n`forms.simulate-submission` evaluates a saved Form using synthetic string fields\nand the same trusted Builder server Form handler used by Builder Preview. Supply\nthe saved Form instance ID and page path. The server uses this project\'s\npublisher origin. It can trigger the Form\'s configured HTTP and Email Resources, so verify\nevery destination and recipient first. For dynamic checkbox or multiple-select fields,\npass `arrayNames` to preserve an empty or single-value array when the saved\nfield props do not identify the control. The result reports destination IDs,\nstatuses, and errors without Resource bodies. Managed Email errors include a\ncode when available. It reports the final outcome, not live Form progress.\nThis server simulation does not exercise client validation, browser event\nhandlers, navigation, file bytes, or actual browser informatiLine truncated
'# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\n### Token transfer\n\nUse `copy-design-token` with `tokenId` to get a transfer payload. Pass that payload as `data` to `paste-design-token` in the target project. Set `instanceId` to attach the new token to an instance; without it, paste creates the token without attaching it. Each paste creates the next numbered copy. Image and font assets transfer when both projects use the same Webstudio origin.\n\n### Native Form actions\n\nA native Form (`ResourceForm`) selects Resources through a data source. Create\nthe Resource with `scopeInstanceId` on the Form or an ancestor and\n`exposeAsDataSource:true`; use the returned `dataSourceId` in the Form\'s `action`\nJSON array with `update-props`. Scope it to the Form when the request needs\n`formData`. Do not bind a resource prop or set `exposeAsDataSource:false` for a\nnative Form action. The selected Resource runs on submission unless page\ncontent also reads it.\n\n### Server-side Form simulation\n\n`forms.simulate-submission` evaluates a saved Form using synthetic string fields\nand the same trusted Builder server Form handler used by Builder Preview. Supply\nthe saved Form instance ID and page path. The server uses this project\'s\npublisher origin. It can trigger the Form\'s configured HTTP and Email Resources, so verify\nevery destination and recipient first. For dynamic checkbox or multiple-select fields,\npass `arrayNames` to preserve an empty oLine truncated
"mcp-startup-epilogue":
'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the input as `.temp/insert-fragment.json`; use single quotes for JSX attributes so the JSON needs no backslash escaping:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 12px;`}><h2>Launch Kit</h2><p>A focused section created with Webstudio JSX.</p><button>Get started</button></section>"\n}\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in exactly one direct `ws:block-template` child. A missing or second template container makes the block invalid. Templates themselves are protected; an editor\'s inserted copy becomes editable Content Block body content. Verify this structure before handoff.\n\nFor an MDX-backed Content Block, use the dedicated content-source tools instead of generic prop mutations: connect, switch, inspect, edit, update frontmatter, reload, or disconnect the source. Confirm before replacing existing Body content. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX resolves a unique stable template **Name** or a built-in MDX adapter. Add custom components to this Content Block\'s Templates before referencing them in MDX. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep template styles. A mismatched child structure replaces defaults, an explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live when matching templates are added later. Preserve invalid source and unresolved names, inspect all diagnostics, and reload before retrying a revision conflict. A frontmatter update replaces the complete property map; preserve fields the user did not ask to remove. Store frontmatter images as exact `$ref` objects; bind editable Image sources to `.src` with explicit `binding.mode:"readwrite"` and alt properties to the Asset `.description` with `mode:"read"`. Omitting the source mode leaves the image visible but not replaceable in Content mode. Only exact direct frontmatter bindings may use `mode:"readwrite"`. After a template rename or deletion, use `migrate-content-block-template-refe Line truncated
"mcp-vision":
+4
View File
@@ -35,6 +35,10 @@ While the server is running, stdout is reserved for MCP JSON-RPC messages. Do no
## One-Shot Tool Calls
### Token transfer
Use `copy-design-token` with `tokenId` to get a transfer payload. Pass that payload as `data` to `paste-design-token` in the target project. Set `instanceId` to attach the new token to an instance; without it, paste creates the token without attaching it. Each paste creates the next numbered copy. Image and font assets transfer when both projects use the same Webstudio origin.
### Native Form actions
A native Form (`ResourceForm`) selects Resources through a data source. Create
+1 -1
View File
@@ -1620,7 +1620,7 @@ test("parse &:functional-pseudo as state", () => {
expect(parseCss(`&:nth-child(2) { color: red }`, new Map()).styles).toEqual([
{
selector: "",
state: ":nth-child",
state: ":nth-child(2)",
property: "color",
value: { type: "keyword", value: "red" },
},
+63 -37
View File
@@ -247,9 +247,9 @@ const preserveOriginalVarLonghands = (
);
}
// Recover unresolved var()->longhand mapping when shorthand expansion drops
// Recover var()->longhand mapping when shorthand expansion drops
// the var() token (e.g. outline/border cases that default to currentcolor).
for (const varText of getFallbacklessVarTexts(value)) {
for (const varText of getVarTexts(value)) {
const varName = getVarNameFromVarText(varText);
if (varName === undefined) {
continue;
@@ -298,17 +298,14 @@ const preserveOriginalVarLonghands = (
return serialized.includes('"type":"var"') || serialized.includes("var(");
});
const firstFallbacklessVarText = getFallbacklessVarTexts(value)[0];
const firstVarText = getVarTexts(value)[0];
if (firstFallbacklessVarText !== undefined) {
if (firstVarText !== undefined) {
for (const [prop, styleValue] of parsedCss) {
if (styleValue.type !== "invalid") {
continue;
}
parsedCss.set(
prop,
parseCssValueLonghand(prop, firstFallbacklessVarText)
);
parsedCss.set(prop, parseCssValueLonghand(prop, firstVarText));
}
}
@@ -318,12 +315,9 @@ const preserveOriginalVarLonghands = (
// When no var() survived at all, keep the first unresolved var() on all
// parsed longhands so authored references are not lost.
if (!hasAnyPreservedVar) {
if (firstFallbacklessVarText !== undefined) {
if (firstVarText !== undefined) {
for (const prop of parsedCss.keys()) {
parsedCss.set(
prop,
parseCssValueLonghand(prop, firstFallbacklessVarText)
);
parsedCss.set(prop, parseCssValueLonghand(prop, firstVarText));
}
}
}
@@ -395,7 +389,7 @@ const getSingleFallbacklessVarText = (value: string): string | undefined => {
}
};
const getFallbacklessVarTexts = (value: string): string[] => {
const getVarTexts = (value: string): string[] => {
try {
const ast = csstree.parse(value, { context: "value" });
const vars: string[] = [];
@@ -408,7 +402,7 @@ const getFallbacklessVarTexts = (value: string): string[] => {
return;
}
const parsedVar = parseCssVar(fnNode);
if (!parsedVar || parsedVar.fallback !== undefined) {
if (!parsedVar) {
return;
}
vars.push(csstree.generate(fnNode));
@@ -422,7 +416,7 @@ const getFallbacklessVarTexts = (value: string): string[] => {
};
const getVarNameFromVarText = (varText: string): string | undefined => {
const match = varText.trim().match(/^var\(\s*(--[\w-]+)\s*\)$/);
const match = varText.trim().match(/^var\(\s*(--[\w-]+)/);
return match?.[1];
};
@@ -713,10 +707,11 @@ export type ParseCssResult = {
* to be resolved together as if they apply to the same element.
*/
export const extractCssCustomProperties = (
css: string
css: string,
parsedAst?: csstree.CssNode
): Map<string, string> => {
const map = new Map<string, string>();
const ast = cssTreeTryParse(css);
const ast = parsedAst ?? cssTreeTryParse(css);
if (ast === undefined) {
return map;
}
@@ -738,9 +733,16 @@ export const extractCssCustomProperties = (
export const parseCss = (
css: string,
cssVars: Map<string, string>
cssVars: Map<string, string>,
// Callers may reuse a css-tree AST parsed with positions: true.
parsedAst?: csstree.CssNode,
options: {
preserveShorthandVariables?: boolean;
preserveNonPixelWidth?: boolean;
parseSelector?: (selector: csstree.Selector) => Selector;
} = {}
): ParseCssResult => {
const ast = cssTreeTryParse(css);
const ast = parsedAst ?? cssTreeTryParse(css);
const stylesMap = new Map<string, ParsedStyleDecl>();
const errors: string[] = [];
@@ -756,6 +758,7 @@ export const parseCss = (
// border-color: rgb(x y z / var(--op)); --op: 0.6;
// resolve correctly regardless of declaration order.
const customProperties = new Map<string, string>();
const emptyCustomProperties = new Map<string, string>();
const collectRuleCustomProperties = (rule: csstree.Rule) => {
customProperties.clear();
@@ -833,6 +836,7 @@ export const parseCss = (
if (
node.type === "Dimension" &&
node.unit !== "px" &&
options.preserveNonPixelWidth !== true &&
(currentFeatureName === "min-width" ||
currentFeatureName === "max-width")
) {
@@ -870,6 +874,10 @@ export const parseCss = (
if (node.type !== "Selector") {
continue;
}
if (options.parseSelector !== undefined) {
selectors.push(options.parseSelector(node));
continue;
}
let selector: Selector | undefined = undefined;
const children = node.children.toArray();
const startsWithNesting = children[0]?.type === "NestingSelector";
@@ -898,14 +906,14 @@ export const parseCss = (
case "PseudoClassSelector": {
// First pseudo selector is not a state but an element selector, e.g. :root
if (selector) {
state = `:${childNode.name}`;
state = csstree.generate(childNode);
} else {
name = `:${childNode.name}`;
name = csstree.generate(childNode);
}
break;
}
case "PseudoElementSelector":
state = `::${childNode.name}`;
state = csstree.generate(childNode);
break;
case "Combinator":
// " " vs " > "
@@ -917,7 +925,7 @@ export const parseCss = (
if (selector) {
selector.name += name;
if (state) {
selector.state = state;
selector.state = `${selector.state ?? ""}${state}`;
}
} else {
selector = { name, state };
@@ -943,15 +951,26 @@ export const parseCss = (
const substituted = substituteVarsInShorthand(
property,
stringValue,
customProperties,
options.preserveShorthandVariables
? emptyCustomProperties
: customProperties,
cssVars
);
if (substituted !== undefined) {
parsedCss = substituted.result;
for (const varName of substituted.droppedVars) {
errors.push(
`"${property}" was not applied because ${varName} could not be resolved`
);
parsedCss =
options.preserveShorthandVariables && stringValue.includes("var(")
? preserveOriginalVarLonghands(
property,
stringValue,
substituted.result
)
: substituted.result;
if (!options.preserveShorthandVariables) {
for (const varName of substituted.droppedVars) {
errors.push(
`"${property}" was not applied because ${varName} could not be resolved`
);
}
}
} else {
parsedCss = parseCssValue(property, stringValue);
@@ -1168,7 +1187,8 @@ type ParsedBreakpoint = {
};
export const parseMediaQuery = (
mediaQuery: string
mediaQuery: string,
options: { preserveNonPixelWidth?: boolean } = {}
): undefined | ParsedBreakpoint => {
const ast = csstree.parse(mediaQuery, { context: "mediaQuery" });
let minWidth: undefined | number;
@@ -1196,12 +1216,18 @@ export const parseMediaQuery = (
otherFeatures.push(cleaned);
}
}
if (node.type === "Dimension" && node.unit === "px") {
const value = Number(node.value);
if (currentWidthProperty === "minWidth") {
minWidth = value;
} else if (currentWidthProperty === "maxWidth") {
maxWidth = value;
if (node.type === "Dimension" && currentWidthProperty !== undefined) {
if (node.unit === "px") {
const value = Number(node.value);
if (currentWidthProperty === "minWidth") {
minWidth = value;
} else {
maxWidth = value;
}
} else if (options.preserveNonPixelWidth) {
const property =
currentWidthProperty === "minWidth" ? "min-width" : "max-width";
otherFeatures.push(`${property}:${node.value}${node.unit}`);
}
currentWidthProperty = undefined;
}
+9 -5
View File
@@ -351,24 +351,28 @@ export class MediaRule {
if (rules.length === 0) {
return "";
}
let conditionText = "";
let query = "";
const { minWidth, maxWidth, condition, mediaType = "all" } = this.options;
// condition and minWidth/maxWidth are mutually exclusive
// If condition is set, use it exclusively (minWidth/maxWidth must be undefined)
if (condition !== undefined) {
conditionText = ` and (${condition})`;
query =
mediaType === "all" && condition.startsWith("not (")
? condition
: `${mediaType} and (${condition})`;
} else {
// Otherwise use width-based conditions (condition must be undefined)
query = mediaType;
if (minWidth !== undefined) {
conditionText = ` and (min-width: ${minWidth}px)`;
query += ` and (min-width: ${minWidth}px)`;
}
if (maxWidth !== undefined) {
conditionText += ` and (max-width: ${maxWidth}px)`;
query += ` and (max-width: ${maxWidth}px)`;
}
}
return `@media ${mediaType}${conditionText} {\n${rules.join("\n")}\n}`;
return `@media ${query} {\n${rules.join("\n")}\n}`;
}
}
+41
View File
@@ -17,6 +17,7 @@ import {
attachDesignToken,
bindProps,
cloneInstance,
copyDesignToken,
createAssetFolder,
createProjectAssetFolder,
createBreakpoint,
@@ -99,6 +100,7 @@ import {
readProjectAssetContent,
parseBuildPatchTransactions,
parseBuilderUrl,
pasteDesignToken,
toLocalProjectBundle,
uploadAsset,
uploadAssets,
@@ -737,6 +739,12 @@ test("wraps project api trpc calls in named functions", async () => {
withUsage: true,
sort: "usage",
});
await copyDesignToken({ ...params, tokenId: "token-id" });
await pasteDesignToken({
...params,
data: "token-data",
instanceId: "instance-id",
});
await createDesignTokens({
...params,
tokens: [
@@ -1033,6 +1041,11 @@ test("wraps project api trpc calls in named functions", async () => {
expectBodyRequest("/trpc/api.styles.deleteDeclarations", '"deletions"'),
expectBodyRequest("/trpc/api.styles.replaceValues", '"fromValue"'),
expectRequest("/trpc/api.designTokens.list"),
expectRequest("/trpc/api.designTokens.copy"),
expectBodyRequest(
"/trpc/api.designTokens.paste",
'"instanceId":"instance-id"'
),
expectBodyRequest("/trpc/api.designTokens.create", '"name":"Primary"'),
expectBodyRequest(
"/trpc/api.designTokens.updateStyles",
@@ -1101,6 +1114,12 @@ test("wraps project api trpc calls in named functions", async () => {
expect(decodeURIComponent(requests[0]?.search ?? "")).toContain(
'"version":2'
);
const copyRequest = requests.find(
(request) => request.path === "/trpc/api.designTokens.copy"
);
expect(decodeURIComponent(copyRequest?.search ?? "")).toContain(
'"sourceOrigin":"http://127.0.0.1:'
);
});
test("reports invalid build patch transactions", async () => {
@@ -1269,6 +1288,28 @@ test("uploads assets as binary requests", async () => {
);
});
test("lets the server detect metadata for assets described only by token CSS", async () => {
const fetch = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ uploadedAssets: [], deduplicated: false }), {
headers: { "content-type": "application/json" },
})
);
vi.stubGlobal("fetch", fetch);
await uploadAsset({
...apiParams,
upload: {
asset: createImageAssetFixture(),
data: new Uint8Array([1, 2, 3]),
detectMetadata: true,
},
});
const [url, init] = fetch.mock.calls[0] as [URL, RequestInit];
expect(url.searchParams.has("width")).toBe(false);
expect(url.searchParams.has("height")).toBe(false);
expect(url.searchParams.has("format")).toBe(false);
expect((init.headers as Headers).has("x-webstudio-asset-meta")).toBe(false);
});
test("rejects malformed successful asset upload responses", async () => {
vi.stubGlobal(
"fetch",
+31 -3
View File
@@ -408,6 +408,7 @@ type AssetUpload = {
asset: Asset;
data: BinaryAssetData;
force?: boolean;
detectMetadata?: boolean;
};
type AssetUploadDescriptor = {
@@ -510,11 +511,13 @@ const getBinaryAssetDataHash = async (data: BinaryAssetData) => {
const getAssetUploadUrl = ({
asset,
force,
detectMetadata,
origin,
projectId,
}: {
asset: Asset;
force?: boolean;
detectMetadata?: boolean;
origin: string;
projectId: string;
}) => {
@@ -525,11 +528,14 @@ const getAssetUploadUrl = ({
if (asset.folderId !== undefined) {
url.searchParams.set("folderId", asset.folderId);
}
if (asset.type === "image" || asset.type === "video") {
if (
detectMetadata !== true &&
(asset.type === "image" || asset.type === "video")
) {
url.searchParams.set("width", String(asset.meta.width));
url.searchParams.set("height", String(asset.meta.height));
}
if (asset.format !== undefined) {
if (detectMetadata !== true && asset.format !== undefined) {
url.searchParams.set("format", asset.format);
}
if (force === true) {
@@ -550,6 +556,7 @@ export const uploadAsset = async (
getAssetUploadUrl({
asset: upload.asset,
force: upload.force,
detectMetadata: upload.detectMetadata,
origin,
projectId,
}),
@@ -565,7 +572,9 @@ export const uploadAsset = async (
: encodeAssetDescriptionHeader(description),
[assetDescriptionEncodingHeader]:
description === undefined ? undefined : assetDescriptionEncoding,
"x-webstudio-asset-meta": JSON.stringify(upload.asset.meta),
"x-webstudio-asset-meta": upload.detectMetadata
? undefined
: JSON.stringify(upload.asset.meta),
"content-type": "application/octet-stream",
}),
}
@@ -2160,6 +2169,25 @@ export const listDesignTokens = projectQueryInput<
}
>("list-design-tokens");
const queryCopyDesignToken = projectQueryInput<
AuthProjectParams & { tokenId: string; sourceOrigin?: string },
{ data: string }
>("copy-design-token");
export const copyDesignToken = (
params: AuthProjectParams & { tokenId: string; sourceOrigin?: string }
) =>
queryCopyDesignToken({
...params,
sourceOrigin:
params.sourceOrigin ?? parseBuilderUrl(params.origin).sourceOrigin,
});
export const pasteDesignToken = projectMutationInput<
AuthProjectParams & { data: string; instanceId?: string },
{ tokenId: string }
>("paste-design-token");
type DesignTokenStyleInput = {
property: string;
value: unknown;
@@ -69513,6 +69513,112 @@ export const runtimeOperationContractData = [
invalidatesNamespaces: [],
retryOnConflict: false,
},
{
id: "designTokens.copy",
command: "copy-design-token",
client: "copyDesignToken",
kind: "read",
inputSchema: {
type: "object",
properties: {
tokenId: {
type: "string",
},
sourceOrigin: {
type: "string",
format: "uri",
},
},
required: ["tokenId"],
},
outputSchema: {
type: "object",
properties: {
data: {
type: "string",
},
},
required: ["data"],
additionalProperties: {},
},
readNamespaces: [
"assets",
"breakpoints",
"styles",
"styleSources",
"styleSourceSelections",
],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
requiresAssets: true,
},
{
id: "designTokens.paste",
command: "paste-design-token",
client: "pasteDesignToken",
kind: "mutation",
inputSchema: {
type: "object",
properties: {
data: {
type: "string",
},
instanceId: {
type: "string",
},
assetIds: {
type: "array",
items: {
type: "array",
prefixItems: [
{
type: "string",
},
{
type: "string",
},
],
minItems: 2,
maxItems: 2,
},
},
},
required: ["data"],
},
outputSchema: {
type: "object",
properties: {
tokenId: {
type: "string",
},
},
required: ["tokenId"],
additionalProperties: {},
},
readNamespaces: [
"assets",
"breakpoints",
"instances",
"styles",
"styleSources",
"styleSourceSelections",
],
writeNamespaces: [
"breakpoints",
"styleSources",
"styles",
"styleSourceSelections",
],
invalidatesNamespaces: [
"breakpoints",
"styleSources",
"styles",
"styleSourceSelections",
],
retryOnConflict: false,
requiresAssets: true,
},
{
id: "designTokens.create",
command: "create-design-token",
+27
View File
@@ -873,6 +873,33 @@ describe("project session mcp adapter", () => {
]);
expect(toolNames).toContain("insert-fragment");
expect(toolNames).not.toContain("meta.get_more_tools");
const tokenTools = listProjectSessionMcpTools(
runtimeOperationContracts
.filter(
({ id }) => id === "designTokens.copy" || id === "designTokens.paste"
)
.map((contract) =>
publicOperation({
command: contract.command,
id: contract.id,
method: contract.kind === "read" ? "query" : "mutation",
permit: contract.kind === "read" ? "view" : "edit",
description: contract.command,
inputSchema: contract.inputSchema,
readNamespaces: contract.readNamespaces,
writeNamespaces: contract.writeNamespaces,
})
)
).filter(
(tool) =>
tool.name === "copy-design-token" || tool.name === "paste-design-token"
);
expect(tokenTools.map(({ name }) => name)).toEqual([
"copy-design-token",
"paste-design-token",
]);
expect(tokenTools[0]?.inputSchema.required).toContain("tokenId");
expect(tokenTools[1]?.inputSchema.required).toContain("data");
const responseHeaderTools = listProjectSessionMcpTools(
runtimeOperationContracts
.filter(({ id }) => id.startsWith("responseHeaders."))
+1
View File
@@ -54,5 +54,6 @@ export * from "./runtime/slot";
export * from "./runtime/style-copy";
export * from "./runtime/style-utils";
export * from "./runtime/styles";
export * from "./runtime/token-transfer";
export * from "./runtime/tree";
export * from "./runtime/url-pattern";
@@ -1,10 +1,12 @@
export const createCopyName = (
name: string,
isTaken: (candidate: string) => boolean
isTaken: (candidate: string) => boolean,
numberFirstCopy = false
) => {
let copyNumber = 1;
while (true) {
const suffix = copyNumber === 1 ? " copy" : ` copy ${copyNumber}`;
const suffix =
copyNumber === 1 && !numberFirstCopy ? " copy" : ` copy ${copyNumber}`;
const candidate = `${name}${suffix}`;
if (isTaken(candidate) === false) {
return candidate;
+17 -3
View File
@@ -216,8 +216,17 @@ export const builderRuntimeCutoverManifests = [
},
{
family: "style-reads",
operationIds: ["styles.getDeclarations", "designTokens.list"] as const,
callers: ["appRouter.api.styles", "appRouter.api.designTokens"] as const,
operationIds: [
"styles.getDeclarations",
"designTokens.list",
"designTokens.copy",
] as const,
callers: [
"appRouter.api.styles",
"appRouter.api.designTokens",
"Builder token menu",
"MCP/CLI token transfer",
] as const,
},
{
family: "style-declaration-mutations",
@@ -241,8 +250,13 @@ export const builderRuntimeCutoverManifests = [
"designTokens.detach",
"designTokens.extract",
"designTokens.createAttached",
"designTokens.paste",
] as const,
callers: [
"appRouter.api.designTokens",
"Builder token paste",
"MCP/CLI token transfer",
] as const,
callers: ["appRouter.api.designTokens"] as const,
},
{
family: "style-source-mutations",
@@ -0,0 +1,359 @@
import { expect, test } from "vitest";
import { copyDesignToken } from "../token-transfer";
import { parseTokenTransferData, serializeTokenCss } from "./token-css";
test("reads a CSS token with variables, states, breakpoints, images, and fonts", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
@font-face {
font-family: "Example";
font-style: normal;
font-weight: 100 900;
src: url("https://builder.example.com/cgi/asset/example.woff2") format("woff2");
}
:root { --brand: #e0e0e0; }
.ws-token { color: var(--brand); background-image: url("https://builder.example.com/cgi/image/image.png?format=raw"); font-family: Example; }
.ws-token:hover { color: red; }
@media (max-width: 600px) { .ws-token { color: blue; } }
`);
expect(parsed.valid).toBe(true);
if (parsed.valid === false) {
return;
}
expect(parsed.data.sourceOrigin).toBe("https://builder.example.com");
expect(parsed.data.fragment.styleSources[0]).toMatchObject({
name: "Button",
});
expect(parsed.data.fragment.breakpoints).toEqual(
expect.arrayContaining([expect.objectContaining({ maxWidth: 600 })])
);
expect(parsed.data.fragment.styles).toEqual(
expect.arrayContaining([
expect.objectContaining({ state: ":hover", property: "color" }),
expect.objectContaining({ property: "--brand" }),
])
);
expect(parsed.data.fragment.assets).toEqual(
expect.arrayContaining([
expect.objectContaining({ type: "font", name: "example.woff2" }),
expect.objectContaining({ type: "image", name: "image.png" }),
])
);
});
test("rejects unsupported token CSS while keeping ordinary CSS pasteable", () => {
expect(parseTokenTransferData(".button { color: red; }")).toEqual({
owned: false,
valid: false,
});
expect(
parseTokenTransferData(
'/* @webstudio/token-css/v1 "Button" */ .other { color: red; }'
)
).toEqual({
owned: true,
valid: false,
});
});
test("does not claim the removed JSON token format", () => {
expect(parseTokenTransferData('{"@webstudio/token/v0.1":{}}')).toEqual({
owned: false,
valid: false,
});
});
test("keeps token attribute and descendant states", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
.ws-token[disabled] { opacity: .5; }
.ws-token > svg { fill: red; }
`);
expect(parsed.valid).toBe(true);
if (parsed.valid === false) {
return;
}
expect(parsed.data.fragment.styles.map((style) => style.state)).toEqual([
"[disabled]",
">svg",
]);
});
test("keeps complete functional and compound token states", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
.ws-token:nth-child(2) { color: red; }
.ws-token:hover:focus { color: blue; }
`);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
expect(parsed.data.fragment.styles.map((style) => style.state)).toEqual([
":nth-child(2)",
":hover:focus",
]);
}
});
test("keeps conditional root variables and variable-backed shorthands", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
:root { --space: 10px; }
:root:hover { --space: 20px; }
.ws-token { padding: var(--space); }
`);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
expect(parsed.data.fragment.styles).toEqual(
expect.arrayContaining([
expect.objectContaining({ property: "--space", state: ":hover" }),
expect.objectContaining({ property: "paddingTop" }),
expect.objectContaining({ property: "paddingRight" }),
expect.objectContaining({ property: "paddingBottom" }),
expect.objectContaining({ property: "paddingLeft" }),
])
);
}
});
test("keeps same-rule variable references in token shorthands", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
.ws-token { --space: 10px; padding: var(--space); }
@media (max-width: 600px) { .ws-token { --space: 20px; } }
`);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
expect(
parsed.data.fragment.styles.find(
(style) => style.property === "paddingTop"
)?.value
).toEqual({ type: "unparsed", value: "var(--space)" });
}
});
test("keeps variable references in mixed token shorthands", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
.ws-token { --width: 2px; outline: var(--width) solid red; }
@media (max-width: 600px) { .ws-token { --width: 4px; } }
`);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
expect(
parsed.data.fragment.styles.find(
(style) => style.property === "outlineWidth"
)?.value
).toEqual({ type: "unparsed", value: "var(--width)" });
}
});
test("keeps fallback variables in mixed token shorthands", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
.ws-token { outline: var(--width, 2px) solid red; }
`);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
expect(
parsed.data.fragment.styles.find(
(style) => style.property === "outlineWidth"
)?.value
).toEqual({ type: "unparsed", value: "var(--width, 2px)" });
}
});
test("keeps token styles at non-pixel width breakpoints", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
@media (min-width: 40em) { .ws-token { color: red; } }
`);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
expect(parsed.data.fragment.breakpoints).toEqual(
expect.arrayContaining([
expect.objectContaining({ condition: "min-width:40em" }),
])
);
expect(parsed.data.fragment.styles).toEqual(
expect.arrayContaining([expect.objectContaining({ property: "color" })])
);
}
});
test("keeps range-syntax custom media conditions", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
@media (width >= 600px) { .ws-token { color: red; } }
`);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
expect(parsed.data.fragment.breakpoints[1].condition).toContain("width");
expect(parsed.data.fragment.styles).toEqual(
expect.arrayContaining([expect.objectContaining({ property: "color" })])
);
expect(serializeTokenCss(parsed.data)).toContain(
"@media all and (width>=600px)"
);
}
});
test("keeps combined width and custom media conditions", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
@media (min-width: 600px) and (orientation: landscape) {
.ws-token { color: red; }
}
`);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
expect(parsed.data.fragment.breakpoints).toEqual(
expect.arrayContaining([
expect.objectContaining({
condition: "min-width:600px) and (orientation:landscape",
}),
])
);
expect(parsed.data.fragment.breakpoints[1]).not.toHaveProperty("minWidth");
expect(serializeTokenCss(parsed.data)).toContain(
"@media all and (min-width:600px) and (orientation:landscape)"
);
}
});
test("keeps combined custom media conditions", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
@media (orientation: landscape) and (hover: hover) {
.ws-token { color: red; }
}
`);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
expect(serializeTokenCss(parsed.data)).toContain(
"@media all and (orientation:landscape) and (hover:hover)"
);
}
});
test.each(["prefers-reduced-motion: reduce", "min-width: 600px"])(
"keeps negated media condition %s",
(feature) => {
const parsed =
parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
@media not (${feature}) {
.ws-token { color: red; }
}
`);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
const condition = `not (${feature.replace(": ", ":")})`;
expect(parsed.data.fragment.breakpoints[1].condition).toBe(condition);
expect(serializeTokenCss(parsed.data)).toContain(`@media ${condition}`);
}
}
);
test("keeps boolean operators between width conditions", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
@media (min-width: 600px) or (max-width: 400px) {
.ws-token { color: red; }
}
`);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
expect(parsed.data.fragment.breakpoints[1].condition).toBe(
"min-width:600px) or (max-width:400px"
);
expect(serializeTokenCss(parsed.data)).toContain(
"@media all and (min-width:600px) or (max-width:400px)"
);
}
});
test("allows token shorthands to reference ancestor variables", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
.ws-token { padding: var(--space); }
`);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
expect(
parsed.data.fragment.styles.filter((style) =>
style.property.startsWith("padding")
)
).toHaveLength(4);
expect(parsed.data.fragment.styles[0].value).toEqual({
type: "unparsed",
value: "var(--space)",
});
}
});
test("keeps pseudo-class positions before descendant selectors", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
.ws-token:hover > svg { fill: red; }
`);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
expect(parsed.data.fragment.styles[0].state).toBe(":hover>svg");
}
});
test("absolutizes relative image URLs when copying a pasted token", () => {
const first = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
:root { --hero: url(/cgi/image/target.svg?format=raw); }
.ws-token { background-image: var(--hero); }
`);
expect(first.valid).toBe(true);
if (first.valid === false) {
return;
}
const copiedAgain = serializeTokenCss({
...first.data,
sourceOrigin: "https://target.example.com",
});
const parsedAgain = parseTokenTransferData(copiedAgain);
expect(parsedAgain.valid).toBe(true);
if (parsedAgain.valid) {
expect(parsedAgain.data.sourceOrigin).toBe("https://target.example.com");
expect(parsedAgain.data.fragment.assets).toEqual([
expect.objectContaining({ name: "target.svg", type: "image" }),
]);
}
});
test("imports image URLs inside custom properties", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
:root { --hero: url("https://builder.example.com/cgi/image/hero.svg?format=raw"); }
.ws-token { background-image: var(--hero); }
`);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
expect(parsed.data.fragment.assets).toEqual([
expect.objectContaining({ name: "hero.svg", type: "image" }),
]);
}
});
test("discovers image assets inside variable fallbacks", () => {
const parsed = parseTokenTransferData(`/* @webstudio/token-css/v1 "Button" */
:root { --hero: var(--missing, url("https://builder.example.com/cgi/image/hero.svg?format=raw")); }
.ws-token { background-image: var(--hero); }
`);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
expect(parsed.data.fragment.assets).toEqual([
expect.objectContaining({ name: "hero.svg", type: "image" }),
]);
}
});
test("escapes token names that contain a CSS comment terminator", () => {
const copied = copyDesignToken(
{
assets: new Map(),
breakpoints: new Map(),
styleSources: new Map([
["token", { type: "token", id: "token", name: "End */ marker" }],
]),
styleSourceSelections: new Map(),
styles: new Map(),
},
{ tokenId: "token" }
);
const parsed = parseTokenTransferData(copied.data);
expect(parsed.valid).toBe(true);
if (parsed.valid) {
expect(parsed.data.fragment.styleSources[0]).toMatchObject({
name: "End */ marker",
});
}
});
@@ -0,0 +1,419 @@
import {
extractCssCustomProperties,
parseCss,
parseMediaQuery,
} from "@webstudio-is/css-data";
import {
createRegularStyleSheet,
FakeStyleElement,
toValue,
type TransformValue,
} from "@webstudio-is/css-engine";
import {
FONT_FORMATS,
getFontFaces,
type FontFormat,
} from "@webstudio-is/fonts";
import {
getAssetUrl,
type Asset,
type Breakpoint,
type WebstudioFragment,
} from "@webstudio-is/sdk";
import * as cssTree from "css-tree";
import { parseWebstudioPragma } from "./webstudio-pragma";
import {
mapCssValueUrls,
mapParsedCssStyles,
traverseStyleValue,
} from "../style-utils";
const tokenId = "clipboard-token";
const rootId = "clipboard-root";
const baseId = "clipboard-base";
export type TokenTransferData = {
tokenId: string;
fragment: WebstudioFragment;
sourceOrigin?: string;
};
export const serializeTokenCss = (data: TokenTransferData): string => {
const { fragment, sourceOrigin } = data;
const token = fragment.styleSources.find(
(source) => source.id === data.tokenId
);
if (token?.type !== "token") {
throw new Error("Invalid token data");
}
const sheet = createRegularStyleSheet({ element: new FakeStyleElement() });
const assets = new Map(fragment.assets.map((asset) => [asset.id, asset]));
const transformValue: TransformValue = (value) => {
if (value.type === "unparsed" && sourceOrigin !== undefined) {
const rebased = mapCssValueUrls(value.value, (url) => {
try {
return new URL(url, sourceOrigin).href;
} catch {
return;
}
});
if (rebased !== value.value) {
return { ...value, value: rebased };
}
}
if (value.type !== "image" || value.value.type !== "asset") {
return;
}
const asset = assets.get(value.value.value);
if (asset === undefined) {
return;
}
const url = getAssetUrl(asset, sourceOrigin ?? "https://webstudio.invalid");
return {
type: "image",
value: {
type: "url",
url: sourceOrigin ? url.href : url.pathname + url.search,
},
hidden: value.hidden,
};
};
sheet.setTransformer(transformValue);
for (const breakpoint of fragment.breakpoints) {
sheet.addMediaRule(breakpoint.id, breakpoint);
}
const tokenMixin = sheet.addMixinRule(data.tokenId);
const rootMixin = sheet.addMixinRule(rootId);
for (const style of fragment.styles) {
(style.styleSourceId === data.tokenId
? tokenMixin
: rootMixin
).setDeclaration({
breakpoint: style.breakpointId,
selector: style.state ?? "",
property: style.property,
value: style.value,
});
}
sheet.addNestingRule(":root").applyMixins([rootId]);
sheet.addNestingRule(".ws-token").applyMixins([data.tokenId]);
const fonts = fragment.assets.filter((asset) => asset.type === "font");
for (const face of getFontFaces(fonts, {
assetBaseUrl: sourceOrigin ? `${sourceOrigin}/cgi/asset/` : "/cgi/asset/",
})) {
sheet.addFontFaceRule(face);
}
const name = JSON.stringify(token.name).replaceAll("*/", "*\\/");
return `/* @webstudio/token-css/v1 ${name} */\n${sheet.cssText}`;
};
type ParsedTokenCss =
| { owned: false; valid: false }
| { owned: true; valid: false }
| { owned: true; valid: true; data: TokenTransferData };
const assetFromUrl = (
urlText: string,
type: "image" | "font",
fontMeta?: {
family: string;
style: "normal" | "italic" | "oblique";
weight: number;
}
): Asset | undefined => {
let url: URL;
try {
url = new URL(urlText, "https://webstudio.invalid");
} catch {
return;
}
if (
url.pathname.startsWith("/cgi/image/") === false &&
url.pathname.startsWith("/cgi/asset/") === false
) {
return;
}
let name: string;
try {
name = decodeURIComponent(url.pathname.split("/").at(-1) ?? "");
} catch {
return;
}
if (name === "") {
return;
}
const format = name.slice(name.lastIndexOf(".") + 1).toLowerCase();
const common = {
id: url.href,
projectId: "",
size: 0,
name,
description: null,
createdAt: "",
};
if (type === "font") {
if (
FONT_FORMATS.has(format as FontFormat) === false ||
fontMeta === undefined
) {
return;
}
return { ...common, type, format: format as FontFormat, meta: fontMeta };
}
return { ...common, type, format, meta: { width: 0, height: 0 } };
};
export const parseTokenTransferData = (source: string): ParsedTokenCss => {
const pragma = parseWebstudioPragma({
source,
syntax: "css",
namespace: "token-css",
});
if (pragma.valid === false) {
return pragma;
}
if (
pragma.version !== "v1" ||
pragma.value === undefined ||
source.slice(0, pragma.start).trim() !== ""
) {
return { owned: true, valid: false };
}
const body = source.slice(pragma.end);
let syntaxError = false;
const ast = cssTree.parse(body, {
positions: true,
onParseError: () => {
syntaxError = true;
},
});
const fonts: Asset[] = [];
const visit = (
nodes: cssTree.List<cssTree.CssNode>,
inMedia = false
): boolean =>
nodes.toArray().every((node) => {
if (node.type === "Rule") {
const rootSelector =
node.prelude.type === "SelectorList" &&
node.prelude.children
.toArray()
.every(
(item) =>
item.type === "Selector" &&
item.children.first?.type === "PseudoClassSelector" &&
item.children.first.name === "root"
);
const tokenSelector =
node.prelude.type === "SelectorList" &&
node.prelude.children
.toArray()
.every(
(item) =>
item.type === "Selector" &&
item.children.first?.type === "ClassSelector" &&
item.children.first.name === "ws-token"
);
return node.block !== null && (rootSelector || tokenSelector);
}
if (node.type !== "Atrule" || node.block === null || inMedia) {
return false;
}
if (node.name.toLowerCase() === "media") {
return visit(node.block.children, true);
}
if (node.name.toLowerCase() === "font-face") {
const declarations = new Map<string, cssTree.Declaration>();
node.block.children.forEach((child) => {
if (child.type === "Declaration") {
declarations.set(child.property.toLowerCase(), child);
}
});
const familyText = declarations.get("font-family")?.value;
const familyPart =
familyText?.type === "Value" && familyText.children.size === 1
? familyText.children.first
: undefined;
const family =
familyPart?.type === "String"
? familyPart.value
: familyText
? cssTree.generate(familyText)
: "";
const styleText = declarations.get("font-style")?.value;
const style = styleText ? cssTree.generate(styleText) : "normal";
const weightText = declarations.get("font-weight")?.value;
let weight = 400;
let foundWeight = false;
if (weightText !== undefined) {
cssTree.walk(weightText, (part) => {
if (part.type === "Number" && !foundWeight) {
weight = Number(part.value);
foundWeight = true;
}
});
}
const src = declarations.get("src")?.value;
if (
family === "" ||
(style !== "normal" && style !== "italic" && style !== "oblique") ||
Number.isFinite(weight) === false ||
src === undefined
) {
return false;
}
let foundUrl = false;
let validUrls = true;
cssTree.walk(src, (node) => {
if (node.type !== "Url") {
return;
}
foundUrl = true;
const asset = assetFromUrl(node.value, "font", {
family,
style,
weight,
});
if (asset === undefined) {
validUrls = false;
} else {
fonts.push(asset);
}
});
return foundUrl && validUrls;
}
return false;
});
if (ast.type !== "StyleSheet") {
return { owned: true, valid: false };
}
if (syntaxError || !visit(ast.children)) {
return { owned: true, valid: false };
}
const parsed = parseCss(body, extractCssCustomProperties(body, ast), ast, {
preserveShorthandVariables: true,
preserveNonPixelWidth: true,
parseSelector: (selector) => {
const name =
selector.children.first?.type === "PseudoClassSelector"
? ":root"
: ".ws-token";
return {
name,
state: cssTree.generate(selector).slice(name.length) || undefined,
};
},
});
if (
parsed.errors.length > 0 ||
parsed.styles.some(
(style) => style.selector === ":root" && !style.property.startsWith("--")
)
) {
return { owned: true, valid: false };
}
const breakpoints = new Map<string, Breakpoint>();
breakpoints.set(baseId, { id: baseId, label: "Base" });
const assets = new Map<string, Asset>(
fonts.map((asset) => [asset.id, asset])
);
let sourceOrigin: string | undefined;
let invalidBreakpoint = false;
const styles = mapParsedCssStyles(parsed.styles, (style) => {
const breakpointId = style.breakpoint ?? baseId;
if (!breakpoints.has(breakpointId)) {
const media =
parseMediaQuery(breakpointId, { preserveNonPixelWidth: true }) ??
(breakpointId.startsWith("(") && breakpointId.endsWith(")")
? { condition: breakpointId.slice(1, -1) }
: undefined);
if (media === undefined) {
invalidBreakpoint = true;
return;
}
const representedQuery =
media.condition === undefined
? [
media.minWidth === undefined
? undefined
: `(min-width:${media.minWidth}px)`,
media.maxWidth === undefined
? undefined
: `(max-width:${media.maxWidth}px)`,
]
.filter(Boolean)
.join(" and ")
: `(${media.condition})`;
breakpoints.set(breakpointId, {
id: breakpointId,
label: breakpointId,
...(breakpointId !== representedQuery
? {
condition: breakpointId.startsWith("(")
? breakpointId.slice(1, -1)
: breakpointId,
}
: media),
});
}
const value = structuredClone(
style.value.type === "var"
? { type: "unparsed" as const, value: toValue(style.value) }
: style.value
);
traverseStyleValue(value, (item) => {
if (item.type === "image" && item.value.type === "url") {
const asset = assetFromUrl(item.value.url, "image");
if (asset !== undefined) {
assets.set(asset.id, asset);
item.value = { type: "asset", value: asset.id };
}
}
if (item.type === "unparsed") {
mapCssValueUrls(item.value, (url) => {
const asset = assetFromUrl(url, "image");
if (asset !== undefined) {
assets.set(asset.id, asset);
}
return;
});
}
});
const isRoot = style.selector === ":root";
return {
styleSourceId: isRoot ? rootId : tokenId,
breakpointId,
value,
state: style.state,
};
});
if (invalidBreakpoint) {
return { owned: true, valid: false };
}
for (const asset of assets.values()) {
const url = new URL(asset.id);
if (url.hostname !== "webstudio.invalid") {
if (sourceOrigin !== undefined && sourceOrigin !== url.origin) {
return { owned: true, valid: false };
}
sourceOrigin = url.origin;
}
}
const fragment: WebstudioFragment = {
children: [],
instances: [],
props: [],
dataSources: [],
resources: [],
styleSourceSelections: [],
styleSources: [{ type: "token", id: tokenId, name: pragma.value }],
styles,
breakpoints: [...breakpoints.values()],
assets: [...assets.values()],
};
return {
owned: true,
valid: true,
data: { tokenId, fragment, sourceOrigin },
};
};
@@ -0,0 +1,57 @@
import { expect, test } from "vitest";
import { parseWebstudioPragma } from "./webstudio-pragma";
test("reads the same Webstudio pragma in HTML and CSS comments", () => {
expect(
parseWebstudioPragma({
source: "<div></div><!-- @webstudio/inception/1 -->",
syntax: "html",
namespace: "inception",
})
).toMatchObject({ owned: true, valid: true, version: "1" });
expect(
parseWebstudioPragma({
source:
'/* @webstudio/token-css/v1 "Button" */\n.ws-token { color: red; }',
syntax: "css",
namespace: "token-css",
})
).toMatchObject({
owned: true,
valid: true,
version: "v1",
value: "Button",
});
});
test("keeps other comments separate and rejects malformed owned pragmas", () => {
expect(
parseWebstudioPragma({
source: "/* ordinary */ .box { color: red; }",
syntax: "css",
namespace: "token-css",
})
).toEqual({ owned: false, valid: false });
expect(
parseWebstudioPragma({
source:
'.box::before { content: "/* @webstudio/token-css/v1 \\"Fake\\" */"; }',
syntax: "css",
namespace: "token-css",
})
).toEqual({ owned: false, valid: false });
expect(
parseWebstudioPragma({
source: '<div title="<!-- @webstudio/inception/1 -->"></div>',
syntax: "html",
namespace: "inception",
})
).toEqual({ owned: false, valid: false });
expect(
parseWebstudioPragma({
source: '/* @webstudio/token-css/v1 "Broken */',
syntax: "css",
namespace: "token-css",
})
).toMatchObject({ owned: true, valid: false });
});
@@ -0,0 +1,108 @@
import * as cssTree from "css-tree";
import { parseFragment } from "parse5";
type CommentSyntax = "html" | "css";
type PragmaResult =
| { owned: false; valid: false }
| { owned: true; valid: false }
| {
owned: true;
valid: true;
version: string;
value?: string;
start: number;
end: number;
};
type Comment = { content: string; start: number; end: number; closed: boolean };
const getComments = (source: string, syntax: CommentSyntax): Comment[] => {
const comments: Comment[] = [];
if (syntax === "css") {
cssTree.parse(source, {
positions: true,
onComment: (content, location) => {
if (location === null) {
return;
}
comments.push({
content,
start: location.start.offset,
end: location.end.offset,
closed:
source.slice(location.end.offset - 2, location.end.offset) === "*/",
});
},
});
return comments;
}
const fragment = parseFragment(source, { sourceCodeLocationInfo: true });
const visit = (
node: typeof fragment | (typeof fragment.childNodes)[number]
) => {
if ("data" in node && node.sourceCodeLocation) {
comments.push({
content: node.data,
start: node.sourceCodeLocation.startOffset,
end: node.sourceCodeLocation.endOffset,
closed:
source.slice(
node.sourceCodeLocation.endOffset - 3,
node.sourceCodeLocation.endOffset
) === "-->",
});
}
if ("childNodes" in node) {
for (const child of node.childNodes) {
visit(child);
}
}
if ("content" in node) {
visit(node.content);
}
};
visit(fragment);
return comments;
};
export const parseWebstudioPragma = ({
source,
syntax,
namespace,
}: {
source: string;
syntax: CommentSyntax;
namespace: string;
}): PragmaResult => {
const prefix = `@webstudio/${namespace}/`;
for (const comment of getComments(source, syntax)) {
const content = comment.content.trim();
if (content.startsWith(prefix) === false) {
continue;
}
if (!comment.closed) {
return { owned: true, valid: false };
}
const parsed =
/^@webstudio\/[a-z-]+\/(v?\d+(?:\.\d+)?)(?:\s+("(?:\\.|[^"\\])*"))?$/.exec(
content
);
if (parsed === null) {
return { owned: true, valid: false };
}
try {
return {
owned: true,
valid: true,
version: parsed[1],
value: parsed[2] === undefined ? undefined : JSON.parse(parsed[2]),
start: comment.start,
end: comment.end,
};
} catch {
return { owned: true, valid: false };
}
}
return { owned: false, valid: false };
};
@@ -2,6 +2,9 @@
// Webstudio fragments. Put serialization-style instance subtree cloning and
// fragment asset/style/data remapping here, not live tree placement decisions.
import { migrateCodeTextContentMutable } from "@webstudio-is/project-migrations";
import { parseCssValue } from "@webstudio-is/css-data";
import { toValue } from "@webstudio-is/css-engine";
import { produce } from "immer";
import {
createId,
type Asset,
@@ -21,6 +24,7 @@ import {
findTreeInstanceIds,
findTreeInstanceIdsExcludingSlotDescendants,
getStyleDeclKey,
getAssetUrl,
getHomePage,
isFormSubmission,
portalComponent,
@@ -53,7 +57,9 @@ import {
} from "./style-copy";
import { unwrap } from "./unwrap";
import {
collectFontFamiliesFromStyleDecls,
collectFontFamiliesFromStyleValue,
mapCssValueUrls,
traverseStyleValue,
} from "./style-utils";
import { countDataSourceAssetReferences } from "./assets";
@@ -76,6 +82,158 @@ export const assertNoAmbiguousFormInstance = (
const createNanoId = () => createId("nano");
export const remapFragmentAssets = (
fragment: WebstudioFragment,
importedAssets: ReadonlyMap<Asset["id"], Asset>
) => {
const replacementIds = new Map<Asset["id"], Asset["id"]>();
const replacementUrls = new Map<string, string>();
const replacementFontFamilies = new Map<string, string>();
for (const sourceAsset of fragment.assets) {
const importedAsset = importedAssets.get(sourceAsset.id);
if (importedAsset === undefined) {
throw new Error("Imported asset is missing");
}
if (
sourceAsset.id === importedAsset.id &&
(sourceAsset.type !== "font" ||
importedAsset.type !== "font" ||
sourceAsset.meta.family === importedAsset.meta.family)
) {
continue;
}
if (sourceAsset.id !== importedAsset.id) {
if (sourceAsset.type === "image") {
const importedUrl = getAssetUrl(
importedAsset,
"https://webstudio.invalid"
);
replacementUrls.set(
new URL(sourceAsset.id, "https://webstudio.invalid").href,
importedUrl.pathname + importedUrl.search
);
}
for (const [sourceId, currentId] of replacementIds) {
if (currentId === sourceAsset.id) {
replacementIds.set(sourceId, importedAsset.id);
}
}
if (replacementIds.has(sourceAsset.id) === false) {
replacementIds.set(sourceAsset.id, importedAsset.id);
}
}
if (sourceAsset.type === "font" && importedAsset.type === "font") {
const from = sourceAsset.meta.family;
const to = importedAsset.meta.family;
if (from === to) {
continue;
}
for (const [original, current] of replacementFontFamilies) {
if (current === from) {
replacementFontFamilies.set(original, to);
}
}
if (replacementFontFamilies.has(from) === false) {
replacementFontFamilies.set(from, to);
}
}
}
const fontVariableStyleKeys = new Set<string>();
if (replacementFontFamilies.size > 0) {
collectFontFamiliesFromStyleDecls(fragment.styles, undefined, (style) => {
fontVariableStyleKeys.add(getStyleDeclKey(style));
});
}
return produce(fragment, (draft) => {
for (const prop of draft.props) {
if (prop.type === "asset") {
prop.value = replacementIds.get(prop.value) ?? prop.value;
}
}
for (const style of draft.styles) {
const isFontValue =
replacementFontFamilies.size > 0 &&
(style.property === "fontFamily" ||
fontVariableStyleKeys.has(getStyleDeclKey(style)));
traverseStyleValue(style.value, (item) => {
if (item.type === "image" && item.value.type === "asset") {
item.value.value =
replacementIds.get(item.value.value) ?? item.value.value;
}
if (replacementUrls.size > 0 && item.type === "unparsed") {
item.value = mapCssValueUrls(item.value, (url) => {
try {
return replacementUrls.get(
new URL(url, "https://webstudio.invalid").href
);
} catch {
return;
}
});
}
if (item.type === "fontFamily") {
const mapped = item.value.map(
(family) => replacementFontFamilies.get(family) ?? family
);
if (mapped.some((family, index) => family !== item.value[index])) {
item.value = mapped;
}
}
if (isFontValue && item.type === "unparsed") {
const parsed = parseCssValue("font-family", item.value);
let changed = false;
traverseStyleValue(parsed, (part) => {
if (part.type === "fontFamily") {
part.value = part.value.map((family) => {
const replacement = replacementFontFamilies.get(family);
changed ||= replacement !== undefined && replacement !== family;
return replacement ?? family;
});
}
});
if (changed) {
item.value = toValue(parsed);
}
}
});
}
draft.assets = [];
});
};
export const importFragmentAssets = async (
fragments: WebstudioFragment[],
importAssets: (assets: Asset[]) => Promise<Map<Asset["id"], Asset>>
) => {
const assets = new Map(
fragments.flatMap((fragment) =>
fragment.assets.map((asset) => [asset.id, asset] as const)
)
);
const importedAssets =
assets.size === 0
? new Map<Asset["id"], Asset>()
: await importAssets([...assets.values()]);
if (importedAssets.size !== assets.size) {
throw new Error("Imported asset is missing");
}
const assetIds = new Map(
[...importedAssets].map(([sourceId, asset]) => [sourceId, asset.id])
);
return {
fragments: new Map(
fragments.map((fragment) => [
fragment,
fragment.assets.length === 0
? fragment
: remapFragmentAssets(fragment, importedAssets),
])
),
assetIds,
assets: importedAssets,
};
};
export type ContentModeCopyableProp = (input: {
prop: Prop;
fragment: WebstudioFragment;
+50 -59
View File
@@ -15,7 +15,6 @@ import {
type StyleSourceSelection,
} from "@webstudio-is/sdk";
import {
camelCaseProperty,
parseCss,
extractCssCustomProperties,
parseClassBasedSelector,
@@ -33,6 +32,7 @@ import { ROOT_INSTANCE_ID } from "@webstudio-is/sdk";
import * as csstree from "css-tree";
import { titleCase } from "title-case";
import { getHtmlAttributeTypes } from "./html-attribute-utils";
import { mapParsedCssStyles } from "./style-utils";
type ElementNode = DefaultTreeAdapterMap["element"];
@@ -491,15 +491,15 @@ export const generateFragmentFromHtml = (
};
styleSources.push(localStyleSource);
styleSourceSelections.push({ instanceId, values: [localStyleSource.id] });
for (const { property, value } of parseCss(`.styles{${css}}`, new Map())
.styles) {
styles.push({
styleSourceId: localStyleSource.id,
breakpointId: getBaseBreakpointId(),
property: camelCaseProperty(property),
value,
});
}
styles.push(
...mapParsedCssStyles(
parseCss(`.styles{${css}}`, new Map()).styles,
() => ({
styleSourceId: localStyleSource.id,
breakpointId: getBaseBreakpointId(),
})
)
);
};
// ---- Pre-parse all <style> tags to extract class-based tokens ----
@@ -1031,52 +1031,46 @@ export const generateFragmentFromHtml = (
const decls =
classRules.get(className) ?? nestedClassRules.get(className)?.decls;
if (decls) {
for (const decl of decls) {
let breakpointId: string;
if (decl.breakpoint) {
const parsed = parseMediaQuery(decl.breakpoint);
if (parsed === undefined) {
continue;
}
const hasWidth =
parsed.minWidth !== undefined || parsed.maxWidth !== undefined;
const hasCondition = parsed.condition !== undefined;
if (hasCondition) {
const conditionParts: string[] = [];
if (parsed.minWidth !== undefined) {
conditionParts.push(`min-width:${parsed.minWidth}px`);
styles.push(
...mapParsedCssStyles(decls, (decl) => {
let breakpointId: string;
if (decl.breakpoint) {
const parsed = parseMediaQuery(decl.breakpoint);
if (parsed === undefined) {
return;
}
if (parsed.maxWidth !== undefined) {
conditionParts.push(`max-width:${parsed.maxWidth}px`);
const hasWidth =
parsed.minWidth !== undefined || parsed.maxWidth !== undefined;
if (parsed.condition !== undefined) {
const conditionParts: string[] = [];
if (parsed.minWidth !== undefined) {
conditionParts.push(`min-width:${parsed.minWidth}px`);
}
if (parsed.maxWidth !== undefined) {
conditionParts.push(`max-width:${parsed.maxWidth}px`);
}
conditionParts.push(parsed.condition);
breakpointId = getOrCreateBreakpoint({
condition: conditionParts.join(" and "),
});
} else if (hasWidth) {
breakpointId = getOrCreateBreakpoint({
...(parsed.minWidth !== undefined
? { minWidth: parsed.minWidth }
: {}),
...(parsed.maxWidth !== undefined
? { maxWidth: parsed.maxWidth }
: {}),
});
} else {
return;
}
// hasCondition guarantees parsed.condition is defined
conditionParts.push(parsed.condition as string);
breakpointId = getOrCreateBreakpoint({
condition: conditionParts.join(" and "),
});
} else if (hasWidth) {
breakpointId = getOrCreateBreakpoint({
...(parsed.minWidth !== undefined
? { minWidth: parsed.minWidth }
: {}),
...(parsed.maxWidth !== undefined
? { maxWidth: parsed.maxWidth }
: {}),
});
} else {
continue;
breakpointId = getBaseBreakpointId();
}
} else {
breakpointId = getBaseBreakpointId();
}
styles.push({
styleSourceId,
breakpointId,
property: camelCaseProperty(decl.property),
value: decl.value,
...(decl.state ? { state: decl.state } : {}),
});
}
return { styleSourceId, breakpointId };
})
);
}
}
@@ -1088,15 +1082,12 @@ export const generateFragmentFromHtml = (
instanceId: ROOT_INSTANCE_ID,
values: [rootStyleSourceId],
});
for (const decl of rootRules) {
styles.push({
styles.push(
...mapParsedCssStyles(rootRules, () => ({
styleSourceId: rootStyleSourceId,
breakpointId: getBaseBreakpointId(),
property: camelCaseProperty(decl.property),
value: decl.value,
...(decl.state ? { state: decl.state } : {}),
});
}
}))
);
}
// Create style source selections for instances that use tokens
@@ -659,6 +659,8 @@ export const runtimeOutputSchemas = {
"styles.deleteSelectedDeclarations": styleKeysResult,
"styles.replaceValues": styleKeysResult,
"designTokens.list": looseObject({ tokens: z.array(token), ...outputPage }),
"designTokens.copy": looseObject({ data: z.string() }),
"designTokens.paste": looseObject({ tokenId: id }),
"designTokens.create": looseObject({ tokenIds: stringArray }),
"designTokens.import": looseObject({
plan: z.array(designTokenImportPlanEntrySchema),
@@ -2668,6 +2668,7 @@ describe("builder runtime registry", () => {
["styles.updateSelectedDeclarations", { updates: {} }],
["styles.deleteSelectedDeclarations", { deletions: {} }],
["styles.replaceValues", {}],
["designTokens.paste", {}],
["designTokens.create", { tokens: {} }],
["designTokens.import", {}],
["designTokens.createAttached", { tokens: {}, instanceIds: [] }],
@@ -42,6 +42,7 @@ import * as slot from "./slot";
import * as designTokenImport from "./design-token-import";
import * as audit from "./audit";
import * as styles from "./styles";
import * as tokenTransfer from "./token-transfer";
import {
getZodValidationIssues,
throwBuilderRuntimeError,
@@ -1850,6 +1851,34 @@ export const builderRuntimeOperations = [
designTokenListInput,
({ state, input }) => styles.listDesignTokens(state, input)
),
runtimeOperation(
"designTokens.copy",
api("copy-design-token", "copyDesignToken"),
readContract(["assets", "breakpoints", ...styleNamespaces]),
tokenTransfer.copyDesignTokenInput,
({ state, input }) => tokenTransfer.copyDesignToken(state, input)
),
runtimeOperation(
"designTokens.paste",
api("paste-design-token", "pasteDesignToken"),
mutationContract({
readNamespaces: [
"assets",
"breakpoints",
"instances",
...styleNamespaces,
],
writeNamespaces: [
"breakpoints",
"styleSources",
"styles",
"styleSourceSelections",
],
}),
tokenTransfer.pasteDesignTokenInput,
({ state, input, context }) =>
tokenTransfer.pasteDesignToken(state, input, context)
),
runtimeOperation(
"designTokens.create",
api("create-design-token", "createDesignTokens"),
@@ -11,11 +11,20 @@ import {
collectFontFamiliesFromStyleValue,
getUniqueNameWithSuffix,
isAutoGridPlacement,
mapCssValueUrls,
resetGridChildPlacement,
serializeStyleDeclarations,
traverseStyleValue,
} from "./style-utils";
test("maps image URLs inside raw variable fallbacks", () => {
expect(
mapCssValueUrls('var(--missing, url("/cgi/image/source.svg"))', (url) =>
url === "/cgi/image/source.svg" ? "/cgi/image/target.svg" : undefined
)
).toContain("/cgi/image/target.svg");
});
test("creates a unique name after the highest numeric suffix", () => {
expect(
getUniqueNameWithSuffix("color", [
@@ -1,5 +1,11 @@
import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";
import { parseCssValue } from "@webstudio-is/css-data";
import {
camelCaseProperty,
cssTryParseValue,
parseCssValue,
type ParsedStyleDecl,
} from "@webstudio-is/css-data";
import { generate, walk, type CssNode } from "css-tree";
import type {
Instance,
Styles,
@@ -36,6 +42,99 @@ export const getUniqueNameWithSuffix = (
return `${name}-${maxCounter + 1}`;
};
export const mapParsedCssStyles = (
declarations: Iterable<ParsedStyleDecl>,
getContext: (
declaration: ParsedStyleDecl
) =>
| (Pick<StyleDecl, "styleSourceId" | "breakpointId"> &
Partial<Pick<StyleDecl, "value" | "state">>)
| undefined
): StyleDecl[] => {
const styles: StyleDecl[] = [];
for (const declaration of declarations) {
const context = getContext(declaration);
if (context === undefined) {
continue;
}
styles.push({
property: camelCaseProperty(declaration.property),
value: declaration.value,
...(declaration.state ? { state: declaration.state } : {}),
...context,
});
}
return styles;
};
const mapCssValueNodes = (
value: string,
mapNode: (node: CssNode) => boolean
) => {
const active = new Set<string>();
const map = (text: string): string => {
if (active.has(text)) {
return text;
}
active.add(text);
const parsed = cssTryParseValue(text);
if (parsed === undefined) {
active.delete(text);
return text;
}
let changed = false;
walk(parsed, (node) => {
changed = mapNode(node) || changed;
if (node.type === "Raw") {
const replacement = map(node.value);
if (replacement !== node.value) {
node.value = replacement;
changed = true;
}
}
});
active.delete(text);
return changed ? generate(parsed) : text;
};
return map(value);
};
export const mapCssValueUrls = (
value: string,
mapUrl: (url: string) => string | undefined
) =>
mapCssValueNodes(value, (node) => {
if (node.type !== "Url") {
return false;
}
const replacement = mapUrl(node.value);
if (replacement === undefined || replacement === node.value) {
return false;
}
node.value = replacement;
return true;
});
export const mapCssValueVariables = (
value: string,
mapName: (name: string) => string | undefined
) =>
mapCssValueNodes(value, (node) => {
if (node.type !== "Function" || node.name !== "var") {
return false;
}
const name = node.children.first;
if (name?.type !== "Identifier" || !name.name.startsWith("--")) {
return false;
}
const replacement = mapName(name.name);
if (replacement === undefined || replacement === name.name) {
return false;
}
name.name = replacement;
return true;
});
export const traverseStyleValue = (
value: StyleValue,
callback: (value: StyleValue) => void
@@ -109,15 +208,16 @@ export const collectFontFamiliesFromStyleDecls = <
family: string,
styleDecl: Declaration,
fromVariable: boolean
) => void
) => void,
onVariableDefinition?: (styleDecl: Declaration) => void
) => {
const fontFamilies = new Set<string>();
const customProperties = new Map<string, StyleValue[]>();
const customProperties = new Map<string, Declaration[]>();
const declarations = Array.from(styles);
for (const styleDecl of declarations) {
if (styleDecl.property?.startsWith("--")) {
const values = customProperties.get(styleDecl.property) ?? [];
values.push(styleDecl.value);
values.push(styleDecl);
customProperties.set(styleDecl.property, values);
}
}
@@ -152,7 +252,8 @@ export const collectFontFamiliesFromStyleDecls = <
}
visitedVariables.add(name);
for (const definition of customProperties.get(name) ?? []) {
collectFromVariable(definition, true);
onVariableDefinition?.(definition);
collectFromVariable(definition.value, true);
}
}
});
@@ -572,6 +572,9 @@ describe("css variable usage", () => {
expect(collectCssVariableReferences("var(--special-$name)", regex)).toEqual(
new Set(["--special-$name"])
);
expect(
collectCssVariableReferences("var(--ancestor, var(--fallback))")
).toEqual(new Set(["--ancestor", "--fallback"]));
});
test("finds css variable definitions and references", () => {
+8 -1
View File
@@ -42,7 +42,10 @@ import { getInstanceDepths } from "./instances";
import { addZodValidationIssue, throwBuilderRuntimeError } from "./errors";
import { runtimeGeneratedIdInput } from "./generated-id-input";
import { createRuntimeMutation } from "./mutation";
import { serializeStyleDeclarations } from "./style-utils";
import {
mapCssValueVariables,
serializeStyleDeclarations,
} from "./style-utils";
import { createPropValue } from "./props";
import { getStyleSourceStylesSignature } from "./style-copy";
import { isBaseWidthBreakpoint } from "./breakpoints";
@@ -425,6 +428,10 @@ export const createCssVariableNamesRegex = (names: Set<string>) => {
export const collectCssVariableReferences = (value: string, regex?: RegExp) => {
const references = new Set<string>();
if (regex === undefined) {
mapCssValueVariables(value, (name) => {
references.add(name);
return;
});
return references;
}
regex.lastIndex = 0;
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,417 @@
import { toValue } from "@webstudio-is/css-engine";
import {
createId,
getStyleDeclKey,
ROOT_INSTANCE_ID,
type Asset,
type StyleDecl,
type StyleSource,
type WebstudioFragment,
} from "@webstudio-is/sdk";
import type { StyleValue } from "@webstudio-is/css-engine";
import { z } from "zod";
import type { BuilderState } from "../state/builder-state";
import type { BuilderPatchChange } from "../contracts/patch";
import { buildMergedBreakpointIds, maxBreakpoints } from "./breakpoints";
import { calculateUsagesByAssetId } from "./assets";
import { createCopyName } from "./copy-name";
import { throwBuilderRuntimeError } from "./errors";
import { createRuntimeMutation } from "./mutation";
import { remapFragmentAssets } from "./fragment";
import {
collectCssVariableReferences,
createStyleSourceSelectionAttachPayload,
} from "./styles";
import {
getUniqueNameWithSuffix,
mapCssValueVariables,
traverseStyleValue,
} from "./style-utils";
import {
parseTokenTransferData,
serializeTokenCss,
} from "./data-formats/token-css";
type TokenState = Pick<
BuilderState,
| "assets"
| "breakpoints"
| "instances"
| "styleSources"
| "styleSourceSelections"
| "styles"
>;
const requireTokenState = (state: TokenState) => {
if (
state.assets === undefined ||
state.breakpoints === undefined ||
state.styleSources === undefined ||
state.styleSourceSelections === undefined ||
state.styles === undefined
) {
return throwBuilderRuntimeError("BAD_REQUEST", "Token data is missing");
}
return state as Required<TokenState>;
};
export const copyDesignTokenInput = z.object({
tokenId: z.string(),
sourceOrigin: z.string().url().optional(),
});
export const pasteDesignTokenInput = z.object({
data: z.string(),
instanceId: z.string().optional(),
assetIds: z.array(z.tuple([z.string(), z.string()])).optional(),
});
const rewriteVariableReferences = (
value: StyleValue,
replacements: Record<string, string>
) => {
if (Object.keys(replacements).length === 0) {
return value;
}
const rewritten = structuredClone(value);
traverseStyleValue(rewritten, (item) => {
if (item.type === "var") {
item.value = replacements[`--${item.value}`]?.slice(2) ?? item.value;
}
if (item.type === "unparsed") {
item.value = mapCssValueVariables(
item.value,
(name) => replacements[name]
);
}
});
return rewritten;
};
export const copyDesignToken = (
state: TokenState,
input: z.infer<typeof copyDesignTokenInput>
) => {
const { assets, breakpoints, styleSources, styleSourceSelections, styles } =
requireTokenState(state);
const token = styleSources.get(input.tokenId);
if (token?.type !== "token") {
return throwBuilderRuntimeError("NOT_FOUND", "Design token not found");
}
const tokenStyles = Array.from(styles.values()).filter(
(style) => style.styleSourceId === token.id
);
const rootSourceOrder = new Map(
styleSourceSelections
.get(ROOT_INSTANCE_ID)
?.values.map((id, index) => [id, index] as const)
);
const rootStylesByKey = new Map<string, StyleDecl>();
for (const style of styles.values()) {
if (
rootSourceOrder.has(style.styleSourceId) === false ||
style.property.startsWith("--") === false
) {
continue;
}
const key = getStyleDeclKey({ ...style, styleSourceId: ROOT_INSTANCE_ID });
const previous = rootStylesByKey.get(key);
if (
previous === undefined ||
rootSourceOrder.get(style.styleSourceId)! >
rootSourceOrder.get(previous.styleSourceId)!
) {
rootStylesByKey.set(key, style);
}
}
const rootStyles = Array.from(rootStylesByKey.values());
const variableNames = new Set<string>(
rootStyles.map((style) => style.property)
);
const referencedNames = new Set<string>();
const queue = [...tokenStyles];
while (queue.length > 0) {
const style = queue.shift()!;
for (const name of collectCssVariableReferences(toValue(style.value))) {
if (variableNames.has(name) === false || referencedNames.has(name)) {
continue;
}
referencedNames.add(name);
queue.push(...rootStyles.filter((style) => style.property === name));
}
}
const variableStyles = rootStyles
.filter((style) => referencedNames.has(style.property))
.map((style) =>
style.styleSourceId === token.id
? { ...style, styleSourceId: ROOT_INSTANCE_ID }
: style
);
const copiedStyles = [...tokenStyles, ...variableStyles];
const breakpointIds = new Set(
copiedStyles.map((style) => style.breakpointId)
);
const copiedBreakpoints = Array.from(breakpoints.values()).filter(
(breakpoint) => breakpointIds.has(breakpoint.id)
);
if (copiedBreakpoints.length !== breakpointIds.size) {
return throwBuilderRuntimeError("NOT_FOUND", "Token breakpoint is missing");
}
const usedAssets = calculateUsagesByAssetId({
pages: undefined,
props: new Map(),
styles: new Map(
copiedStyles.map((style) => [getStyleDeclKey(style), style])
),
assets,
});
const fragment: WebstudioFragment = {
children: [],
instances: [],
props: [],
dataSources: [],
resources: [],
styleSourceSelections: [],
styleSources: [token],
styles: copiedStyles,
breakpoints: copiedBreakpoints,
assets: Array.from(assets.values()).filter((asset) =>
usedAssets.has(asset.id)
),
};
for (const assetId of usedAssets.keys()) {
if (assets.has(assetId) === false) {
return throwBuilderRuntimeError("NOT_FOUND", "Token asset is missing");
}
}
return {
data: serializeTokenCss({
tokenId: token.id,
fragment,
sourceOrigin: input.sourceOrigin,
}),
};
};
export const pasteDesignToken = (
state: TokenState,
input: z.infer<typeof pasteDesignTokenInput>,
context: { createId: () => string } = { createId: () => createId("nano") }
) => {
const target = requireTokenState(state);
const parsed = parseTokenTransferData(input.data);
if (parsed.valid === false) {
return throwBuilderRuntimeError("INVALID_INPUT", "Invalid token data");
}
const { tokenId } = parsed.data;
let { fragment } = parsed.data;
const sourceToken = fragment.styleSources[0];
if (sourceToken?.type !== "token") {
return throwBuilderRuntimeError("INVALID_INPUT", "Invalid token data");
}
if (fragment.assets.length > 0) {
const assetIds = new Map(input.assetIds ?? []);
const importedAssets = new Map<Asset["id"], Asset>();
for (const source of fragment.assets) {
const imported = target.assets.get(assetIds.get(source.id) ?? source.id);
if (imported === undefined) {
return throwBuilderRuntimeError("NOT_FOUND", "Token asset is missing");
}
if (source.type !== imported.type) {
return throwBuilderRuntimeError(
"INVALID_INPUT",
"Token asset type changed"
);
}
importedAssets.set(source.id, imported);
}
fragment = remapFragmentAssets(fragment, importedAssets);
}
if (input.instanceId !== undefined) {
if (
target.instances === undefined ||
(input.instanceId !== ROOT_INSTANCE_ID &&
target.instances.has(input.instanceId) === false)
) {
return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");
}
}
// The CSS parser creates only token and root-variable styles with matching breakpoints.
const breakpointIds = buildMergedBreakpointIds(
fragment.breakpoints,
target.breakpoints
);
const newBreakpoints = fragment.breakpoints.filter(
(breakpoint) => breakpointIds.has(breakpoint.id) === false
);
if (target.breakpoints.size + newBreakpoints.length > maxBreakpoints + 1) {
return throwBuilderRuntimeError("CONFLICT", "Breakpoint limit reached");
}
const breakpointPatches: BuilderPatchChange["patches"] = [];
for (const breakpoint of newBreakpoints) {
const id = context.createId();
for (const [sourceId, mappedId] of breakpointIds) {
if (mappedId === breakpoint.id) {
breakpointIds.set(sourceId, id);
}
}
breakpointIds.set(breakpoint.id, id);
breakpointPatches.push({
op: "add",
path: [id],
value: { ...breakpoint, id },
});
}
const selection = target.styleSourceSelections.get(ROOT_INSTANCE_ID);
const sourceId = selection?.values.findLast(
(id) => target.styleSources.get(id)?.type === "local"
);
const rootSourceId = sourceId ?? context.createId();
const incomingVariables = fragment.styles.filter(
(style) => style.styleSourceId !== tokenId
);
const replacements: Record<string, string> = {};
const targetVariableNames = new Set<string>();
for (const style of target.styles.values()) {
if (style.property.startsWith("--")) {
targetVariableNames.add(style.property);
}
for (const name of collectCssVariableReferences(toValue(style.value))) {
targetVariableNames.add(name);
}
}
const tokenVariableNames = new Set<string>(
fragment.styles
.filter(
(style) =>
style.styleSourceId === tokenId && style.property.startsWith("--")
)
.map((style) => style.property)
);
const existingNames = new Set<string>([
...targetVariableNames,
...incomingVariables.map((style) => style.property),
...tokenVariableNames,
]);
for (const style of fragment.styles) {
for (const name of collectCssVariableReferences(toValue(style.value))) {
existingNames.add(name);
}
}
for (const style of incomingVariables) {
if (
targetVariableNames.has(style.property) &&
replacements[style.property] === undefined
) {
const renamed = getUniqueNameWithSuffix(style.property, existingNames);
replacements[style.property] = renamed;
existingNames.add(renamed);
}
}
const mappedStyles = fragment.styles.map((style) => ({
...style,
property: (replacements[style.property] ??
style.property) as StyleDecl["property"],
value: rewriteVariableReferences(style.value, replacements),
}));
const tokenNames = new Set(
Array.from(target.styleSources.values()).flatMap((source) =>
source.type === "token" ? [source.name] : []
)
);
const newTokenId = context.createId();
const newToken = {
...sourceToken,
id: newTokenId,
name: createCopyName(
sourceToken.name,
(name) => tokenNames.has(name),
true
),
};
const variablePatches: BuilderPatchChange["patches"] = [];
const tokenPatches: BuilderPatchChange["patches"] = [];
for (const style of mappedStyles) {
const mapped: StyleDecl = {
...style,
styleSourceId:
style.styleSourceId === tokenId ? newTokenId : rootSourceId,
breakpointId: breakpointIds.get(style.breakpointId) ?? style.breakpointId,
};
const key = getStyleDeclKey(mapped);
if (style.styleSourceId === tokenId) {
tokenPatches.push({ op: "add", path: [key], value: mapped });
} else if (target.styles.has(key) === false) {
variablePatches.push({ op: "add", path: [key], value: mapped });
}
}
const needsRootSource = sourceId === undefined && variablePatches.length > 0;
const sourcePatches: BuilderPatchChange["patches"] = [];
if (needsRootSource) {
sourcePatches.push({
op: "add",
path: [rootSourceId],
value: { type: "local", id: rootSourceId } satisfies StyleSource,
});
}
sourcePatches.push({
op: "add",
path: [newTokenId],
value: newToken,
});
const stylePatches = [...variablePatches, ...tokenPatches];
const payload: BuilderPatchChange[] = [];
if (breakpointPatches.length > 0) {
payload.push({ namespace: "breakpoints", patches: breakpointPatches });
}
payload.push({ namespace: "styleSources", patches: sourcePatches });
if (stylePatches.length > 0) {
payload.push({ namespace: "styles", patches: stylePatches });
}
if (needsRootSource) {
payload.push({
namespace: "styleSourceSelections",
patches: [
selection === undefined
? {
op: "add",
path: [ROOT_INSTANCE_ID],
value: { instanceId: ROOT_INSTANCE_ID, values: [rootSourceId] },
}
: {
op: "add",
path: [ROOT_INSTANCE_ID, "values", selection.values.length],
value: rootSourceId,
},
],
});
}
if (input.instanceId !== undefined) {
const selections = new Map(target.styleSourceSelections);
if (needsRootSource) {
selections.set(ROOT_INSTANCE_ID, {
instanceId: ROOT_INSTANCE_ID,
values: [...(selection?.values ?? []), rootSourceId],
});
}
payload.push(
...createStyleSourceSelectionAttachPayload({
instanceIds: [input.instanceId],
styleSourceSelections: selections.values(),
styleSources: new Map([...target.styleSources, [newTokenId, newToken]]),
styleSourceId: newTokenId,
})
);
}
return createRuntimeMutation({
payload,
result: { tokenId: newTokenId },
invalidatesNamespaces: [
"breakpoints",
"styleSources",
"styles",
"styleSourceSelections",
],
});
};
+2
View File
@@ -1,6 +1,8 @@
export * from "./runtime/data-formats/data-envelope";
export * from "./runtime/data-formats/instance-transfer";
export * from "./runtime/data-formats/page-transfer";
export * from "./runtime/data-formats/token-css";
export * from "./runtime/data-formats/webstudio-pragma";
export * from "./runtime/jsx/syntax";
export * from "./runtime/jsx/utils";
export * from "./runtime/webflow/instances-properties";
@@ -175,6 +175,7 @@ export const assetUploadReservationRequest = z.strictObject({
.string()
.regex(/^[a-f0-9]{64}$/)
.optional(),
sourceUrl: z.url().optional(),
});
/** Concrete query payload accepted by the Assets REST API. */