Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

feat: Resolve asset paths in HTML embeds (#6409)

Oleg Isonen18d171212f21
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsx
index 2b89cae275..fdef5f8e0e 100644
--- a/apps/builder/app/canvas/canvas.tsx
+++ b/apps/builder/app/canvas/canvas.tsx
@@ -8,7 +8,8 @@ import {
} from "react";
import { ErrorBoundary, type FallbackProps } from "react-error-boundary";
import { useStore } from "@nanostores/react";
-import { type Instances } from "@webstudio-is/sdk";
+import { type Instances, toRuntimeAsset } from "@webstudio-is/sdk";
+import { createAssetUrlsByPath } from "@webstudio-is/project-build/runtime";
import type { Components } from "@webstudio-is/react-sdk";
import { wsImageLoader, wsVideoLoader } from "@webstudio-is/image";
import { ReactSdkContext } from "@webstudio-is/react-sdk/runtime";
@@ -41,7 +42,7 @@ import {
subscribeModifierKeys,
assetBaseUrl,
} from "~/shared/nano-states";
-import { $assets } from "~/shared/sync/data-stores";
+import { $assetFolders, $assets } from "~/shared/sync/data-stores";
import { $pages, $instances, $breakpoints } from "~/shared/sync/data-stores";
import { useDragAndDrop } from "./shared/use-drag-drop";
import {
@@ -106,6 +107,8 @@ const useElementsTree = (components: Components, instances: Instances) => {
const page = useStore($selectedPage);
const isPreviewMode = useStore($isPreviewMode);
const breakpointsMap = useStore($breakpoints);
+ const assets = useStore($assets);
+ const assetFolders = useStore($assetFolders);
const rootInstanceId = page?.rootInstanceId ?? "";
if (typeof window === "undefined") {
@@ -122,6 +125,15 @@ const useElementsTree = (components: Components, instances: Instances) => {
() => [...breakpointsMap.values()].sort(compareMedia),
[breakpointsMap]
);
+ const assetUrlsByPath = useMemo(
+ () =>
+ createAssetUrlsByPath({
+ assets: assets.values(),
+ assetFolders,
+ getUrl: (asset) => toRuntimeAsset(asset, "https://webstudio.local").url,
+ }),
+ [assetFolders, assets]
+ );
return useMemo(() => {
return (
@@ -130,6 +142,7 @@ const useElementsTree = (components: Components, instances: Instances) => {
renderer: isPreviewMode ? "preview" : "canvas",
isSafeMode,
assetBaseUrl,
+ assetUrlsByPath,
imageLoader: wsImageLoader,
videoLoader: wsVideoLoader,
resources: {},
@@ -156,6 +169,7 @@ const useElementsTree = (components: Components, instances: Instances) => {
isPreviewMode,
breakpoints,
isSafeMode,
+ assetUrlsByPath,
]);
};
diff --git a/apps/builder/app/canvas/html-embed-assets.browser.test.tsx b/apps/builder/app/canvas/html-embed-assets.browser.test.tsx
new file mode 100644
index 0000000000..76d82cdbbe
--- /dev/null
+++ b/apps/builder/app/canvas/html-embed-assets.browser.test.tsx
@@ -0,0 +1,124 @@
+import { act } from "react-dom/test-utils";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, test } from "vitest";
+import { createAssetUrlsByPath } from "@webstudio-is/project-build/runtime";
+import { ReactSdkContext } from "@webstudio-is/react-sdk/runtime";
+import { type Asset, toRuntimeAsset } from "@webstudio-is/sdk";
+import { HtmlEmbed } from "@webstudio-is/sdk-components-react/components";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+test("resolves an asset-panel path through the Builder SDK context", async () => {
+ const assets = [
+ {
+ id: "script",
+ projectId: "project",
+ name: "test_hash.js",
+ filename: "test",
+ folderId: "scripts",
+ type: "file",
+ size: 1,
+ format: "js",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ description: null,
+ meta: {},
+ },
+ {
+ id: "stylesheet",
+ projectId: "project",
+ name: "site_hash.css",
+ filename: "site",
+ type: "file",
+ size: 1,
+ format: "css",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ description: null,
+ meta: {},
+ },
+ {
+ id: "image",
+ projectId: "project",
+ name: "hero_hash.png",
+ filename: "hero",
+ type: "image",
+ size: 1,
+ format: "png",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ description: null,
+ meta: { width: 100, height: 100 },
+ },
+ ] as Asset[];
+ const assetUrlsByPath = createAssetUrlsByPath({
+ assets,
+ assetFolders: new Map([
+ [
+ "scripts",
+ {
+ id: "scripts",
+ projectId: "project",
+ name: "Custom scripts",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ },
+ ],
+ ]),
+ getUrl: (asset) => toRuntimeAsset(asset, "https://webstudio.local").url,
+ });
+
+ await act(async () => {
+ root.render(
+ <ReactSdkContext.Provider
+ value={{
+ renderer: "canvas",
+ assetBaseUrl: "",
+ assetUrlsByPath,
+ imageLoader: ({ src }) => src,
+ resources: {},
+ breakpoints: [],
+ onError: (error) => {
+ throw error;
+ },
+ }}
+ >
+ <HtmlEmbed
+ code={`
+ <script src="/Custom scripts/test.js"></script>
+ <link rel="stylesheet" href="/site.css">
+ <img src="/hero.png">
+ `}
+ $ws$executeScripts={false}
+ />
+ </ReactSdkContext.Provider>
+ );
+ });
+
+ expect(assetUrlsByPath).toEqual({
+ "/Custom%20scripts/test.js": "/cgi/asset/test_hash.js?format=raw",
+ "/site.css": "/cgi/asset/site_hash.css?format=raw",
+ "/hero.png": "/cgi/image/hero_hash.png?format=raw",
+ });
+ expect(container.querySelector("script")?.getAttribute("src")).toBe(
+ "/cgi/asset/test_hash.js?format=raw"
+ );
+ expect(container.querySelector("link")?.getAttribute("href")).toBe(
+ "/cgi/asset/site_hash.css?format=raw"
+ );
+ expect(container.querySelector("img")?.getAttribute("src")).toBe(
+ "/cgi/image/hero_hash.png?format=raw"
+ );
+});
diff --git a/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.ts b/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.ts
index 352ec12362..8ecf9c6e25 100644
--- a/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.ts
+++ b/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.ts
@@ -39,4 +39,8 @@
"contentRef": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
}
};
+ export const assetUrlsByPath = {
+ "/iconly_svg_converted-converted.svg": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
+ "/147-1478573_cat-icon-png-black-cat-png-icon.png.jpeg": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
+};
\ No newline at end of file
diff --git a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx
index d44cc286db..864b48df2e 100644
--- a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/react-router-cloudflare/app/routes/_index.tsx b/fixtures/react-router-cloudflare/app/routes/_index.tsx
index 0b9d27d395..051857b2cd 100644
--- a/fixtures/react-router-cloudflare/app/routes/_index.tsx
+++ b/fixtures/react-router-cloudflare/app/routes/_index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/react-router-docker/app/__generated__/$resources.assets.ts b/fixtures/react-router-docker/app/__generated__/$resources.assets.ts
index 352ec12362..8ecf9c6e25 100644
--- a/fixtures/react-router-docker/app/__generated__/$resources.assets.ts
+++ b/fixtures/react-router-docker/app/__generated__/$resources.assets.ts
@@ -39,4 +39,8 @@
"contentRef": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
}
};
+ export const assetUrlsByPath = {
+ "/iconly_svg_converted-converted.svg": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
+ "/147-1478573_cat-icon-png-black-cat-png-icon.png.jpeg": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
+};
\ No newline at end of file
diff --git a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx b/fixtures/react-router-docker/app/routes/[another-page]._index.tsx
index d44cc286db..864b48df2e 100644
--- a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-docker/app/routes/[another-page]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/react-router-docker/app/routes/_index.tsx b/fixtures/react-router-docker/app/routes/_index.tsx
index 0b9d27d395..051857b2cd 100644
--- a/fixtures/react-router-docker/app/routes/_index.tsx
+++ b/fixtures/react-router-docker/app/routes/_index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/react-router-netlify/app/__generated__/$resources.assets.ts b/fixtures/react-router-netlify/app/__generated__/$resources.assets.ts
index 352ec12362..8ecf9c6e25 100644
--- a/fixtures/react-router-netlify/app/__generated__/$resources.assets.ts
+++ b/fixtures/react-router-netlify/app/__generated__/$resources.assets.ts
@@ -39,4 +39,8 @@
"contentRef": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
}
};
+ export const assetUrlsByPath = {
+ "/iconly_svg_converted-converted.svg": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
+ "/147-1478573_cat-icon-png-black-cat-png-icon.png.jpeg": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
+};
\ No newline at end of file
diff --git a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx
index d44cc286db..864b48df2e 100644
--- a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/react-router-netlify/app/routes/_index.tsx b/fixtures/react-router-netlify/app/routes/_index.tsx
index 0b9d27d395..051857b2cd 100644
--- a/fixtures/react-router-netlify/app/routes/_index.tsx
+++ b/fixtures/react-router-netlify/app/routes/_index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/react-router-vercel/app/__generated__/$resources.assets.ts b/fixtures/react-router-vercel/app/__generated__/$resources.assets.ts
index 352ec12362..8ecf9c6e25 100644
--- a/fixtures/react-router-vercel/app/__generated__/$resources.assets.ts
+++ b/fixtures/react-router-vercel/app/__generated__/$resources.assets.ts
@@ -39,4 +39,8 @@
"contentRef": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
}
};
+ export const assetUrlsByPath = {
+ "/iconly_svg_converted-converted.svg": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
+ "/147-1478573_cat-icon-png-black-cat-png-icon.png.jpeg": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
+};
\ No newline at end of file
diff --git a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx
index d44cc286db..864b48df2e 100644
--- a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/react-router-vercel/app/routes/_index.tsx b/fixtures/react-router-vercel/app/routes/_index.tsx
index 0b9d27d395..051857b2cd 100644
--- a/fixtures/react-router-vercel/app/routes/_index.tsx
+++ b/fixtures/react-router-vercel/app/routes/_index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.ts b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.ts
index 352ec12362..8ecf9c6e25 100644
--- a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.ts
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.ts
@@ -39,4 +39,8 @@
"contentRef": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
}
};
+ export const assetUrlsByPath = {
+ "/iconly_svg_converted-converted.svg": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
+ "/147-1478573_cat-icon-png-black-cat-png-icon.png.jpeg": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
+};
\ No newline at end of file
diff --git a/fixtures/ssg-cloudflare-pages/pages/another-page/+Page.tsx b/fixtures/ssg-cloudflare-pages/pages/another-page/+Page.tsx
index 9dd77cf5e3..3359a47b81 100644
--- a/fixtures/ssg-cloudflare-pages/pages/another-page/+Page.tsx
+++ b/fixtures/ssg-cloudflare-pages/pages/another-page/+Page.tsx
@@ -7,6 +7,7 @@ import {
} from "@webstudio-is/react-sdk/runtime";
import { LinkCurrentUrlContext } from "@webstudio-is/sdk-components-react";
import { assetBaseUrl, imageLoader } from "../../app/constants.mjs";
+import { assetUrlsByPath } from "../../app/__generated__/$resources.assets";
import {
Page,
breakpoints,
@@ -36,6 +37,7 @@ const PageComponent = ({ data }: { data: PageContext["data"] }) => {
() => ({
imageLoader,
assetBaseUrl,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/ssg-cloudflare-pages/pages/index/+Page.tsx b/fixtures/ssg-cloudflare-pages/pages/index/+Page.tsx
index f65c32c477..a035e6fd9c 100644
--- a/fixtures/ssg-cloudflare-pages/pages/index/+Page.tsx
+++ b/fixtures/ssg-cloudflare-pages/pages/index/+Page.tsx
@@ -7,6 +7,7 @@ import {
} from "@webstudio-is/react-sdk/runtime";
import { LinkCurrentUrlContext } from "@webstudio-is/sdk-components-react";
import { assetBaseUrl, imageLoader } from "../../app/constants.mjs";
+import { assetUrlsByPath } from "../../app/__generated__/$resources.assets";
import { Page, breakpoints, siteName } from "../../app/__generated__/_index";
const getPageKey = (url: string) => {
@@ -32,6 +33,7 @@ const PageComponent = ({ data }: { data: PageContext["data"] }) => {
() => ({
imageLoader,
assetBaseUrl,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.assets.ts b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.assets.ts
index 803ae11d57..2289f8d8ff 100644
--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.assets.ts
+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.assets.ts
@@ -1,3 +1,4 @@
export const assets = {};
+ export const assetUrlsByPath = {};
\ No newline at end of file
diff --git a/fixtures/ssg-netlify-by-project-id/pages/index/+Page.tsx b/fixtures/ssg-netlify-by-project-id/pages/index/+Page.tsx
index f65c32c477..a035e6fd9c 100644
--- a/fixtures/ssg-netlify-by-project-id/pages/index/+Page.tsx
+++ b/fixtures/ssg-netlify-by-project-id/pages/index/+Page.tsx
@@ -7,6 +7,7 @@ import {
} from "@webstudio-is/react-sdk/runtime";
import { LinkCurrentUrlContext } from "@webstudio-is/sdk-components-react";
import { assetBaseUrl, imageLoader } from "../../app/constants.mjs";
+import { assetUrlsByPath } from "../../app/__generated__/$resources.assets";
import { Page, breakpoints, siteName } from "../../app/__generated__/_index";
const getPageKey = (url: string) => {
@@ -32,6 +33,7 @@ const PageComponent = ({ data }: { data: PageContext["data"] }) => {
() => ({
imageLoader,
assetBaseUrl,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/ssg-netlify-by-project-id/pages/redirect/+Page.tsx b/fixtures/ssg-netlify-by-project-id/pages/redirect/+Page.tsx
index 25a295f44b..42caba38f6 100644
--- a/fixtures/ssg-netlify-by-project-id/pages/redirect/+Page.tsx
+++ b/fixtures/ssg-netlify-by-project-id/pages/redirect/+Page.tsx
@@ -7,6 +7,7 @@ import {
} from "@webstudio-is/react-sdk/runtime";
import { LinkCurrentUrlContext } from "@webstudio-is/sdk-components-react";
import { assetBaseUrl, imageLoader } from "../../app/constants.mjs";
+import { assetUrlsByPath } from "../../app/__generated__/$resources.assets";
import {
Page,
breakpoints,
@@ -36,6 +37,7 @@ const PageComponent = ({ data }: { data: PageContext["data"] }) => {
() => ({
imageLoader,
assetBaseUrl,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.ts b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.ts
index 352ec12362..8ecf9c6e25 100644
--- a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.ts
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.ts
@@ -39,4 +39,8 @@
"contentRef": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
}
};
+ export const assetUrlsByPath = {
+ "/iconly_svg_converted-converted.svg": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
+ "/147-1478573_cat-icon-png-black-cat-png-icon.png.jpeg": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
+};
\ No newline at end of file
diff --git a/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx
index 8ba1d66e4e..c7dde77853 100644
--- a/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx
@@ -46,6 +46,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -356,6 +357,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx
index 87b03a8a3d..ada034ef65 100644
--- a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx
@@ -46,6 +46,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -356,6 +357,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-features/app/__generated__/$resources.assets.ts b/fixtures/webstudio-features/app/__generated__/$resources.assets.ts
index a8c5284db1..38ec702446 100644
--- a/fixtures/webstudio-features/app/__generated__/$resources.assets.ts
+++ b/fixtures/webstudio-features/app/__generated__/$resources.assets.ts
@@ -131,4 +131,13 @@
"contentRef": "_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg"
}
};
+ export const assetUrlsByPath = {
+ "/e-mail-39993.mp3": "/assets/e-mail-39993_vrxyjxQv3j67Krs62Vz7Y.mp3",
+ "/cabinsketch-bold.ttf": "/assets/cabinsketch-bold_TLCbytfxf8ENHwZ6ze3Jj.ttf",
+ "/webm-example.webm": "/assets/webm-example_2r_6VmRBjhAy3ldaqz0gk.webm",
+ "/cat_silhouette.png": "/assets/cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png",
+ "/small-avif-kitty.webp": "/assets/small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp",
+ "/video_QamtUWsD-ShifhzZLoNIv.mp4": "/assets/video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4",
+ "/_937084ed-a798-49fe-8664-df93a2af605e.jpeg": "/assets/_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg"
+};
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx
index 8b9e13bb86..b5e950efc7 100644
--- a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-features/app/routes/[animations]._index.tsx b/fixtures/webstudio-features/app/routes/[animations]._index.tsx
index 535c941404..9641e3a34e 100644
--- a/fixtures/webstudio-features/app/routes/[animations]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[animations]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx b/fixtures/webstudio-features/app/routes/[assets1]._index.tsx
index 403bc792ef..93f42d008a 100644
--- a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[assets1]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx b/fixtures/webstudio-features/app/routes/[class-names]._index.tsx
index fba594a77b..95bb5689a2 100644
--- a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[class-names]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx b/fixtures/webstudio-features/app/routes/[content-block]._index.tsx
index 546175503b..381e5d90e9 100644
--- a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[content-block]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-features/app/routes/[duration]._index.tsx b/fixtures/webstudio-features/app/routes/[duration]._index.tsx
index 151ffbd878..c2ad4c7062 100644
--- a/fixtures/webstudio-features/app/routes/[duration]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[duration]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx b/fixtures/webstudio-features/app/routes/[expressions]._index.tsx
index 1eae8491cd..f7d84ace21 100644
--- a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[expressions]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-features/app/routes/[form]._index.tsx b/fixtures/webstudio-features/app/routes/[form]._index.tsx
index 89ff380174..e31ac374bc 100644
--- a/fixtures/webstudio-features/app/routes/[form]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[form]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx
index 77ee10baec..470c672ce1 100644
--- a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx
index 0d392a9473..d0cc06a97c 100644
--- a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx
index fd7be339c3..2b8ef1f132 100644
--- a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-features/app/routes/[radix]._index.tsx b/fixtures/webstudio-features/app/routes/[radix]._index.tsx
index c6e5b70c1b..afeacaf5c0 100644
--- a/fixtures/webstudio-features/app/routes/[radix]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[radix]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-features/app/routes/[resources]._index.tsx b/fixtures/webstudio-features/app/routes/[resources]._index.tsx
index 036104153e..f2bbcf969c 100644
--- a/fixtures/webstudio-features/app/routes/[resources]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[resources]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx
index fc5f1067d6..07745f4f33 100644
--- a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/fixtures/webstudio-features/app/routes/_index.tsx b/fixtures/webstudio-features/app/routes/_index.tsx
index 0b9d27d395..051857b2cd 100644
--- a/fixtures/webstudio-features/app/routes/_index.tsx
+++ b/fixtures/webstudio-features/app/routes/_index.tsx
@@ -45,6 +45,7 @@ import css from "../__generated__/index.css?url";
import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
+import { assetUrlsByPath } from "../__generated__/$resources.assets";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.ts
index 1da869d1a7..bfe65b9f12 100644
--- a/packages/cli/src/prebuild.test.ts
+++ b/packages/cli/src/prebuild.test.ts
@@ -1879,7 +1879,13 @@ sitemap.map((page) => page.path);`
"utf8"
);
expect(assetsModule).toContain('"url": "/assets/audio.mp3"');
+ expect(assetsModule).toContain("export const assetUrlsByPath");
+ expect(assetsModule).toContain('"/audio.mp3": "/assets/audio.mp3"');
expect(assetsModule).not.toContain("/cgi/");
+
+ const route = await readFile("app/routes/_index.tsx", "utf8");
+ expect(route).toContain("assetUrlsByPath");
+ expect(route).toContain("assetUrlsByPath,");
});
test("scaffolds generated files and stores redirects as data", async () => {
@@ -2365,7 +2371,7 @@ sitemap.map((page) => page.path);`
).rejects.toThrow("ENOENT");
});
- test("loads deferred SaaS document content from the asset proxy", async () => {
+ test("keeps deferred SaaS asset proxy URLs deployment-relative", async () => {
const index = await createAssetIndex({
projectId: "project-1",
entries: [
@@ -2391,6 +2397,7 @@ sitemap.map((page) => page.path);`
});
const siteData = {
...baseSiteData,
+ origin: "https://p-project-1.apps.webstudio.is",
assetIndex: index,
build: {
...baseSiteData.build,
@@ -2429,10 +2436,21 @@ sitemap.map((page) => page.path);`
"app/__generated__/$resources.asset-query-runtime.ts",
"utf8"
);
- expect(runtimeModule).toContain(
- '"url":"https://assets.example/cgi/asset/post.md?format=raw"'
+ expect(runtimeModule).toContain('"url":"/cgi/asset/post.md?format=raw"');
+ expect(runtimeModule).not.toContain(
+ "https://p-project-1.apps.webstudio.is/cgi/asset/"
);
expect(runtimeModule).not.toContain('"url":"/assets/post.md"');
+ const assetsModule = await readFile(
+ "app/__generated__/$resources.assets.ts",
+ "utf8"
+ );
+ expect(assetsModule).toContain(
+ '"/post.md": "/cgi/asset/post.md?format=raw"'
+ );
+ expect(assetsModule).not.toContain(
+ "https://p-project-1.apps.webstudio.is/cgi/asset/"
+ );
await mkdir(".webstudio/assets", { recursive: true });
await writeFile(".webstudio/assets/post.md", "# Post\n", "utf8");
@@ -2450,6 +2468,11 @@ sitemap.map((page) => page.path);`
expect(materializedRuntimeModule).not.toContain(
'"url":"https://assets.example/cgi/asset/post.md?format=raw"'
);
+ const materializedAssetsModule = await readFile(
+ "app/__generated__/$resources.assets.ts",
+ "utf8"
+ );
+ expect(materializedAssetsModule).toContain('"/post.md": "/assets/post.md"');
});
test("uses pass-through images in the base react-router template", async () => {
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index abe1182309..143385dde5 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -69,6 +69,7 @@ import {
getUnsafeDynamicPublishedMdxDiagnostic,
materializePublishedMdx,
getZodValidationIssues,
+ createAssetUrlsByPath,
} from "@webstudio-is/project-build/runtime";
import {
createPublishedBuildContentCompilationPlan,
@@ -1095,6 +1096,16 @@ export const prebuild = async (options: {
}
const assets = new Map(siteData.assets.map((asset) => [asset.id, asset]));
+ const getPublishedAssetUrl = (asset: Asset) => {
+ const runtimeAsset = toAssetReferenceRuntimeData(
+ asset,
+ "https://placeholder.local"
+ );
+ return siteData.build.deployment?.destination === "saas" &&
+ options.assets === false
+ ? runtimeAsset.url
+ : `${assetBaseUrl}${asset.name}`;
+ };
const runtimeAssetsById = Object.fromEntries(
siteData.assets.map((asset) => {
const runtimeAsset = toAssetReferenceRuntimeData(
@@ -1108,15 +1119,18 @@ export const prebuild = async (options: {
contentRef: asset.name,
// SaaS serves project assets through its storage-backed proxy.
// Generated projects with downloaded assets serve them locally.
- url:
- siteData.build.deployment?.destination === "saas" &&
- options.assets === false
- ? new URL(runtimeAsset.url, siteData.origin).href
- : `${assetBaseUrl}${asset.name}`,
+ url: getPublishedAssetUrl(asset),
},
];
})
);
+ const assetUrlsByPath = createAssetUrlsByPath({
+ assets: siteData.assets,
+ assetFolders: new Map(
+ (siteData.assetFolders ?? []).map((folder) => [folder.id, folder])
+ ),
+ getUrl: getPublishedAssetUrl,
+ });
const publishedInstances = new Map(siteData.build.instances);
const publishedProps = new Map(siteData.build.props);
const publishedStyleSources = new Map(siteData.build.styleSources);
@@ -1825,6 +1839,7 @@ export const prebuild = async (options: {
join(generatedDir, "$resources.assets.ts"),
`
export const assets = ${JSON.stringify(runtimeAssetsById, null, 2)};
+ export const assetUrlsByPath = ${JSON.stringify(assetUrlsByPath, null, 2)};
`
);
diff --git a/packages/cli/templates/defaults/app/route-templates/html.tsx b/packages/cli/templates/defaults/app/route-templates/html.tsx
index 5507cb745a..11f707f05b 100644
--- a/packages/cli/templates/defaults/app/route-templates/html.tsx
+++ b/packages/cli/templates/defaults/app/route-templates/html.tsx
@@ -46,6 +46,7 @@ import css from "__CSS__?url";
import { sitemap } from "__SITEMAP__";
import { authRoutes } from "__AUTH__";
import { createGeneratedAssetResourceFetch } from "__ASSET_QUERY_RUNTIME__";
+import { assetUrlsByPath } from "__ASSETS__";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -356,6 +357,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/packages/cli/templates/react-router/app/route-templates/html.tsx b/packages/cli/templates/react-router/app/route-templates/html.tsx
index 514fd8c004..e01f19c70f 100644
--- a/packages/cli/templates/react-router/app/route-templates/html.tsx
+++ b/packages/cli/templates/react-router/app/route-templates/html.tsx
@@ -45,6 +45,7 @@ import css from "__CSS__?url";
import { sitemap } from "__SITEMAP__";
import { authRoutes } from "__AUTH__";
import { createGeneratedAssetResourceFetch } from "__ASSET_QUERY_RUNTIME__";
+import { assetUrlsByPath } from "__ASSETS__";
const authenticateProductionRequest = (request: Request) => {
const host =
@@ -355,6 +356,7 @@ const Outlet = () => {
const sdkContext = useMemo(
() => ({
...constants,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/packages/cli/templates/ssg/app/route-templates/html/+Page.tsx b/packages/cli/templates/ssg/app/route-templates/html/+Page.tsx
index 1778f4f606..36c78d03c7 100644
--- a/packages/cli/templates/ssg/app/route-templates/html/+Page.tsx
+++ b/packages/cli/templates/ssg/app/route-templates/html/+Page.tsx
@@ -7,6 +7,7 @@ import {
} from "@webstudio-is/react-sdk/runtime";
import { LinkCurrentUrlContext } from "@webstudio-is/sdk-components-react";
import { assetBaseUrl, imageLoader } from "__CONSTANTS__";
+import { assetUrlsByPath } from "__ASSETS__";
import { Page, breakpoints, siteName } from "__CLIENT__";
const getPageKey = (url: string) => {
@@ -32,6 +33,7 @@ const PageComponent = ({ data }: { data: PageContext["data"] }) => {
() => ({
imageLoader,
assetBaseUrl,
+ assetUrlsByPath,
resources,
breakpoints,
onError: console.error,
diff --git a/packages/project-build/src/runtime.ts b/packages/project-build/src/runtime.ts
index 5a0f04209e..d16cc645d1 100644
--- a/packages/project-build/src/runtime.ts
+++ b/packages/project-build/src/runtime.ts
@@ -1,6 +1,7 @@
export * from "./build-integrity";
export * from "./shared/graph-utils";
export * from "./runtime/assets";
+export * from "./runtime/asset-urls";
export * from "./runtime/binding-verification";
export * from "./runtime/asset-folders";
export * from "./runtime/auth";
diff --git a/packages/project-build/src/runtime/asset-urls.test.ts b/packages/project-build/src/runtime/asset-urls.test.ts
new file mode 100644
index 0000000000..4611d67527
--- /dev/null
+++ b/packages/project-build/src/runtime/asset-urls.test.ts
@@ -0,0 +1,77 @@
+import { expect, test } from "vitest";
+import type { Asset, AssetFolders } from "@webstudio-is/sdk";
+import { createAssetUrlsByPath } from "./asset-urls";
+
+const asset = ({
+ id,
+ name,
+ filename,
+ folderId,
+}: {
+ id: string;
+ name: string;
+ filename?: string;
+ folderId?: string;
+}) =>
+ ({
+ id,
+ name,
+ filename,
+ folderId,
+ projectId: "project",
+ type: "file",
+ size: 1,
+ format: name.slice(name.lastIndexOf(".") + 1),
+ createdAt: "2026-01-01T00:00:00.000Z",
+ description: null,
+ meta: {},
+ }) as Asset;
+
+test("creates runtime URLs keyed by root-relative asset paths", () => {
+ const folders: AssetFolders = new Map([
+ [
+ "scripts",
+ {
+ id: "scripts",
+ projectId: "project",
+ name: "Custom scripts",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ },
+ ],
+ ]);
+ const assets = [
+ asset({ id: "hero", name: "hero_hash.png", filename: "Hero image" }),
+ asset({
+ id: "script",
+ name: "test_hash.js",
+ filename: "test",
+ folderId: "scripts",
+ }),
+ ];
+
+ expect(
+ createAssetUrlsByPath({
+ assets,
+ assetFolders: folders,
+ getUrl: (item) => `/cgi/asset/${item.name}`,
+ })
+ ).toEqual({
+ "/Hero%20image.png": "/cgi/asset/hero_hash.png",
+ "/Custom%20scripts/test.js": "/cgi/asset/test_hash.js",
+ });
+});
+
+test("omits ambiguous asset paths", () => {
+ const assets = [
+ asset({ id: "first", name: "first_hash.js", filename: "test" }),
+ asset({ id: "second", name: "second_hash.js", filename: "test" }),
+ ];
+
+ expect(
+ createAssetUrlsByPath({
+ assets,
+ assetFolders: new Map(),
+ getUrl: (item) => `/assets/${item.name}`,
+ })
+ ).toEqual({});
+});
diff --git a/packages/project-build/src/runtime/asset-urls.ts b/packages/project-build/src/runtime/asset-urls.ts
new file mode 100644
index 0000000000..71619f1aae
--- /dev/null
+++ b/packages/project-build/src/runtime/asset-urls.ts
@@ -0,0 +1,40 @@
+import { createUniqueAssetIdsByPath } from "@webstudio-is/content-engine";
+import { createCanonicalAssetPath } from "@webstudio-is/content-engine/mdx";
+import {
+ createAssetFolderHierarchy,
+ formatAssetName,
+ type Asset,
+ type AssetFolders,
+} from "@webstudio-is/sdk";
+
+export const createAssetUrlsByPath = ({
+ assets,
+ assetFolders,
+ getUrl,
+}: {
+ assets: Iterable<Asset>;
+ assetFolders: AssetFolders;
+ getUrl: (asset: Asset) => string;
+}) => {
+ const hierarchy = createAssetFolderHierarchy(assetFolders);
+ const urlsById = new Map<string, string>();
+ const assetIdsByPath = createUniqueAssetIdsByPath(
+ Array.from(assets, (asset) => {
+ urlsById.set(asset.id, getUrl(asset));
+ return {
+ id: asset.id,
+ path: createCanonicalAssetPath({
+ folderNames: hierarchy
+ .getPath(asset.folderId)
+ .map((folder) => folder.name),
+ name: formatAssetName(asset),
+ }),
+ };
+ })
+ );
+ return Object.fromEntries(
+ Array.from(assetIdsByPath, ([path, assetId]) => {
+ return [`/${path}`, urlsById.get(assetId)!];
+ })
+ );
+};
diff --git a/packages/react-sdk/placeholder.d.ts b/packages/react-sdk/placeholder.d.ts
index b925be91bb..8b08ae3438 100644
--- a/packages/react-sdk/placeholder.d.ts
+++ b/packages/react-sdk/placeholder.d.ts
@@ -72,6 +72,7 @@ declare module "__SITEMAP__" {
declare module "__ASSETS__" {
import type { RuntimeAsset } from "@webstudio-is/sdk";
export const assets: Record<string, RuntimeAsset>;
+ export const assetUrlsByPath: Record<string, string>;
}
declare module "__REDIRECT__" {
diff --git a/packages/react-sdk/src/context.tsx b/packages/react-sdk/src/context.tsx
index be06dfc88c..02e36db48f 100644
--- a/packages/react-sdk/src/context.tsx
+++ b/packages/react-sdk/src/context.tsx
@@ -30,6 +30,8 @@ export type Params = {
* https://assets.webstudio.is/
*/
assetBaseUrl: string;
+ /** Runtime URLs keyed by their root-relative path in the Assets panel. */
+ assetUrlsByPath?: Readonly<Record<string, string>>;
};
export const ReactSdkContext = createContext<
diff --git a/packages/sdk-components-react/package.json b/packages/sdk-components-react/package.json
index 3dad30c508..d37d637cda 100644
--- a/packages/sdk-components-react/package.json
+++ b/packages/sdk-components-react/package.json
@@ -86,6 +86,7 @@
"@webstudio-is/sdk": "workspace:*",
"await-interaction-response": "^0.0.2",
"colord": "^2.9.3",
+ "decode-named-character-reference": "1.0.2",
"github-slugger": "2.0.0",
"hast-util-to-jsx-runtime": "^2.3.6",
"mdast-util-from-markdown": "2.0.3",
diff --git a/packages/sdk-components-react/src/html-embed-assets.test.ts b/packages/sdk-components-react/src/html-embed-assets.test.ts
new file mode 100644
index 0000000000..0584fd167c
--- /dev/null
+++ b/packages/sdk-components-react/src/html-embed-assets.test.ts
@@ -0,0 +1,95 @@
+import { expect, test } from "vitest";
+import { resolveHtmlEmbedAssetUrls } from "./html-embed-assets";
+
+const assetUrlsByPath = {
+ "/test.js": "/cgi/asset/test_hash.js?format=raw",
+ "/site.css": "/cgi/asset/site_hash.css?format=raw",
+ "/hero.png": "/cgi/image/hero_hash.png?format=raw",
+ "/hero%26": "/cgi/image/hero_ampersand_hash.png?format=raw",
+ "/hero%26cover.png": "/cgi/image/hero_cover_hash.png?format=raw",
+ "/hero%402x.png": "/cgi/image/hero_2x_hash.png?format=raw",
+};
+
+test("rewrites asset attributes without reformatting embed markup", () => {
+ const code = `<SCRIPT defer SRC='/test.js#ready'></SCRIPT>
+<link href=/site.css rel=stylesheet>
+<img alt="Hero > image" src="/hero.png">`;
+
+ expect(resolveHtmlEmbedAssetUrls(code, assetUrlsByPath)).toBe(
+ `<SCRIPT defer SRC='/cgi/asset/test_hash.js?format=raw#ready'></SCRIPT>
+<link href=/cgi/asset/site_hash.css?format=raw rel=stylesheet>
+<img alt="Hero > image" src="/cgi/image/hero_hash.png?format=raw">`
+ );
+});
+
+test.each([
+ ["audio", "src"],
+ ["embed", "src"],
+ ["img", "src"],
+ ["input", "src"],
+ ["link", "href"],
+ ["object", "data"],
+ ["script", "src"],
+ ["source", "src"],
+ ["track", "src"],
+ ["video", "src"],
+ ["video", "poster"],
+] as const)("rewrites %s[%s] asset references", (tag, attribute) => {
+ expect(
+ resolveHtmlEmbedAssetUrls(
+ `<${tag} ${attribute}="/test.js"></${tag}>`,
+ assetUrlsByPath
+ )
+ ).toBe(`<${tag} ${attribute}="/cgi/asset/test_hash.js?format=raw"></${tag}>`);
+});
+
+test("does not rewrite markup-like text in comments or raw text elements", () => {
+ const code = `<!-- <img src="/hero.png"> -->
+<script>const markup = '</scripture><img src="/hero.png">'</script>
+<style>.hero { background: url('/hero.png') }</style>
+<textarea><img src="/hero.png"></textarea>`;
+
+ expect(resolveHtmlEmbedAssetUrls(code, assetUrlsByPath)).toBe(code);
+});
+
+test("leaves unrelated and missing asset references unchanged", () => {
+ const code = `<div data-src="/hero.png"><img src="/missing.png"></div>`;
+ expect(resolveHtmlEmbedAssetUrls(code, assetUrlsByPath)).toBe(code);
+ expect(resolveHtmlEmbedAssetUrls(code, undefined)).toBe(code);
+});
+
+test("decodes character references and canonicalizes asset paths", () => {
+ const code = `<script src="/test.js?one=1&amp;two=2"></script>
+<img src="/hero&amp;cover.png">
+<img src="/hero&amp">`;
+
+ expect(resolveHtmlEmbedAssetUrls(code, assetUrlsByPath)).toBe(
+ `<script src="/cgi/asset/test_hash.js?format=raw&one=1&two=2"></script>
+<img src="/cgi/image/hero_cover_hash.png?format=raw">
+<img src="/cgi/image/hero_ampersand_hash.png?format=raw">`
+ );
+});
+
+test("rewrites responsive image candidates", () => {
+ const code = `<picture>
+ <source srcset="/hero.png 1x, /[email protected] 2x">
+ <img src="/hero.png" srcset="/hero.png 480w, /missing.png 960w">
+</picture>`;
+
+ expect(resolveHtmlEmbedAssetUrls(code, assetUrlsByPath)).toBe(`<picture>
+ <source srcset="/cgi/image/hero_hash.png?format=raw 1x, /cgi/image/hero_2x_hash.png?format=raw 2x">
+ <img src="/cgi/image/hero_hash.png?format=raw" srcset="/cgi/image/hero_hash.png?format=raw 480w, /missing.png 960w">
+</picture>`);
+});
+
+test("preserves data URLs and resolves descriptorless and malformed srcset candidates", () => {
+ const code =
+ `<img srcset="data:image/svg+xml,%3Csvg%3E 1x, /hero.png, ` +
+ `/[email protected] invalid-descriptor">`;
+
+ expect(resolveHtmlEmbedAssetUrls(code, assetUrlsByPath)).toBe(
+ `<img srcset="data:image/svg+xml,%3Csvg%3E 1x, ` +
+ `/cgi/image/hero_hash.png?format=raw, ` +
+ `/cgi/image/hero_2x_hash.png?format=raw invalid-descriptor">`
+ );
+});
diff --git a/packages/sdk-components-react/src/html-embed-assets.ts b/packages/sdk-components-react/src/html-embed-assets.ts
new file mode 100644
index 0000000000..314966f9a3
--- /dev/null
+++ b/packages/sdk-components-react/src/html-embed-assets.ts
@@ -0,0 +1,355 @@
+import { decodeNamedCharacterReference } from "decode-named-character-reference";
+
+const assetAttributes = new Map<string, ReadonlySet<string>>([
+ ["audio", new Set(["src"])],
+ ["embed", new Set(["src"])],
+ ["img", new Set(["src", "srcset"])],
+ ["input", new Set(["src"])],
+ ["link", new Set(["href"])],
+ ["object", new Set(["data"])],
+ ["script", new Set(["src"])],
+ ["source", new Set(["src", "srcset"])],
+ ["track", new Set(["src"])],
+ ["video", new Set(["src", "poster"])],
+]);
+
+const rawTextElements = new Set([
+ "iframe",
+ "noembed",
+ "noframes",
+ "noscript",
+ "plaintext",
+ "script",
+ "style",
+ "textarea",
+ "title",
+ "xmp",
+]);
+
+const isWhitespace = (character: string | undefined) =>
+ character !== undefined && /\s/.test(character);
+const isTagNameCharacter = (character: string | undefined) =>
+ character !== undefined && /[A-Za-z0-9:-]/.test(character);
+
+const decodeHtmlCharacterReferences = (value: string) =>
+ value
+ .replace(
+ /&(#(?:\d+|x[\da-f]+)|[a-z][\da-z]+);/gi,
+ (reference, name: string) => {
+ if (name[0] !== "#") {
+ return decodeNamedCharacterReference(name) || reference;
+ }
+ const isHex = name[1]?.toLowerCase() === "x";
+ const radix = isHex ? 16 : 10;
+ const codePoint = Number.parseInt(name.slice(isHex ? 2 : 1), radix);
+ if (
+ Number.isNaN(codePoint) ||
+ codePoint === 0 ||
+ codePoint > 0x10ffff ||
+ (codePoint >= 0xd800 && codePoint <= 0xdfff)
+ ) {
+ return "�";
+ }
+ return String.fromCodePoint(codePoint);
+ }
+ )
+ // `amp` is one of the legacy named references HTML permits without a
+ // semicolon, except before an alphanumeric character or equals sign.
+ .replace(/&amp(?=$|[^=\da-z])/gi, "&");
+
+const encodeAssetPathSegment = (segment: string) => {
+ const encoded = encodeURIComponent(segment);
+ if (encoded === ".") {
+ return "%2E";
+ }
+ if (encoded === "..") {
+ return "%2E%2E";
+ }
+ return encoded;
+};
+
+const normalizeAssetPath = (path: string) =>
+ path
+ .split("/")
+ .map((segment) => {
+ try {
+ return encodeAssetPathSegment(decodeURIComponent(segment));
+ } catch {
+ return encodeAssetPathSegment(segment);
+ }
+ })
+ .join("/");
+
+const resolveAssetUrl = (
+ value: string,
+ assetUrlsByPath: Readonly<Record<string, string>>
+) => {
+ value = decodeHtmlCharacterReferences(value);
+ if (value.startsWith("/") === false || value.startsWith("//")) {
+ return;
+ }
+
+ const base = "https://webstudio.invalid";
+ const hashIndex = value.indexOf("#");
+ const beforeHash = hashIndex === -1 ? value : value.slice(0, hashIndex);
+ const hash = hashIndex === -1 ? "" : value.slice(hashIndex);
+ const searchIndex = beforeHash.indexOf("?");
+ const pathname =
+ searchIndex === -1 ? beforeHash : beforeHash.slice(0, searchIndex);
+ const search = searchIndex === -1 ? "" : beforeHash.slice(searchIndex);
+ const assetUrl = assetUrlsByPath[normalizeAssetPath(pathname)];
+ if (assetUrl === undefined) {
+ return;
+ }
+
+ const isAbsolute = URL.canParse(assetUrl);
+ const resolved = new URL(assetUrl, base);
+ for (const [name, value] of new URLSearchParams(search)) {
+ resolved.searchParams.append(name, value);
+ }
+ if (hash !== "") {
+ resolved.hash = hash;
+ }
+ return isAbsolute
+ ? resolved.href
+ : `${resolved.pathname}${resolved.search}${resolved.hash}`;
+};
+
+const resolveSrcset = (
+ value: string,
+ assetUrlsByPath: Readonly<Record<string, string>>
+) => {
+ const replacements: Replacement[] = [];
+ let index = 0;
+ while (index < value.length) {
+ while (
+ index < value.length &&
+ (isWhitespace(value[index]) || value[index] === ",")
+ ) {
+ index += 1;
+ }
+ const urlStart = index;
+ while (index < value.length && isWhitespace(value[index]) === false) {
+ index += 1;
+ }
+ let urlEnd = index;
+ while (urlEnd > urlStart && value[urlEnd - 1] === ",") {
+ urlEnd -= 1;
+ }
+ const hasTrailingComma = urlEnd < index;
+ const resolved = resolveAssetUrl(
+ value.slice(urlStart, urlEnd),
+ assetUrlsByPath
+ );
+ if (resolved !== undefined) {
+ replacements.push({ start: urlStart, end: urlEnd, value: resolved });
+ }
+ if (hasTrailingComma) {
+ continue;
+ }
+ while (index < value.length && value[index] !== ",") {
+ index += 1;
+ }
+ }
+ if (replacements.length === 0) {
+ return;
+ }
+ let resolved = value;
+ for (const replacement of replacements.toReversed()) {
+ resolved = `${resolved.slice(0, replacement.start)}${replacement.value}${resolved.slice(replacement.end)}`;
+ }
+ return resolved;
+};
+
+type Replacement = { start: number; end: number; value: string };
+
+const findTagEnd = (code: string, start: number) => {
+ let quote = "";
+ for (let index = start; index < code.length; index += 1) {
+ const character = code[index];
+ if (quote !== "") {
+ if (character === quote) {
+ quote = "";
+ }
+ continue;
+ }
+ if (character === '"' || character === "'") {
+ quote = character;
+ continue;
+ }
+ if (character === ">") {
+ return index;
+ }
+ }
+ return code.length;
+};
+
+const collectAttributeReplacements = ({
+ code,
+ start,
+ end,
+ attributeNames,
+ assetUrlsByPath,
+}: {
+ code: string;
+ start: number;
+ end: number;
+ attributeNames: ReadonlySet<string>;
+ assetUrlsByPath: Readonly<Record<string, string>>;
+}) => {
+ const replacements: Replacement[] = [];
+ let index = start;
+ while (index < end) {
+ while (index < end && (isWhitespace(code[index]) || code[index] === "/")) {
+ index += 1;
+ }
+ const nameStart = index;
+ while (
+ index < end &&
+ isWhitespace(code[index]) === false &&
+ code[index] !== "=" &&
+ code[index] !== "/" &&
+ code[index] !== ">"
+ ) {
+ index += 1;
+ }
+ if (index === nameStart) {
+ index += 1;
+ continue;
+ }
+ const name = code.slice(nameStart, index).toLowerCase();
+ while (index < end && isWhitespace(code[index])) {
+ index += 1;
+ }
+ if (code[index] !== "=") {
+ continue;
+ }
+ index += 1;
+ while (index < end && isWhitespace(code[index])) {
+ index += 1;
+ }
+ const quote = code[index] === '"' || code[index] === "'" ? code[index] : "";
+ if (quote !== "") {
+ index += 1;
+ }
+ const valueStart = index;
+ if (quote === "") {
+ while (
+ index < end &&
+ isWhitespace(code[index]) === false &&
+ code[index] !== ">"
+ ) {
+ index += 1;
+ }
+ } else {
+ while (index < end && code[index] !== quote) {
+ index += 1;
+ }
+ }
+ const valueEnd = index;
+ if (quote !== "" && code[index] === quote) {
+ index += 1;
+ }
+ if (attributeNames.has(name)) {
+ const attributeValue = code.slice(valueStart, valueEnd);
+ const value =
+ name === "srcset"
+ ? resolveSrcset(attributeValue, assetUrlsByPath)
+ : resolveAssetUrl(attributeValue, assetUrlsByPath);
+ if (value !== undefined) {
+ replacements.push({ start: valueStart, end: valueEnd, value });
+ }
+ }
+ }
+ return replacements;
+};
+
+const findRawTextEnd = (code: string, tagName: string, start: number) => {
+ if (tagName === "plaintext") {
+ return code.length;
+ }
+ const lowerCode = code.toLowerCase();
+ let index = start;
+ while (index < code.length) {
+ const closingTag = lowerCode.indexOf(`</${tagName}`, index);
+ if (closingTag === -1) {
+ return code.length;
+ }
+ const afterName = code[closingTag + tagName.length + 2];
+ if (afterName === ">" || afterName === "/" || isWhitespace(afterName)) {
+ return closingTag;
+ }
+ index = closingTag + tagName.length + 2;
+ }
+ return code.length;
+};
+
+export const resolveHtmlEmbedAssetUrls = (
+ code: string,
+ assetUrlsByPath: Readonly<Record<string, string>> | undefined
+) => {
+ if (
+ assetUrlsByPath === undefined ||
+ Object.keys(assetUrlsByPath).length === 0
+ ) {
+ return code;
+ }
+
+ const replacements: Replacement[] = [];
+ let index = 0;
+ while (index < code.length) {
+ const tagStart = code.indexOf("<", index);
+ if (tagStart === -1) {
+ break;
+ }
+ if (code.startsWith("<!--", tagStart)) {
+ const commentEnd = code.indexOf("-->", tagStart + 4);
+ index = commentEnd === -1 ? code.length : commentEnd + 3;
+ continue;
+ }
+ const nameStart = tagStart + 1;
+ if (
+ code[nameStart] === "/" ||
+ code[nameStart] === "!" ||
+ code[nameStart] === "?"
+ ) {
+ index = findTagEnd(code, nameStart) + 1;
+ continue;
+ }
+ let nameEnd = nameStart;
+ while (isTagNameCharacter(code[nameEnd])) {
+ nameEnd += 1;
+ }
+ if (nameEnd === nameStart) {
+ index = tagStart + 1;
+ continue;
+ }
+ const tagName = code.slice(nameStart, nameEnd).toLowerCase();
+ const tagEnd = findTagEnd(code, nameEnd);
+ const attributeNames = assetAttributes.get(tagName);
+ if (attributeNames !== undefined) {
+ replacements.push(
+ ...collectAttributeReplacements({
+ code,
+ start: nameEnd,
+ end: tagEnd,
+ attributeNames,
+ assetUrlsByPath,
+ })
+ );
+ }
+ index = tagEnd + 1;
+ if (rawTextElements.has(tagName)) {
+ index = findRawTextEnd(code, tagName, index);
+ }
+ }
+
+ if (replacements.length === 0) {
+ return code;
+ }
+ let resolved = code;
+ for (const replacement of replacements.toReversed()) {
+ resolved = `${resolved.slice(0, replacement.start)}${replacement.value}${resolved.slice(replacement.end)}`;
+ }
+ return resolved;
+};
diff --git a/packages/sdk-components-react/src/html-embed.browser.test.tsx b/packages/sdk-components-react/src/html-embed.browser.test.tsx
index c69b5c3a49..30d07981a3 100644
--- a/packages/sdk-components-react/src/html-embed.browser.test.tsx
+++ b/packages/sdk-components-react/src/html-embed.browser.test.tsx
@@ -17,11 +17,15 @@ const App = (props: {
renderer?: "canvas" | "preview";
executeScriptOnCanvas?: boolean;
$ws$executeScripts?: boolean;
+ assetUrlsByPath?: Record<string, string>;
+ code?: string;
}) => {
const [page, switchPage] = React.useReducer((n) => (n + 1) % 2, 0);
const [refresh, setRefresh] = React.useReducer((n) => n + 1, 0);
- const code = `
+ const code =
+ props.code ??
+ `
<script data-testid="${SCRIPT_TEST_ID}" data-page="${page}">console.log('hello')</script>
<div data-testid="${FRAGMENT_DIV_ID}">hello</div>
`;
@@ -30,6 +34,7 @@ const App = (props: {
<ReactSdkContext.Provider
value={{
assetBaseUrl: "",
+ assetUrlsByPath: props.assetUrlsByPath,
imageLoader: () => "",
renderer: props.renderer,
resources: {},
@@ -63,6 +68,32 @@ beforeEach(() => {
});
describe("Published site", () => {
+ test("resolves root-relative asset paths during server rendering", () => {
+ const html = ReactDOMServer.renderToString(
+ <App
+ code={`
+ <script src="/test.js?version=1#ready"></script>
+ <link rel="stylesheet" href="/styles/site.css">
+ <img src="/Hero image.png">
+ <img src="/not-an-asset.png">
+ `}
+ assetUrlsByPath={{
+ "/test.js": "/assets/test_hash.js",
+ "/styles/site.css": "/assets/site_hash.css",
+ "/Hero%20image.png":
+ "https://assets.example/hero_hash.png?format=raw",
+ }}
+ />
+ );
+
+ expect(html).toContain('src="/assets/test_hash.js?version=1#ready"');
+ expect(html).toContain('href="/assets/site_hash.css"');
+ expect(html).toContain(
+ 'src="https://assets.example/hero_hash.png?format=raw"'
+ );
+ expect(html).toContain('src="/not-an-asset.png"');
+ });
+
/**
* Tests the behavior of script tags in an SSR context for a published site with `clientOnly` set to false:
* - SSR: Renders script tags in HTML embeds directly, without modification, on the server side, on hydration and on refresh.
@@ -162,6 +193,34 @@ describe("Published site", () => {
* On canvas renderer, scripts are not executed on the server side.
*/
describe("Builder renderer= canvas | preview", () => {
+ test("resolves root-relative asset paths for canvas markup", () => {
+ const { container } = render(
+ <App
+ renderer="canvas"
+ code={`
+ <script src="/test.js"></script>
+ <link rel="stylesheet" href="/site.css">
+ <img src="/hero.png">
+ `}
+ assetUrlsByPath={{
+ "/test.js": "/cgi/asset/test_hash.js",
+ "/site.css": "/cgi/asset/site_hash.css",
+ "/hero.png": "/cgi/asset/hero_hash.png",
+ }}
+ />
+ );
+
+ expect(container.querySelector("script")?.getAttribute("src")).toBe(
+ "/cgi/asset/test_hash.js"
+ );
+ expect(container.querySelector("link")?.getAttribute("href")).toBe(
+ "/cgi/asset/site_hash.css"
+ );
+ expect(container.querySelector("img")?.getAttribute("src")).toBe(
+ "/cgi/asset/hero_hash.png"
+ );
+ });
+
test.each(["canvas", "preview"] as const)(
"waits for resources to settle before executing scripts in %s",
async (renderer) => {
diff --git a/packages/sdk-components-react/src/html-embed.tsx b/packages/sdk-components-react/src/html-embed.tsx
index 038f75efdd..912265e464 100644
--- a/packages/sdk-components-react/src/html-embed.tsx
+++ b/packages/sdk-components-react/src/html-embed.tsx
@@ -12,6 +12,7 @@ import {
import { mergeRefs } from "@react-aria/utils";
import { ReactSdkContext } from "@webstudio-is/react-sdk/runtime";
import { executeDomEvents, patchDomEvents } from "./html-embed-patchers";
+import { resolveHtmlEmbedAssetUrls } from "./html-embed-assets";
const scriptTestIdPrefix = "client-";
@@ -233,11 +234,15 @@ export const HtmlEmbed = forwardRef<HTMLDivElement, HtmlEmbedProps>(
$ws$executeScripts = true,
...rest
} = props;
- const { renderer } = useContext(ReactSdkContext);
+ const { renderer, assetUrlsByPath } = useContext(ReactSdkContext);
const isServer = useIsServer();
const [ssrRendered] = useState(isServer);
+ const resolvedCode = useMemo(
+ () => resolveHtmlEmbedAssetUrls(String(code ?? ""), assetUrlsByPath),
+ [assetUrlsByPath, code]
+ );
// - code can be actually undefined when prop is not provided
// - cast code to string in case non-string value is computed from expression
@@ -248,12 +253,12 @@ export const HtmlEmbed = forwardRef<HTMLDivElement, HtmlEmbedProps>(
if (ssrRendered) {
// We are on published site, on server rendering or after hydration
if (clientOnly !== true) {
- return <ServerEmbed innerRef={ref} code={code} {...rest} />;
+ return <ServerEmbed innerRef={ref} code={resolvedCode} {...rest} />;
}
return (
<ClientOnly>
- <ClientEmbed innerRef={ref} code={code} {...rest} />
+ <ClientEmbed innerRef={ref} code={resolvedCode} {...rest} />
</ClientOnly>
);
}
@@ -264,7 +269,7 @@ export const HtmlEmbed = forwardRef<HTMLDivElement, HtmlEmbedProps>(
<ClientOnly>
<ClientEmbedWithNonExecutableScripts
innerRef={ref}
- code={code}
+ code={resolvedCode}
{...rest}
/>
</ClientOnly>
@@ -277,7 +282,7 @@ export const HtmlEmbed = forwardRef<HTMLDivElement, HtmlEmbedProps>(
<ClientOnly>
<ClientEmbedWithNonExecutableScripts
innerRef={ref}
- code={code}
+ code={resolvedCode}
{...rest}
/>
</ClientOnly>
@@ -288,9 +293,9 @@ export const HtmlEmbed = forwardRef<HTMLDivElement, HtmlEmbedProps>(
<ClientOnly>
<ClientEmbed
// Use key={code} to allow scripts to be reexecuted when code has changed
- key={code}
+ key={resolvedCode}
innerRef={ref}
- code={code}
+ code={resolvedCode}
{...rest}
/>
</ClientOnly>
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0ba5867609..32c13d1cb3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2758,6 +2758,9 @@ importers:
colord:
specifier: ^2.9.3
version: 2.9.3
+ decode-named-character-reference:
+ specifier: 1.0.2
+ version: 1.0.2
github-slugger:
specifier: 2.0.0
version: 2.0.0