fix(core): the motion path plugin loads from beside the page's own GSAP, never a CDN it did not name (#8523)

* fix(core): the motion path plugin loads from beside the page's own GSAP, never a CDN it did not name

* test(core): local root, revalidation and path-free preload rows

* fix(core): the motion path plugin never falls back to jsDelivr, nor preloads for a page with none

* fix(core): the plugin path beside GSAP is cut in linear time

* test(core): the Desktop walk film's plugin request stays on its origin

* fix(core): preload the motion path plugin only from the page's origin or a configured mirror

* fix(core): the motion path preload compares with the preview document's own origin

* fix(core): one rule decides the motion path plugin URL, bound to the document's own origin

* fix(studio-server): the plugin tag sits beside the page's GSAP as the page wrote it

* test(studio): the plugin-load fixtures name a page GSAP or a configured mirror
This commit is contained in:
Miguel Ángel
2026-11-22 20:31:38 +00:00
committed by GitHub
parent 4daeb78c3d
commit 80f45de33d
12 changed files with 395 additions and 57 deletions
+1
View File
@@ -74,6 +74,7 @@ export {
isAlwaysAppliedStyle,
deferScriptsUntilFonts,
headStyleRuns,
INLINED_FILE_ATTR,
inlineScriptRuns,
styleElementsFor,
type CompositionStyle,
+35 -1
View File
@@ -6,6 +6,18 @@ export const NO_PATH_TWEEN_META = "hf-no-path-tween";
export const namesMotionPath = (script: string) => /motionPath["']?\s*[:{]/.test(script);
const pathOf = (src: string) =>
URL.canParse(src, "http://localhost/") ? new URL(src, "http://localhost/").pathname : null;
export function isGsapCoreUrl(src: string): boolean {
return /\/gsap(-\d+(\.\d+)*)?(\.min)?\.js$/i.test(pathOf(src) ?? "");
}
export function motionPathBesideGsap(gsapFile: string): string {
const path = gsapFile.split(/[?#]/, 1)[0]!;
return `${path.slice(0, path.lastIndexOf("/") + 1)}MotionPathPlugin.min.js`;
}
function isLoopbackHost(hostname: string): boolean {
return hostname === "localhost" || hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/.test(hostname);
}
@@ -51,7 +63,29 @@ export function gsapCdnDist(gsapVersion?: string, baseUrl?: string): string {
return `${normalizeGsapBaseUrl(baseUrl)}/gsap@${version}/dist/`;
}
/** MotionPathPlugin at the composition's own gsap version; a skew registers with a GSAP warning. */
export function motionPathPluginUrl(gsapVersion?: string, baseUrl?: string): string {
return `${gsapCdnDist(gsapVersion, baseUrl)}MotionPathPlugin.min.js`;
}
const originOf = (url: string) => (URL.canParse(url) ? new URL(url).origin : "null");
/** The plugin a preview may load: an absolute mirror, the document's own origin, or (`pageOwned`) the page's GSAP. */
export function previewMotionPathSrc(page: {
gsapFile: string | null;
mirror?: string | null;
version?: string;
documentUrl: string;
baseUrl: string;
pageOwned: boolean;
}): string | null {
const own = originOf(page.documentUrl);
const mirror = page.mirror?.trim();
if (mirror?.startsWith("/")) {
return own === "null" ? null : new URL(motionPathPluginUrl(GSAP_CDN_VERSION, mirror), own).href;
}
const version = page.version ?? page.gsapFile?.match(/gsap@([\d.]+)/)?.[1];
if (mirror) return motionPathPluginUrl(version, mirror);
if (!page.gsapFile || !URL.canParse(page.gsapFile, page.baseUrl)) return null;
const href = new URL(motionPathBesideGsap(page.gsapFile), page.baseUrl).href;
return page.pageOwned || (own !== "null" && originOf(href) === own) ? href : null;
}
@@ -4,6 +4,7 @@ import { parseRestoreAttributes } from "./restoreAttributes";
import {
parseRestoreAttributesRerun,
parseSoftReload,
preloadMotionPath,
restoreAttributesOrRerun,
softReload,
type SoftReloadParams,
@@ -167,6 +168,7 @@ describe("a re-run that waits for the MotionPath plugin", () => {
document.body.innerHTML =
`<div data-composition-id="main"><div id="a" data-hf-id="a" style="left: 0px"></div></div>` +
`<div data-composition-id="other"></div>` +
`<script src="gsap.min.js"></script>` +
`<script>${run("main", "file")}</script><script>${run("other", "file")}</script>`;
delete document.body.dataset.main;
delete document.body.dataset.other;
@@ -491,3 +493,93 @@ describe("parseSoftReload", () => {
expect(parseSoftReload(request)).toBeNull();
});
});
describe("where the MotionPath plugin loads from", () => {
const pluginSrc = () =>
document.head.querySelector<HTMLScriptElement>("script[data-hf-gsap-plugin]")?.src ?? null;
const PATH_TWEEN = '<script>gsap.to("#a", { motionPath: { path: "#p" } });</script>';
function preloadOn(markup: string, version?: string) {
document.body.innerHTML = markup;
win.gsap = { version, registerPlugin: () => {} };
preloadMotionPath(win, document);
return pluginSrc();
}
// fails without the fix: the plugin came from jsDelivr whatever the page's GSAP was, so a preview with no
// network asked a third party for a script the page never named.
it.each([
['<script src="vendor/gsap.min.js"></script>', "vendor/MotionPathPlugin.min.js"],
[
'<script data-hf-inlined-src="vendor/gsap.min.js"></script>',
"vendor/MotionPathPlugin.min.js",
],
])("loads it from beside the page's own GSAP: %s", (tag, plugin) => {
expect(preloadOn(tag + PATH_TWEEN)).toBe(new URL(plugin, document.baseURI).href);
});
// fails without the fix: Desktop's walk film (project gsap.min.js at 3.12.5, no server meta) asked jsDelivr.
it("asks the page's own origin for a project GSAP's plugin, whatever its version", () => {
const src = preloadOn(`<script src="gsap.min.js"></script>${PATH_TWEEN}`, "3.12.5");
expect(src).toBe(new URL("MotionPathPlugin.min.js", document.baseURI).href);
expect(new URL(src!).origin).toBe(new URL(document.baseURI).origin);
});
it("requests nothing when the page names no GSAP file", () => {
expect(preloadOn(`<script>/* gsap inlined by hand */</script>${PATH_TWEEN}`)).toBeNull();
});
// fails without the fix: a host's bundled root holds only its own GSAP version, so for another version the
// plugin came from jsDelivr though the page and the host named only same-origin files.
it("takes the host's bundled plugin for a page on another GSAP version, never the CDN", () => {
const meta = '<meta name="hyperframes-gsap-base-url" content="/api/vendor/npm">';
document.head.innerHTML = meta;
const src = preloadOn(
`<script src="vendor/gsap@3.12.5/dist/gsap.min.js"></script>${PATH_TWEEN}`,
"3.12.5",
);
expect(src).toBe(
new URL("/api/vendor/npm/gsap@3.15.0/dist/MotionPathPlugin.min.js", document.baseURI).href,
);
});
// fails without the fix: with no server meta (Desktop), a film with GSAP from jsDelivr preloaded the plugin
// from there ahead of any path tween; an edit that adds one still loads it beside that GSAP.
it.each([
["no path tween", ""],
["a path tween", PATH_TWEEN],
])("never preloads from a CDN the host did not configure, with %s", (_, tween) => {
const cdn = '<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>';
expect(preloadOn(cdn + tween, "3.14.2")).toBeNull();
});
// fails without the fix: rows "nothing, other site" and "local root, other site". The check read the
// page's base, so a <base> on another site moved a "local" plugin there.
const LOCAL = "http://localhost:3000/api/vendor/npm/gsap@3.15.0/dist/MotionPathPlugin.min.js";
const MIRROR = "https://mirror.example/npm/gsap@3.12.5/dist/MotionPathPlugin.min.js";
it.each<[string, string, string, string | null]>([
["nothing", "/film/", "", "http://localhost:3000/film/vendor/MotionPathPlugin.min.js"],
["nothing", "https://assets.example/film/", "", null],
["local root", "/film/", "/api/vendor/npm", LOCAL],
["local root", "https://assets.example/film/", "/api/vendor/npm", LOCAL],
["mirror", "/film/", "https://mirror.example/npm", MIRROR],
["mirror", "https://assets.example/film/", "https://mirror.example/npm", MIRROR],
])("preloads with %s configured under the base %s", (_, base, mirror, expected) => {
document.head.innerHTML =
`<base href="${base}">` +
(mirror ? `<meta name="hyperframes-gsap-base-url" content="${mirror}">` : "");
expect(preloadOn(`<script src="vendor/gsap.min.js"></script>${PATH_TWEEN}`, "3.12.5")).toBe(
expected,
);
});
// fails without the fix: a data: script threw out of the preload, and a project script beside GSAP was
// taken for GSAP's own and skipped it.
it.each([
["a project script beside GSAP", '<script src="vendor/scene.js"></script>'],
["a data: script", '<script src="data:text/javascript,window.x=1"></script>'],
])("preloads the local plugin whatever else the page loads: %s", (_, other) => {
expect(preloadOn(`<script src="vendor/gsap.min.js"></script>${other}`)).toBe(
new URL("vendor/MotionPathPlugin.min.js", document.baseURI).href,
);
});
});
@@ -5,9 +5,11 @@ import {
GSAP_BASE_URL_META,
GSAP_PLUGIN_LOAD_ATTR,
NO_PATH_TWEEN_META,
motionPathPluginUrl,
isGsapCoreUrl,
previewMotionPathSrc,
namesMotionPath,
} from "../../gsapCdn";
import { INLINED_FILE_ATTR } from "../../compiler/scriptRuns";
import { applyAuthoredInlineOpacity, readStampedAuthoredOpacity } from "../../colorGrading";
import { escapeCssString } from "../editingElement";
import { applyAuthoredTiming } from "../../studioPreviewMark";
@@ -337,11 +339,29 @@ export function finalizeSoftReload(win: SoftReloadWindow, currentTime: number):
if (wasPlaying) win.__player?.play?.();
}
export function previewMotionPathUrl(doc: Document, version?: string): string {
const baseUrl = doc.head.querySelector<HTMLMetaElement>(
`meta[name="${GSAP_BASE_URL_META}"]`,
)?.content;
return motionPathPluginUrl(version, baseUrl);
const scriptFile = (script: Element) =>
script.getAttribute("src") ?? script.getAttribute(INLINED_FILE_ATTR);
function pageGsapFile(doc: Document): string | null {
for (const script of doc.querySelectorAll(`script[src], script[${INLINED_FILE_ATTR}]`)) {
const file = scriptFile(script);
if (file && isGsapCoreUrl(file)) return file;
}
return null;
}
const gsapMirror = (doc: Document) =>
doc.head.querySelector<HTMLMetaElement>(`meta[name="${GSAP_BASE_URL_META}"]`)?.content;
function previewMotionPathUrl(doc: Document, version?: string, pageOwned = true): string | null {
return previewMotionPathSrc({
gsapFile: pageGsapFile(doc),
mirror: gsapMirror(doc),
version,
documentUrl: doc.URL,
baseUrl: doc.baseURI,
pageOwned,
});
}
function runSuppressed(win: SoftReloadWindow, reload: () => void): boolean {
@@ -411,8 +431,10 @@ function whenMotionPathLoaded(
win.__hfMotionPathWaiters = undefined;
for (const [onReady, onFailed] of waiters) (loaded ? onReady : onFailed)();
};
const src = previewMotionPathUrl(doc, win.gsap?.version);
if (!src) return settle(false);
const pluginScript = doc.createElement("script");
pluginScript.src = previewMotionPathUrl(doc, win.gsap?.version);
pluginScript.src = src;
pluginScript.setAttribute(GSAP_PLUGIN_LOAD_ATTR, "");
pluginScript.onload = () => settle(Boolean(win.MotionPathPlugin));
// Running the script without the plugin would leave a motionPath tween that cannot play.
@@ -469,6 +491,8 @@ export function preloadMotionPath(
): void {
if (win.MotionPathPlugin || win.__hfMotionPathWaiters || !win.gsap) return;
if (doc.querySelector(`meta[name="${NO_PATH_TWEEN_META}"]`)) return;
// Ahead of any path tween, only a request that stays local: the document's origin or the host's mirror.
if (!previewMotionPathUrl(doc, win.gsap.version, false)) return;
const register = () => win.MotionPathPlugin && win.gsap?.registerPlugin?.(win.MotionPathPlugin);
whenMotionPathLoaded(win, doc, register, () => {});
}
@@ -64,6 +64,25 @@ describe("installEditingAgent", () => {
expect(transfer).toHaveLength(1);
});
// fails without the fix: the plugin preload ran before the handoff, so a page it threw on never got a port.
it("hands the port over before the optional plugin preload", () => {
Object.defineProperty(window, "gsap", {
configurable: true,
get: () => {
throw new Error("page gsap getter");
},
});
const reported = (event: ErrorEvent) => event.preventDefault();
window.addEventListener("error", reported);
try {
post(parent, CONNECT);
expect(handoff).toHaveBeenCalledOnce();
} finally {
window.removeEventListener("error", reported);
Reflect.deleteProperty(window, "gsap");
}
});
it("hands a fresh port to each later connect from the parent and keeps the earlier one working", async () => {
const old = connectedPort();
post(parent, CONNECT);
+2 -1
View File
@@ -303,7 +303,6 @@ export function installEditingAgent(parent: Window = window.parent): { dispose:
const port = channel.port1;
ports.add(port);
serve(port);
preloadMotionPath();
try {
// "*" as every runtime post does (bridge.ts): the frame is not told its parent's origin.
parent.postMessage(
@@ -315,7 +314,9 @@ export function installEditingAgent(parent: Window = window.parent): { dispose:
swallow("editingAgent.handoff", err);
port.close();
ports.delete(port);
return;
}
preloadMotionPath();
};
window.addEventListener("message", onMessage);
return {
@@ -1,4 +1,5 @@
import { findStartTags, insertBeforeCloseTag } from "@hyperframes/core/compiler/html-document";
import { isGsapCoreUrl } from "@hyperframes/core/gsap-cdn";
const URL_BASE = "http://localhost/";
@@ -6,9 +7,7 @@ function urlPath(src: string): string | null {
return URL.canParse(src, URL_BASE) ? new URL(src, URL_BASE).pathname : null;
}
export function isGsapCoreUrl(src: string): boolean {
return /\/gsap(-\d+(\.\d+)*)?(\.min)?\.js$/i.test(urlPath(src) ?? "");
}
export { isGsapCoreUrl };
const GSAP_PLUGIN_FILE =
/\/(\w+Plugin|CustomBounce|CustomEase|CustomWiggle|Draggable|EasePack|Flip|GSDevTools|MotionPathHelper|Observer|ScrollSmoother|ScrollTrigger|SplitText)(\.min)?\.js$/i;
@@ -20,7 +20,12 @@ export interface FinishJob {
signature: string;
projectDir: string;
compPath: string;
options: { capture: boolean; gsapBaseUrl: string; sandboxedCapture: boolean };
options: {
capture: boolean;
gsapBaseUrl: string;
gsapMirror?: string | null;
sandboxedCapture: boolean;
};
variables?: Record<string, unknown>;
}
@@ -818,6 +818,29 @@ describe("registerPreviewRoutes", () => {
return [...parseHTML(html).document.querySelectorAll("script[src]")];
}
// fails without the fix: a page whose GSAP is the project's own file got the plugin from jsDelivr, a fetch
// a preview with no network cannot make and a script from a third party the page never named.
it.each([
[
"its own file",
'<script src="vendor/gsap.min.js"></script>',
"vendor/MotionPathPlugin.min.js",
],
[
"a file the build inlined",
'<script data-hf-inlined-src="vendor/gsap.min.js">/* gsap */</script>',
"vendor/MotionPathPlugin.min.js",
],
])(
"loads the MotionPathPlugin from beside the page's GSAP when that is %s",
async (_, tag, plugin) => {
const scripts = await previewScriptSrcs(tag);
const srcs = scripts.map((el) => el.getAttribute("src") ?? "");
expect(srcs).toContain(plugin);
expect(srcs.filter((src) => /jsdelivr|^https?:/.test(src))).toEqual([]);
},
);
it.each([
["a query string", "https://cdn.jsdelivr.net/npm/gsap@3/dist/gsap.min.js?v=1"],
["a hash", "https://cdn.jsdelivr.net/npm/gsap@3/dist/gsap.js#core"],
@@ -3340,7 +3363,31 @@ describe("GSAP mirror configuration", () => {
);
});
it("preserves authored plugins and the default CDN when the override is unset", async () => {
// fails without the fix: an explicit jsDelivr mirror and no mirror shared an ETag, so after the mirror was
// removed a revalidation got a 304 and kept the cached page with the CDN plugin.
it.each(["", "/comp/scene.html"])(
"revalidates %s when the mirror setting changes",
async (suffix) => {
const projectDir = createProjectDir();
const source = `<html><head><script src="vendor/gsap.min.js"></script></head><body><script>gsap.to("#card", { motionPath: {} });</script></body></html>`;
writeFileSync(join(projectDir, "index.html"), source);
writeFileSync(join(projectDir, "scene.html"), source);
const url = previewUrl + suffix;
const first = await appForMirror(projectDir, "https://cdn.jsdelivr.net/npm").request(url);
const etag = first.headers.get("ETag");
expect(etag).toBeTruthy();
const again = await appForMirror(projectDir, "").request(url, {
headers: { "If-None-Match": etag! },
});
expect(again.status).toBe(200);
const plugin = parseHTML(await again.text()).document.querySelector(
'script[src*="MotionPathPlugin"]',
);
expect(plugin?.getAttribute("src")).toBe("vendor/MotionPathPlugin.min.js");
},
);
it("preserves authored plugins, and names no plugin base when the override is unset", async () => {
const projectDir = createProjectDir();
const plugin = "https://authored.example/MotionPathPlugin.min.js";
writeFileSync(
@@ -3353,11 +3400,7 @@ describe("GSAP mirror configuration", () => {
).toHaveLength(1);
expect(configured).toContain(`src="${plugin}"`);
const defaults = await (await appForMirror(projectDir, "").request(previewUrl)).text();
expect(
parseHTML(defaults)
.document.querySelector(`meta[name="${metaName}"]`)
?.getAttribute("content"),
).toBe("https://cdn.jsdelivr.net/npm");
expect(parseHTML(defaults).document.querySelector(`meta[name="${metaName}"]`)).toBeNull();
expect(defaults).toContain('var cdnBase="https://cdn.jsdelivr.net/npm/gsap@3.15.0/dist/"');
});
@@ -3521,7 +3564,8 @@ describe("bundled GSAP local root", () => {
expect(withPath).not.toContain("jsdelivr");
});
it("loads a plugin for another GSAP version from jsDelivr", async () => {
// fails without the fix: the plugin for another GSAP version came from jsDelivr, a host the page never named.
it("loads the bundled plugin for another GSAP version, never jsDelivr", async () => {
const projectDir = createProjectDir();
writeFileSync(
join(projectDir, "index.html"),
@@ -3532,7 +3576,8 @@ describe("bundled GSAP local root", () => {
parseHTML(html)
.document.querySelector('script[src*="MotionPathPlugin"]')
?.getAttribute("src"),
).toBe("https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/MotionPathPlugin.min.js");
).toBe(`${localRoot}/gsap@3.15.0/dist/MotionPathPlugin.min.js`);
expect(html).not.toContain("jsdelivr");
});
it("prefers HYPERFRAMES_GSAP_BASE_URL over the bundled copy", async () => {
@@ -3588,3 +3633,68 @@ describe("preview asset colour tags", () => {
expect(response.headers.get("Content-Length") ?? String(body.length)).toBe(String(body.length));
});
});
describe("where the preview's MotionPathPlugin tag points", () => {
afterEach(() => vi.unstubAllEnvs());
const pageUrl = "http://localhost/projects/demo/preview";
const LOCAL = "http://localhost/api/vendor/npm/gsap@3.15.0/dist/MotionPathPlugin.min.js";
const MIRROR = "https://mirror.example/npm/gsap@3.15.0/dist/MotionPathPlugin.min.js";
// fails without the fix: row "local root, other site". The bundled root was written as a path, which the
// page's <base> on another site resolved there; the runtime now loads it on demand from the document.
it.each<[string, string | null, string | null]>([
["nothing", null, "http://localhost/api/projects/demo/preview/vendor/MotionPathPlugin.min.js"],
[
"nothing",
"https://assets.example/film/",
"https://assets.example/film/vendor/MotionPathPlugin.min.js",
],
["local root", null, LOCAL],
["local root", "https://assets.example/film/", null],
["mirror", null, MIRROR],
["mirror", "https://assets.example/film/", MIRROR],
["nothing", "assets/", "http://localhost/projects/demo/assets/vendor/MotionPathPlugin.min.js"],
["local root", "assets/", LOCAL],
])("writes the tag with %s configured under the base %s", async (setup, base, expected) => {
const projectDir = createProjectDir();
writeFileSync(
join(projectDir, "index.html"),
`<!doctype html><html><head>${base ? `<base href="${base}">` : ""}</head><body><div id="card"></div>
<script src="vendor/gsap.min.js"></script>
<script>gsap.to("#card", { motionPath: { path: [{ x: 100, y: 50 }] } });</script>
</body></html>`,
);
vi.stubEnv("HYPERFRAMES_GSAP_BASE_URL", setup === "mirror" ? "https://mirror.example/npm" : "");
const app = new Hono();
registerPreviewRoutes(
app,
createAdapter(projectDir, setup === "local root" ? { gsapLocalRoot: "/api/vendor/npm" } : {}),
);
const doc = parseHTML(await (await app.request(pageUrl)).text()).document;
const src = doc.querySelector('script[src*="MotionPathPlugin"]')?.getAttribute("src");
const baseUrl = new URL(doc.querySelector("base[href]")?.getAttribute("href") ?? "", pageUrl);
expect(src === undefined ? null : new URL(src, baseUrl).href).toBe(expected);
});
// fails without the fix: under <base href="assets/"> the plugin was written from the site root, so it
// missed the folder the page's GSAP loads from and 404ed.
it("puts the plugin in the folder the page's GSAP loads from under a relative base", async () => {
const projectDir = createProjectDir();
writeFileSync(
join(projectDir, "index.html"),
`<!doctype html><html><head><base href="assets/"></head><body><div id="card"></div>
<script src="vendor/gsap.min.js"></script>
<script>gsap.to("#card", { motionPath: { path: [{ x: 100, y: 50 }] } });</script>
</body></html>`,
);
vi.stubEnv("HYPERFRAMES_GSAP_BASE_URL", "");
const app = new Hono();
registerPreviewRoutes(app, createAdapter(projectDir));
const doc = parseHTML(await (await app.request(pageUrl)).text()).document;
const baseUrl = new URL(doc.querySelector("base[href]")?.getAttribute("href") ?? "", pageUrl);
const at = (selector: string) =>
new URL(doc.querySelector(selector)?.getAttribute("src") ?? "missing", baseUrl).href;
const gsapFolder = at('script[src$="/gsap.min.js"]').replace(/gsap\.min\.js$/, "");
expect(at('script[src*="MotionPathPlugin"]')).toBe(`${gsapFolder}MotionPathPlugin.min.js`);
});
});
+66 -26
View File
@@ -8,6 +8,7 @@ import { join, resolve } from "node:path";
import { createHash } from "node:crypto";
import {
AFTER_FONTS_SCRIPT_TYPE,
INLINED_FILE_ATTR,
RUNTIME_BOOTSTRAP_ATTR,
insertBeforeCloseTag,
insertRuntimeTag,
@@ -34,7 +35,8 @@ import {
GSAP_PLUGIN_LOAD_ATTR,
NO_PATH_TWEEN_META,
gsapCdnDist,
motionPathPluginUrl,
motionPathBesideGsap,
previewMotionPathSrc,
namesMotionPath,
normalizeGsapBaseUrl,
normalizeGsapLocalRoot,
@@ -312,20 +314,38 @@ function htmlHasMotionPathPlugin(html: string): boolean {
);
}
function injectMotionPathPluginIfNeeded(html: string, baseUrl: string): string {
// The plugin goes right after the page's GSAP, beside it as the page wrote it. The cached tag is the same for every
// visitor, so a local root's origin is a stand-in: written as a path, it holds only under a same-origin base.
const PREVIEW_DOCUMENT = "http://preview.invalid/preview";
function pluginTagSrc(html: string, gsapFile: string | null, mirror: string | null): string | null {
const baseHref = parseHTML(html).document.querySelector("base[href]")?.getAttribute("href");
const baseUrl = new URL(
baseHref && URL.canParse(baseHref, PREVIEW_DOCUMENT) ? baseHref : "",
PREVIEW_DOCUMENT,
);
const href = previewMotionPathSrc({
gsapFile,
mirror,
documentUrl: PREVIEW_DOCUMENT,
baseUrl: baseUrl.href,
pageOwned: true,
});
if (!href || !mirror) return href && gsapFile && motionPathBesideGsap(gsapFile);
const own = new URL(PREVIEW_DOCUMENT).origin;
if (new URL(href).origin !== own) return href;
return baseUrl.origin === own ? href.slice(own.length) : null;
}
function injectMotionPathPluginIfNeeded(html: string, mirror: string | null = null): string {
if (!htmlUsesMotionPath(html) || htmlHasMotionPathPlugin(html)) return html;
// The plugin registers onto an already-loaded gsap, so it must come AFTER the
// core gsap script — which often lives at body-end, not <head>. Insert it
// directly after the gsap script tag; only fall back to <head> if none is found
// (e.g. gsap is inlined).
const gsap = findGsapCoreScript(html);
if (gsap) {
const version = gsap.src.match(/gsap@([\d.]+)/)?.[1];
const ordering = `${gsap.type ? ` type="${gsap.type}"` : ""}${gsap.defer ? " defer" : ""}`;
const pluginTag = `<script${ordering} src="${escapeGsapUrl(motionPathPluginUrl(version, baseUrl))}"></script>`;
return html.slice(0, gsap.end) + "\n" + pluginTag + html.slice(gsap.end);
}
return injectScriptTagIntoHead(html, gsapScriptTag("MotionPathPlugin.min.js", baseUrl));
const src = pluginTagSrc(html, gsap?.src ?? null, mirror);
if (!src) return html;
if (!gsap) return injectScriptTagIntoHead(html, `<script src="${escapeGsapUrl(src)}"></script>`);
const ordering = `${gsap.type ? ` type="${gsap.type}"` : ""}${gsap.defer ? " defer" : ""}`;
const pluginTag = `<script${ordering} src="${escapeGsapUrl(src)}"></script>`;
return html.slice(0, gsap.end) + "\n" + pluginTag + html.slice(gsap.end);
}
type GsapCoreScript = { src: string; type: string | null; defer: boolean; end: number };
@@ -335,15 +355,15 @@ function findGsapCoreScript(html: string): GsapCoreScript | null {
// The scanner skips comments, raw text and templates, so its `<script` offsets line up with the DOM's scripts.
const starts = findStartTags(html, "script");
if (starts.length !== scripts.length) return null;
const at = scripts.findIndex((script) =>
isGsapCoreUrl(lowerCaseAttributes(script).get("src") ?? ""),
);
const fileOf = (attributes: Map<string, string>) =>
attributes.get("src") ?? attributes.get(INLINED_FILE_ATTR) ?? "";
const at = scripts.findIndex((script) => isGsapCoreUrl(fileOf(lowerCaseAttributes(script))));
if (at === -1) return null;
const attributes = lowerCaseAttributes(scripts[at]!);
const end = scriptCloseEnd(html, starts[at]!);
if (end === 0) return null;
return {
src: attributes.get("src")!,
src: fileOf(attributes),
type: attributes.get("type") ?? null,
defer: attributes.has("defer"),
end,
@@ -499,7 +519,13 @@ export function injectStudioPreviewAugmentations(
signature: string,
projectDir: string,
activeCompositionPath: string,
options: { capture: boolean; gsapBaseUrl: string; sandboxedCapture: boolean; pathFree?: boolean },
options: {
capture: boolean;
gsapBaseUrl: string;
gsapMirror?: string | null;
sandboxedCapture: boolean;
pathFree?: boolean;
},
): string {
const studioMotion = readStudioMotion(projectDir, activeCompositionPath);
const noTimelineToCome =
@@ -519,8 +545,9 @@ export function injectStudioPreviewAugmentations(
injectProjectSignature(
injectTagsAtHeadStart(
marked,
`<meta name="${GSAP_BASE_URL_META}" content="${escapeGsapUrl(options.gsapBaseUrl)}">` +
(!studioMotion && options.pathFree ? `<meta name="${NO_PATH_TWEEN_META}">` : ""),
(options.gsapMirror
? `<meta name="${GSAP_BASE_URL_META}" content="${escapeGsapUrl(options.gsapMirror)}">`
: "") + (!studioMotion && options.pathFree ? `<meta name="${NO_PATH_TWEEN_META}">` : ""),
),
signature,
),
@@ -534,7 +561,10 @@ export function injectStudioPreviewAugmentations(
options.gsapBaseUrl,
)
: withFallback;
const withPlugin = injectMotionPathPluginIfNeeded(withMotionDependencies, options.gsapBaseUrl);
const withPlugin = injectMotionPathPluginIfNeeded(
withMotionDependencies,
options.gsapMirror ?? null,
);
return studioMotion ? injectStudioMotionScript(withPlugin, studioMotion.script) : withPlugin;
}
@@ -601,11 +631,16 @@ export const withPreviewBase = (html: string, projectId: string) => {
return hasBaseElement(mapped) ? mapped : injectTagsAtHeadStart(mapped, `<base href="${base}">`);
};
function resolvePreviewGsapBaseUrl(adapter: PreviewApiAdapter): string {
/** The GSAP root the preview rewrites to, and the same root when someone configured it (else null). */
function resolvePreviewGsap(adapter: PreviewApiAdapter): {
gsapBaseUrl: string;
gsapMirror: string | null;
} {
const configured = process.env.HYPERFRAMES_GSAP_BASE_URL;
if (configured?.trim() || !adapter.gsapLocalRoot) {
try {
return normalizeGsapBaseUrl(configured);
const gsapBaseUrl = normalizeGsapBaseUrl(configured);
return { gsapBaseUrl, gsapMirror: configured?.trim() ? gsapBaseUrl : null };
} catch (cause) {
throw new Error(
"Invalid HYPERFRAMES_GSAP_BASE_URL: use an absolute HTTPS npm mirror root (plain HTTP only for localhost) without credentials, query, or fragment",
@@ -613,7 +648,8 @@ function resolvePreviewGsapBaseUrl(adapter: PreviewApiAdapter): string {
);
}
}
return normalizeGsapLocalRoot(adapter.gsapLocalRoot);
const gsapBaseUrl = normalizeGsapLocalRoot(adapter.gsapLocalRoot);
return { gsapBaseUrl, gsapMirror: gsapBaseUrl };
}
export function registerPreviewRoutes(
@@ -624,8 +660,9 @@ export function registerPreviewRoutes(
subCompositionDeadlineMs,
}: { sandboxThumbnailCaptures?: boolean; subCompositionDeadlineMs?: number } = {},
): void {
const gsapBaseUrl = resolvePreviewGsapBaseUrl(adapter);
const gsapEtagSalt = `:gsap:${createHash("sha1").update(gsapBaseUrl).digest("hex").slice(0, 12)}`;
const { gsapBaseUrl, gsapMirror } = resolvePreviewGsap(adapter);
const gsapSource = `${gsapBaseUrl}|${gsapMirror ?? "unset"}`;
const gsapEtagSalt = `:gsap:${createHash("sha1").update(gsapSource).digest("hex").slice(0, 12)}`;
const previewCacheHeaders = (etag: string) => ({
"Cache-Control": "private, no-cache",
ETag: etag,
@@ -695,6 +732,7 @@ export function registerPreviewRoutes(
const options = {
capture,
gsapBaseUrl,
gsapMirror,
sandboxedCapture: sandboxThumbnailCaptures,
pathFree: await provesNoPathTween(transformed, project.dir, rootDeadline),
};
@@ -759,6 +797,7 @@ export function registerPreviewRoutes(
{
capture,
gsapBaseUrl,
gsapMirror,
sandboxedCapture: sandboxThumbnailCaptures,
pathFree: await provesNoPathTween(fallbackPage, project.dir),
},
@@ -876,6 +915,7 @@ export function registerPreviewRoutes(
const options = {
capture,
gsapBaseUrl,
gsapMirror,
sandboxedCapture: sandboxThumbnailCaptures,
pathFree: await provesNoPathTween(transformed, project.dir, deadline),
};
@@ -25,6 +25,13 @@ tl.to("#box", { motionPath: { path: [{ x: 0, y: 0 }, { x: 100, y: 50 }] } });
window.__timelines["root"] = tl;
`;
const PAGE = "http://localhost:3000/preview";
/** The page's own GSAP file, which the plugin loads beside. */
const pageGsap = () =>
Object.assign(document.createElement("script"), { src: "vendor/gsap.min.js" });
const pageScripts = (sel: string, inline: Element[] = []) =>
sel === "script:not([src])" ? inline : sel.startsWith("script[src]") ? [pageGsap()] : [];
function buildMockIframe(overrides: Record<string, unknown> = {}) {
const scriptEl = document.createElement("script");
scriptEl.textContent =
@@ -59,7 +66,9 @@ function buildMockIframe(overrides: Record<string, unknown> = {}) {
};
const contentDocument = {
querySelectorAll: (sel: string) => (sel === "script:not([src])" ? [scriptEl] : []),
URL: PAGE,
baseURI: PAGE,
querySelectorAll: (sel: string) => pageScripts(sel, [scriptEl]),
createElement: (tag: string) => document.createElement(tag),
body: container,
head: document.createElement("div"),
@@ -307,7 +316,7 @@ window.__timelines["root"] = tl;`;
// script has NOT executed yet, so the timeline isn't rebound synchronously.
expect(result).toBe("applied");
expect(appendedScripts).toHaveLength(1);
expect(appendedScripts[0]!.src).toContain("gsap@3.14.2/dist/MotionPathPlugin");
expect(appendedScripts[0]!.src).toBe("http://localhost:3000/vendor/MotionPathPlugin.min.js");
expect(contentWindow.__hfForceTimelineRebind).not.toHaveBeenCalled();
// onerror must NOT run the script (that would reference a missing plugin) —
@@ -478,6 +487,9 @@ function buildBootstrapIframe(overrides: Record<string, unknown> = {}, pathFree
...overrides,
};
const contentDocument = {
URL: PAGE,
baseURI: PAGE,
querySelectorAll: (sel: string) => pageScripts(sel),
createElement: (tag: string) => document.createElement(tag),
querySelector: (sel: string) =>
pathFree && sel === `meta[name="${NO_PATH_TWEEN_META}"]`
@@ -574,14 +586,12 @@ describe("ensureMotionPathPluginLoaded", () => {
expect(appendedScripts[0]!.hasAttribute(GSAP_PLUGIN_LOAD_ATTR)).toBe(true);
});
it("loads the plugin at the composition's own gsap version", () => {
it("loads the plugin from beside the page's own GSAP, whatever its version", () => {
const { iframe, appendedScripts } = buildBootstrapIframe({
gsap: { version: "3.14.2", registerPlugin: vi.fn() },
});
ensureMotionPathPluginLoaded(iframe);
expect(appendedScripts[0]!.src).toBe(
"https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/MotionPathPlugin.min.js",
);
expect(appendedScripts[0]!.src).toBe("http://localhost:3000/vendor/MotionPathPlugin.min.js");
});
it("preloads from the iframe mirror once, retaining the runtime version", () => {
@@ -605,10 +615,10 @@ describe("ensureMotionPathPluginLoaded", () => {
});
it.each([
["3.15.0", "/api/vendor/npm/gsap@3.15.0/dist/MotionPathPlugin.min.js"],
["3.14.2", "https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/MotionPathPlugin.min.js"],
["3.15.0", "http://localhost:3000/api/vendor/npm/gsap@3.15.0/dist/MotionPathPlugin.min.js"],
["3.14.2", "http://localhost:3000/api/vendor/npm/gsap@3.15.0/dist/MotionPathPlugin.min.js"],
])(
"preloads gsap %s from the host's bundled copy only when it holds that version",
"preloads gsap %s from the host's bundled copy at its own version, never the CDN",
(version, url) => {
const { iframe, appendedScripts } = buildBootstrapIframe({
gsap: { version, registerPlugin: vi.fn() },
@@ -15,7 +15,10 @@ import {
vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 });
const require = createRequire(import.meta.url);
const STUDIO_MARK = '<meta name="hyperframes-studio-preview" content="1" />';
// A srcdoc preview has no origin of its own, so its plugin comes from a configured mirror, as Studio configures one.
const STUDIO_MARK =
'<meta name="hyperframes-studio-preview" content="1" />' +
'<meta name="hyperframes-gsap-base-url" content="https://fixture.hyperframes.test/npm" />';
const MODES = process.env.HF_PARITY_MODE ? [process.env.HF_PARITY_MODE] : ["unsealed", "sealed"];
let browser: Browser;
let studioBundle: string;