fix(core): load the motion path plugin only for a page that tweens along a path (#8449)

* fix(core): load the motion path plugin only for a page that tweens along a path

* fix(core): a path tween an external script builds still gets the motion path plugin

* test(studio): a path tween from an external script gets the plugin when Studio connects

* fix(core): a page with a script the preview cannot read still gets the motion path plugin

* fix(studio-server): the preview builder, not a file name, decides a page needs no path plugin

* refactor(studio-server): split the preview builder's script check

* fix(studio-server): a script the preview builder cannot read leaves the page unmarked

* fix(studio-server): the preview builder reads scripts off the event loop, within a time budget

* fix(studio-server): the preview builder resolves script paths off the event loop too

* fix(studio-server): the preview builder's script scan stays inside the request's deadline

* fix(core): the async project path check answers null for a path it cannot resolve
This commit is contained in:
Miguel Ángel
2026-11-22 09:40:47 +00:00
committed by GitHub
parent a638c31aa1
commit 4157992664
13 changed files with 537 additions and 29 deletions
+4
View File
@@ -1,6 +1,10 @@
export const GSAP_CDN_VERSION = "3.15.0";
const GSAP_CDN_BASE_URL = "https://cdn.jsdelivr.net/npm";
export const GSAP_BASE_URL_META = "hyperframes-gsap-base-url";
export const GSAP_PLUGIN_LOAD_ATTR = "data-hf-gsap-plugin";
export const NO_PATH_TWEEN_META = "hf-no-path-tween";
export const namesMotionPath = (script: string) => /motionPath["']?\s*[:{]/.test(script);
function isLoopbackHost(hostname: string): boolean {
return hostname === "localhost" || hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/.test(hostname);
@@ -1,7 +1,13 @@
// A GSAP script edit re-runs the edited composition's script in the live preview, without a reload.
// Studio runs it on a frame it can reach; a sealed frame runs it on itself through the editing port,
// with the script Studio saved and the authored styles Studio read from that file.
import { GSAP_BASE_URL_META, motionPathPluginUrl } from "../../gsapCdn";
import {
GSAP_BASE_URL_META,
GSAP_PLUGIN_LOAD_ATTR,
NO_PATH_TWEEN_META,
motionPathPluginUrl,
namesMotionPath,
} from "../../gsapCdn";
import { applyAuthoredInlineOpacity, readStampedAuthoredOpacity } from "../../colorGrading";
import { escapeCssString } from "../editingElement";
import { applyAuthoredTiming } from "../../studioPreviewMark";
@@ -407,6 +413,7 @@ function whenMotionPathLoaded(
};
const pluginScript = doc.createElement("script");
pluginScript.src = previewMotionPathUrl(doc, win.gsap?.version);
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.
pluginScript.onerror = () => settle(false);
@@ -455,12 +462,13 @@ export function swapWaiting(win: SoftReloadWindow = window as SoftReloadWindow):
return (win.__hfSwapsWaiting ?? 0) > 0;
}
/** Loads and registers MotionPathPlugin ahead of the first re-run that needs it, as Studio does same-origin. */
/** Loads and registers MotionPathPlugin ahead of a re-run that needs it, unless the page is marked path-free. */
export function preloadMotionPath(
win: SoftReloadWindow = window as SoftReloadWindow,
doc: Document = document,
): void {
if (win.MotionPathPlugin || win.__hfMotionPathWaiters || !win.gsap) return;
if (doc.querySelector(`meta[name="${NO_PATH_TWEEN_META}"]`)) return;
const register = () => win.MotionPathPlugin && win.gsap?.registerPlugin?.(win.MotionPathPlugin);
whenMotionPathLoaded(win, doc, register, () => {});
}
@@ -523,7 +531,7 @@ export function softReloadFrame(
return ran && !builtDom;
};
const needsMotionPath = /motionPath\s*[:{]/.test(script);
const needsMotionPath = namesMotionPath(script);
if (!needsMotionPath || win.MotionPathPlugin || !win.gsap) {
if (!swap(currentTime)) return "cannot-soft-reload";
return verifyTimelinesPopulated(win, targetKeys) ? "applied" : "verify-failed";
+15
View File
@@ -16,6 +16,7 @@ import {
isSafePath,
isStudioPrivatePath,
mkdirWithinProject,
resolveExistingWithinProjectOff,
resolveWithinProject,
toolTrustedFileKind,
} from "./safePath.js";
@@ -189,6 +190,20 @@ describe("resolveWithinProject", () => {
if (!tryCreateSymlink(external, join(base, "link"), "dir")) return;
expect(resolveWithinProject(base, "link/secret.txt")).toBeNull();
});
it("answers the same off the event loop for a file that exists", async () => {
const base = tmpDir("rwp-base-");
const external = tmpDir("rwp-external-");
writeFileSync(join(base, "in.js"), "in");
writeFileSync(join(external, "secret.txt"), "top secret");
expect(await resolveExistingWithinProjectOff(base, "in.js")).toBe(join(base, "in.js"));
// fails without the fix: a path that does not resolve threw instead of answering null.
expect(await resolveExistingWithinProjectOff(base, "missing.js")).toBeNull();
const escape = join("..", basename(external), "secret.txt");
expect(await resolveExistingWithinProjectOff(base, escape)).toBeNull();
if (!tryCreateSymlink(external, join(base, "link"), "dir")) return;
expect(await resolveExistingWithinProjectOff(base, "link/secret.txt")).toBeNull();
});
});
describe("mkdirWithinProject", () => {
+18 -1
View File
@@ -105,10 +105,27 @@ export function isSafePath(base: string, resolved: string): boolean {
const targetReal = trailing.length
? join(ancestorReal, ...[...trailing].reverse())
: ancestorReal;
return targetReal === baseReal || targetReal.startsWith(baseReal + sep);
return realPathWithin(baseReal, targetReal);
}
}
/** The containment rule once both sides are real paths. */
export const realPathWithin = (baseReal: string, targetReal: string): boolean =>
targetReal === baseReal || targetReal.startsWith(baseReal + sep);
/** `resolveWithinProject` off the event loop: the absolute path of an existing entry inside `base`, else null. */
export async function resolveExistingWithinProjectOff(
base: string,
relativePath: string,
): Promise<string | null> {
const resolved = resolve(base, relativePath);
if (namesAnotherNetworkRoot(resolve(base), resolved)) return null;
const real = await Promise.all([realpathOff(resolve(base)), realpathOff(resolved)]).catch(
() => null,
);
return real !== null && realPathWithin(real[0], real[1]) ? resolved : null;
}
/**
* Resolve `relativePath` against `base` and return the absolute path only if it
* stays within `base` (after symlink resolution); otherwise return `null`.
@@ -1,6 +1,6 @@
import type { Stats } from "node:fs";
import { stat } from "node:fs/promises";
import { realpathOff } from "@hyperframes/core/safe-path";
import { realpathOff, resolveExistingWithinProjectOff } from "@hyperframes/core/safe-path";
import { basename, dirname, join, relative, sep } from "node:path";
import { isPrivateProjectPath } from "./safePath.js";
@@ -37,3 +37,11 @@ export async function isPrivateProjectFileOff(
);
return real === unresolvable || isPrivateProjectPath(rel(real[0], real[1]));
}
export async function resolveExistingProjectFileOff(
base: string,
relativePath: string,
): Promise<string | null> {
const file = await resolveExistingWithinProjectOff(base, relativePath);
return file === null || (await isPrivateProjectFileOff(base, file)) ? null : file;
}
@@ -0,0 +1,133 @@
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { NO_PATH_TWEEN_META } from "@hyperframes/core/gsap-cdn";
import { describe, expect, it, onTestFinished } from "vitest";
import {
injectStudioPreviewAugmentations,
provesNoPathTween,
withPreviewBase,
withPreviewRuntime,
} from "./preview";
const GSAP_FILE = "/*! GSAP 3.12.5 */ window.gsap = { timeline: function () {} };";
const PLAIN_TWEEN = '<script>gsap.timeline({ paused: true }).to("#card", { x: 300 });</script>';
const LATE_PATH_TWEEN =
'window.buildPathTween = function () { gsap.to("#card", { motionPath: { path: [{ x: 50, y: 0 }] } }); };';
function projectDir(files: Record<string, string>, links: Record<string, string> = {}): string {
const dir = mkdtempSync(join(tmpdir(), "hf-no-path-tween-"));
onTestFinished(() => rmSync(dir, { recursive: true, force: true }));
for (const [rel, content] of Object.entries(files)) {
mkdirSync(join(dir, rel, ".."), { recursive: true });
writeFileSync(join(dir, rel), content, "utf-8");
}
for (const [rel, target] of Object.entries(links)) symlinkSync(target, join(dir, rel));
return dir;
}
/** The main preview page for `scripts` in the head, as the preview route builds it, and the project it reads. */
function page(
scripts: string,
files: Record<string, string> = {},
links: Record<string, string> = {},
) {
const index = `<!doctype html><html><head>${scripts}</head><body><div id="card"></div>${PLAIN_TWEEN}</body></html>`;
const dir = projectDir({ "index.html": index, ...files }, links);
return { html: withPreviewRuntime(withPreviewBase(index, "film"), "/api/runtime.js"), dir };
}
const pathFree = (
scripts: string,
files?: Record<string, string>,
links?: Record<string, string>,
) => {
const { html, dir } = page(scripts, files, links);
return provesNoPathTween(html, dir);
};
describe("the preview builder's proof that no script can tween along a path", () => {
// fails without the fix: no preview carried the mark, so every one loaded the plugin.
it("holds for a page whose scripts are read and name no path: its own GSAP file and inline tweens", async () => {
const own = '<script src="gsap.min.js"></script>';
expect(await pathFree(own, { "gsap.min.js": GSAP_FILE })).toBe(true);
});
it("holds for a page that loads GSAP from its CDN", async () => {
const cdn = '<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>';
expect(await pathFree(cdn)).toBe(true);
});
it("fails for a project script that builds a path tween, whatever its name", async () => {
const authored = '<script src="authored/gsap.js"></script>';
expect(await pathFree(authored, { "authored/gsap.js": LATE_PATH_TWEEN })).toBe(false);
});
it("fails for a script it cannot read: another host, a missing file, a module, a folder", async () => {
expect(await pathFree('<script src="https://example.com/gsap.min.js"></script>')).toBe(false);
expect(await pathFree('<script src="missing.js"></script>')).toBe(false);
const module = '<script type="module" src="gsap.min.js"></script>';
expect(await pathFree(module, { "gsap.min.js": GSAP_FILE })).toBe(false);
expect(await pathFree('<script src="assets"></script>', { "assets/a.txt": "a" })).toBe(false);
});
it("fails for a script that links out of the project", async () => {
const outside = projectDir({ "gsap.min.js": GSAP_FILE });
const own = '<script src="gsap.min.js"></script>';
expect(await pathFree(own, {}, { "gsap.min.js": join(outside, "gsap.min.js") })).toBe(false);
});
// fails without the fix: each project script's path was resolved with a synchronous realpath on the server thread.
it("resolves project scripts without a synchronous realpath", async () => {
const { html, dir } = page('<script src="gsap.min.js"></script>', { "gsap.min.js": GSAP_FILE });
const fs = createRequire(import.meta.url)("node:fs") as typeof import("node:fs");
const native = fs.realpathSync.native;
let syncCalls = 0;
fs.realpathSync.native = ((...args: Parameters<typeof native>) => (
syncCalls++, native(...args)
)) as typeof native;
onTestFinished(() => void (fs.realpathSync.native = native));
expect(await provesNoPathTween(html, dir)).toBe(true);
expect(syncCalls).toBe(0);
});
// fails without the fix: the scan resolved and read the disk on the route's event loop, with no limit on a silent
// drive.
it.each([
[
"resolving its path",
{ resolve: () => new Promise<never>(() => {}), read: async () => GSAP_FILE },
],
[
"reading it",
{
resolve: async (base: string, rel: string) => join(base, rel),
read: () => new Promise<never>(() => {}),
},
],
])("fails when %s does not answer within the budget", async (_, files) => {
const { html, dir } = page('<script src="gsap.min.js"></script>', { "gsap.min.js": GSAP_FILE });
expect(await provesNoPathTween(html, dir, performance.now() + 100, files)).toBe(false);
});
it("fails for a page whose own text names a path", async () => {
expect(await pathFree('<script>gsap.to("#card", { "motionPath": {} });</script>')).toBe(false);
});
});
describe("the preview's path-free mark", () => {
it("is set only when the builder proved the page path-free", () => {
const { html, dir } = page("");
const augmented = (proved: boolean) =>
injectStudioPreviewAugmentations(html, "/api/runtime.js", "signature", dir, "index.html", {
capture: false,
gsapBaseUrl: "https://cdn.jsdelivr.net/npm",
sandboxedCapture: false,
pathFree: proved,
});
const mark = `<meta name="${NO_PATH_TWEEN_META}">`;
expect(augmented(true)).toContain(mark);
expect(augmented(false)).not.toContain(mark);
});
});
@@ -0,0 +1,56 @@
// @vitest-environment node
import { afterAll, describe, expect, it, vi } from "vitest";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createStudioApi } from "../createStudioApi";
import type { StudioApiAdapter } from "../types";
vi.mock("../helpers/projectDisk.js", async (real) => {
const disk = await real<typeof import("../helpers/projectDisk.js")>();
return {
...disk,
resolveExistingProjectFileOff: (base: string, rel: string) =>
rel.endsWith("held.js")
? new Promise<never>(() => {})
: disk.resolveExistingProjectFileOff(base, rel),
};
});
const projectDir = mkdtempSync(join(tmpdir(), "hf-preview-scan-deadline-"));
mkdirSync(join(projectDir, "scenes"));
writeFileSync(join(projectDir, "index.html"), "<html><head></head><body></body></html>");
writeFileSync(join(projectDir, "held.js"), "window.held = true;");
const scene = (script: string) =>
`<div data-composition-id="card" data-width="320" data-height="180"><p>Hi</p>${script}</div>`;
writeFileSync(join(projectDir, "scenes", "plain.html"), scene(""));
writeFileSync(join(projectDir, "scenes", "held.html"), scene('<script src="held.js"></script>'));
afterAll(() => rmSync(projectDir, { recursive: true, force: true }));
const adapter: StudioApiAdapter = {
listProjects: () => [],
resolveProject: async (id: string) => ({ id, dir: projectDir }),
bundle: async () => null,
lint: async () => ({ findings: [] }),
runtimeUrl: "/api/runtime.js",
rendersDir: () => join(projectDir, "renders"),
startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "/tmp/out.mp4" }),
};
const DEADLINE_MS = 200;
const api = createStudioApi(adapter, { subCompositionDeadlineMs: DEADLINE_MS });
// Starts the build worker both share, which a 200 ms request cannot wait for.
const patient = createStudioApi(adapter, { subCompositionDeadlineMs: 60_000 });
const comp = (file: string, on = api) =>
on.request(`http://localhost/projects/demo/preview/comp/scenes/${file}`);
describe("the preview builder's script scan inside a request's deadline", () => {
// fails without the fix: a held lookup kept the request for the scan's own 1 s, past a 200 ms deadline.
it("gives up within the request's time, and the preview is still served", async () => {
expect((await comp("plain.html", patient)).status).toBe(200);
expect((await comp("plain.html")).status).toBe(200);
const started = performance.now();
const res = await comp("held.html");
expect(res.status).toBe(200);
expect(performance.now() - started).toBeLessThan(500);
}, 30_000);
});
@@ -27,6 +27,7 @@ import {
STUDIO_PREVIEW_MARK_META,
} from "@hyperframes/core/studio-preview-mark";
import { AFTER_FONTS_SCRIPT_TYPE } from "@hyperframes/core/compiler";
import { GSAP_PLUGIN_LOAD_ATTR } from "@hyperframes/core/gsap-cdn";
import {
PREVIEW_BUNDLE_OPTIONS,
PREVIEW_CAPTURE_PARAM,
@@ -375,6 +376,38 @@ describe("registerPreviewRoutes", () => {
expect(message).toContain(appended[0]?.src);
});
// fails without the fix: a failed MotionPath preload was loaded again from the CDN and reported as the film's GSAP.
it("leaves the preview's own plugin load to its loader: no fallback load, no report", async () => {
const app = new Hono();
registerPreviewRoutes(app, createAdapter(createProjectDir()));
const html = await (await app.request("http://localhost/projects/demo/preview")).text();
const fallback = /<script data-hf-gsap-fallback>([\s\S]*?)<\/script>/.exec(html)?.[1] ?? "";
let onDocumentError: (event: { target: unknown }) => void = () => undefined;
const appended: unknown[] = [];
const reported: unknown[] = [];
new Function("document", "reportError", fallback)(
{
addEventListener: (_type: string, listener: typeof onDocumentError) => {
onDocumentError = listener;
},
createElement: () => ({ tagName: "SCRIPT", src: "" }),
head: { appendChild: (script: unknown) => appended.push(script) },
},
(error: unknown) => reported.push(error),
);
onDocumentError({
target: {
tagName: "SCRIPT",
src: "https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/MotionPathPlugin.min.js",
hasAttribute: (name: string) => name === GSAP_PLUGIN_LOAD_ATTR,
},
});
await new Promise((settle) => setTimeout(settle, 0));
expect(appended).toHaveLength(0);
expect(reported).toHaveLength(0);
});
it("keeps every error a Studio preview raises from its first script, and leaves captures without it", async () => {
const projectDir = createProjectDir();
writeFileSync(
+112 -9
View File
@@ -31,8 +31,11 @@ import {
} from "@hyperframes/core";
import {
GSAP_BASE_URL_META,
GSAP_PLUGIN_LOAD_ATTR,
NO_PATH_TWEEN_META,
gsapCdnDist,
motionPathPluginUrl,
namesMotionPath,
normalizeGsapBaseUrl,
normalizeGsapLocalRoot,
} from "@hyperframes/core/gsap-cdn";
@@ -47,7 +50,11 @@ import {
projectRelativePath,
resolveWithinProject,
} from "../helpers/safePath.js";
import { isPrivateProjectFileOff, statOrNull } from "../helpers/projectDisk.js";
import {
isPrivateProjectFileOff,
resolveExistingProjectFileOff,
statOrNull,
} from "../helpers/projectDisk.js";
import { getMimeType } from "../helpers/mime.js";
import { serveWhileOpen } from "../helpers/servedFiles.js";
import { openRangeEnd } from "../helpers/mediaRange.js";
@@ -192,7 +199,81 @@ function htmlHasCustomEase(html: string): boolean {
// throws "Invalid property motionPath ... Missing plugin?". Detect it anywhere in
// the bundle (the plugin registers globally, so sub-composition usage counts too).
function htmlUsesMotionPath(html: string): boolean {
return /motionPath\s*[:{]/.test(html);
return namesMotionPath(html);
}
const SCRIPT_SRC_ATTR = /\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i;
const GSAP_ON_ITS_CDN = /^https:\/\/cdn\.jsdelivr\.net\/npm\/gsap@[\d.]+\/dist\/[\w.-]+\.js$/;
const PROJECT_PREVIEW_BASE =
/<base\b[^>]*\shref\s*=\s*["']\/api\/projects\/[^/"']+\/preview\/["']/i;
const MAX_READ_SCRIPT_BYTES = 4 * 1024 * 1024;
const SCRIPT_SCAN_MS = 1000;
/** How the scan reaches a project's files: both off the event loop. */
interface ScriptFiles {
resolve: (base: string, relativePath: string) => Promise<string | null>;
read: (file: string) => Promise<string>;
}
const projectFiles: ScriptFiles = {
resolve: resolveExistingProjectFileOff,
read: (file) => readFile(file, "utf-8"),
};
async function projectScriptNamesNoPath(
src: string,
projectDir: string,
files: ScriptFiles,
): Promise<boolean> {
if (/^(?:[a-z][\w+.-]*:|\/)/i.test(src)) return false;
try {
const file = await files.resolve(projectDir, decodeURIComponent(src.split(/[?#]/)[0]!));
if (file === null) return false;
const info = await statFile(file);
if (!info.isFile() || info.size > MAX_READ_SCRIPT_BYTES) return false;
return !namesMotionPath(await files.read(file));
} catch {
return false;
}
}
async function scriptCannotTweenAlongPath(
tag: string,
projectDir: string,
files: ScriptFiles,
): Promise<boolean> {
if (tag.includes(RUNTIME_BOOTSTRAP_ATTR)) return true;
if (/\stype\s*=\s*["']?module\b/i.test(tag)) return false;
const match = SCRIPT_SRC_ATTR.exec(tag);
if (!match) return true;
const src = (match[1] ?? match[2] ?? match[3] ?? "").replace(/&amp;/gi, "&");
return GSAP_ON_ITS_CDN.test(src) || projectScriptNamesNoPath(src, projectDir, files);
}
/** True only when no script the page loads can tween along a path: the page's text and each project script it loads
* name no `motionPath`, and any other script is GSAP on its CDN. Unsure or late is false, and the page preloads. The
* scan takes at most half of the time left before `requestDeadline`, so the preview itself keeps the rest. */
export async function provesNoPathTween(
html: string,
projectDir: string,
requestDeadline = Number.POSITIVE_INFINITY,
files = projectFiles,
): Promise<boolean> {
if (namesMotionPath(html) || /\sdata-composition-src\s*=/i.test(html)) return false;
if ((html.match(/<base\b/gi) ?? []).length !== 1 || !PROJECT_PREVIEW_BASE.test(html))
return false;
const now = performance.now();
const deadline = now + Math.min(SCRIPT_SCAN_MS, (requestDeadline - now) / 2);
if (deadline <= now) return false;
const scripts = findStartTags(html, "script").map((start) =>
scriptCannotTweenAlongPath(html.slice(start, html.indexOf(">", start) + 1), projectDir, files),
);
try {
const answers = await withinDeadline(Promise.all(scripts), deadline, "scripts");
return answers.every(Boolean);
} catch {
return false;
}
}
function htmlHasMotionPathPlugin(html: string): boolean {
@@ -303,7 +384,7 @@ function gsapCdnFallbackScript(baseUrl: string): string {
}
document.addEventListener("error",function(e){
var t=e.target;
if(!t||t.tagName!=="SCRIPT"||!t.src||t.hfGsapFallback)return;
if(!t||t.tagName!=="SCRIPT"||!t.src||t.hfGsapFallback||(t.hasAttribute&&t.hasAttribute(${scriptJson(GSAP_PLUGIN_LOAD_ATTR)})))return;
var m=t.src.match(/gsap[^/]*\\/dist\\/(.+\\.js)/);
if(m)loadFallback(m[1]).catch(function(){
reportError(new Error("GSAP could not load from "+t.src+" or "+cdnBase+m[1]+", so this preview's animations will not play."));
@@ -390,7 +471,7 @@ export function injectStudioPreviewAugmentations(
signature: string,
projectDir: string,
activeCompositionPath: string,
options: { capture: boolean; gsapBaseUrl: string; sandboxedCapture: boolean },
options: { capture: boolean; gsapBaseUrl: string; sandboxedCapture: boolean; pathFree?: boolean },
): string {
const studioMotion = readStudioMotion(projectDir, activeCompositionPath);
const noTimelineToCome =
@@ -410,7 +491,8 @@ export function injectStudioPreviewAugmentations(
injectProjectSignature(
injectTagsAtHeadStart(
marked,
`<meta name="${GSAP_BASE_URL_META}" content="${escapeGsapUrl(options.gsapBaseUrl)}">`,
`<meta name="${GSAP_BASE_URL_META}" content="${escapeGsapUrl(options.gsapBaseUrl)}">` +
(!studioMotion && options.pathFree ? `<meta name="${NO_PATH_TWEEN_META}">` : ""),
),
signature,
),
@@ -579,7 +661,12 @@ export function registerPreviewRoutes(
project,
mainCompositionPath,
);
const options = { capture, gsapBaseUrl, sandboxedCapture: sandboxThumbnailCaptures };
const options = {
capture,
gsapBaseUrl,
sandboxedCapture: sandboxThumbnailCaptures,
pathFree: await provesNoPathTween(transformed, project.dir, rootDeadline),
};
const job = {
runtimeUrl: adapter.runtimeUrl,
signature,
@@ -626,13 +713,24 @@ export function registerPreviewRoutes(
withPreviewBase(ensureHfIds(fallback.html), project.id),
adapter.runtimeUrl,
);
const fallbackPage = await transformPreviewHtml(
fallbackHtml,
adapter,
project,
fallback.compositionPath,
);
let fallbackAugmented = injectStudioPreviewAugmentations(
await transformPreviewHtml(fallbackHtml, adapter, project, fallback.compositionPath),
fallbackPage,
adapter.runtimeUrl,
signature,
project.dir,
fallback.compositionPath,
{ capture, gsapBaseUrl, sandboxedCapture: sandboxThumbnailCaptures },
{
capture,
gsapBaseUrl,
sandboxedCapture: sandboxThumbnailCaptures,
pathFree: await provesNoPathTween(fallbackPage, project.dir),
},
);
if (previewVariables) {
fallbackAugmented = injectPreviewVariables(fallbackAugmented, previewVariables);
@@ -745,7 +843,12 @@ export function registerPreviewRoutes(
deadline,
compPath,
);
const options = { capture, gsapBaseUrl, sandboxedCapture: sandboxThumbnailCaptures };
const options = {
capture,
gsapBaseUrl,
sandboxedCapture: sandboxThumbnailCaptures,
pathFree: await provesNoPathTween(transformed, project.dir, deadline),
};
const finish = { kind: "finish" as const, ...job, html: transformed, signature, options };
const html = await runOffThread(
{ ...finish, ...(previewVariables && { variables: previewVariables }) },
@@ -3,6 +3,7 @@
import { patchRuntimeTweenInPlace } from "../hooks/gsapRuntimePatch";
import { afterEach, describe, it, expect, vi } from "vitest";
import { GSAP_PLUGIN_LOAD_ATTR, NO_PATH_TWEEN_META } from "@hyperframes/core/gsap-cdn";
import {
readNestedFiles,
applySoftReload,
@@ -458,7 +459,9 @@ describe("applySoftReloadFinalization", () => {
});
});
function buildBootstrapIframe(overrides: Record<string, unknown> = {}) {
/** A preview frame for the plugin preload; `pathFree` is the preview builder's mark that no script can tween along
* a path. */
function buildBootstrapIframe(overrides: Record<string, unknown> = {}, pathFree = false) {
const head = document.createElement("div");
const appendedScripts: HTMLScriptElement[] = [];
const realHeadAppend = head.appendChild.bind(head);
@@ -476,6 +479,10 @@ function buildBootstrapIframe(overrides: Record<string, unknown> = {}) {
};
const contentDocument = {
createElement: (tag: string) => document.createElement(tag),
querySelector: (sel: string) =>
pathFree && sel === `meta[name="${NO_PATH_TWEEN_META}"]`
? document.createElement("meta")
: null,
head,
};
return {
@@ -547,6 +554,26 @@ describe("ensureMotionPathPluginLoaded", () => {
});
});
// fails without the fix: every GSAP preview fetched the plugin, so an offline one reported its animations broken.
it("loads no plugin for a page the preview builder marked as unable to tween along a path", () => {
const { iframe, appendedScripts } = buildBootstrapIframe({}, true);
ensureMotionPathPluginLoaded(iframe);
expect(appendedScripts).toHaveLength(0);
});
it("loads the plugin for any page without that mark", () => {
const { iframe, appendedScripts } = buildBootstrapIframe();
ensureMotionPathPluginLoaded(iframe);
expect(appendedScripts).toHaveLength(1);
});
// fails without the fix: the page's GSAP fallback took the plugin's failure for the film's and reported it.
it("marks the plugin script as the preview's own load, so the page's GSAP fallback leaves it alone", () => {
const { iframe, appendedScripts } = buildBootstrapIframe();
ensureMotionPathPluginLoaded(iframe);
expect(appendedScripts[0]!.hasAttribute(GSAP_PLUGIN_LOAD_ATTR)).toBe(true);
});
it("loads the plugin at the composition's own gsap version", () => {
const { iframe, appendedScripts } = buildBootstrapIframe({
gsap: { version: "3.14.2", registerPlugin: vi.fn() },
+3 -3
View File
@@ -34,9 +34,9 @@ export {
type IframeWindow = SoftReloadWindow & { __playerReady?: boolean };
/**
* Pre-load and register MotionPathPlugin once per preview load (NLELayout's onIframeLoad), so
* adding the first motion path does not wait for the CDN mid-reload and flash. Idempotent; without
* gsap it waits for the runtime's ready, and a CDN failure is left to the soft reload's own load.
* Pre-load and register MotionPathPlugin once per preview load (NLELayout's onIframeLoad) unless the page is marked
* path-free; a first path added by an edit waits for it on its re-run. Idempotent; without gsap it waits for the
* runtime's ready, and a CDN failure is left to the soft reload's own load.
*/
// At most one preview waits for its runtime; a newer load replaces it, so a frame that never boots is not kept alive.
let pendingReadyRetry: ((event: MessageEvent) => void) | null = null;
@@ -4,6 +4,7 @@ import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import type { Browser, Page } from "puppeteer-core";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { NO_PATH_TWEEN_META } from "@hyperframes/core/gsap-cdn";
import { closeTestChrome, launchTestChrome } from "../../tests/chromeTestUtils";
import {
buildStudioBundle,
@@ -51,8 +52,8 @@ function timeline(key: "main" | "other", name: string, x: number, motion = false
})();${motion ? "\n// motionPath: held until the plugin loads" : ""}`;
}
/** A Studio preview page with two timelines, "main" and "other", GSAP and the runtime inline. */
function previewHtml(): string {
/** A Studio preview page with two timelines, "main" (`main`'s script tag) and "other", GSAP and the runtime inline. */
function previewHtml(main = `<script>${timeline("main", "file", 120)}</script>`): string {
const gsap = readFileSync(require.resolve("gsap/dist/gsap.min.js"), "utf8");
const runtime = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8");
const box = (id: string, track: number, style: string) =>
@@ -65,7 +66,7 @@ function previewHtml(): string {
${box("target", 1, "left: 100px; top: 100px")}${box("b", 2, "left: 600px; top: 100px")}
<div id="c" data-hf-id="c" class="clip box" data-start="0" data-duration="4" data-track-index="3" style="left: 0px; top: 500px"></div>
</div>
<script>${gsap}</script><script>${timeline("main", "file", 120)}</script><script>${timeline("other", "file", 120)}</script>
<script>${gsap}</script>${main}<script>${timeline("other", "file", 120)}</script>
<script>${runtime}</script></body></html>`;
}
@@ -300,24 +301,123 @@ describe.each(MODES)("a re-run waiting for the MotionPath plugin, %s", (mode) =>
});
});
const PATH_TWEEN = `(function () {
window.__timelines = window.__timelines || {};
var tl = gsap.timeline({ paused: true });
tl.to("#target", { motionPath: { path: [{ x: 0, y: 0 }, { x: 50, y: 0 }] }, duration: 4, ease: "none" }, 0);
window.__timelines["main"] = tl;
})();`;
const PATH_TWEEN_URL = "https://fixture.hyperframes.test/path-tween.js";
/** Studio meeting a freshly loaded preview: the same-origin preload (NLEContext), then the editing port. */
const connect = (page: Page) =>
page.evaluate(async () => {
const studio = (window as unknown as { hfStudio: Studio }).hfStudio;
const iframe = document.querySelector("iframe")!;
studio.ensureMotionPathPluginLoaded(iframe);
await studio.previewRequest(iframe, "runtime-snapshot", {});
});
const pluginScripts = ({ frame }: Preview) =>
frame.evaluate(() => document.querySelectorAll('script[src*="MotionPathPlugin"]').length);
// Parity: a same-origin preview gets the plugin on load (NLEContext), and a sealed one when Studio connects.
it.each(MODES)(
"the first motion-path re-run after load finds the plugin loaded (%s)",
async (mode) => {
const { page, frame, release } = await openPreview(mode);
const { page, frame, release } = await openSharedPreview(
browser,
studioBundle,
previewHtml(`<script>${PATH_TWEEN}</script>`),
mode,
);
await release(200);
await page.evaluate(async () => {
const studio = (window as unknown as { hfStudio: Studio }).hfStudio;
const iframe = document.querySelector("iframe")!;
studio.ensureMotionPathPluginLoaded(iframe);
await studio.previewRequest(iframe, "runtime-snapshot", {});
});
await connect(page);
await frame.waitForFunction(() => "MotionPathPlugin" in window, { timeout: 5_000 });
expect(await rerun(page, timeline("main", "older", 60, true), 1)).toBe("applied");
await page.close();
},
);
// fails without the fix: the preload read only inline scripts, so this page's plugin was never requested.
it.each(MODES)(
"a path tween from an external script gets the plugin when Studio connects (%s)",
async (mode) => {
const preview = await openSharedPreview(
browser,
studioBundle,
previewHtml(`<script src="${PATH_TWEEN_URL}"></script>`),
mode,
{ [PATH_TWEEN_URL]: PATH_TWEEN },
);
await preview.release(200);
await connect(preview.page);
expect(await pluginScripts(preview)).toBe(1);
await preview.frame.waitForFunction(() => "MotionPathPlugin" in window, { timeout: 5_000 });
await preview.page.close();
},
);
const LATE_PATH_TWEEN = `(function () {
window.__timelines = window.__timelines || {};
var tl = gsap.timeline({ paused: true });
window.__timelines["main"] = tl;
window.buildPathTween = function () {
tl.to("#target", { motionPath: { path: [{ x: 0, y: 0 }, { x: 50, y: 0 }] }, duration: 4, ease: "none" }, 0);
};
})();`;
const LATE_TWEEN_CASES = MODES.flatMap((mode) =>
[PATH_TWEEN_URL, "https://fixture.hyperframes.test/authored/gsap.js"].map(
(url) => [mode, url] as const,
),
);
// fails without the fix: an external script that builds its first path tween after connect, named gsap.js, got no
// plugin and stayed at 0.
it.each(LATE_TWEEN_CASES)(
"a path tween an external script builds after connect plays (%s, %s)",
async (mode, url) => {
const preview = await openSharedPreview(
browser,
studioBundle,
previewHtml(`<script src="${url}"></script>`),
mode,
{ [url]: LATE_PATH_TWEEN },
);
await preview.release(200);
await connect(preview.page);
await preview.frame.waitForFunction(() => "MotionPathPlugin" in window, { timeout: 5_000 });
await preview.frame.evaluate(() =>
(window as unknown as { buildPathTween(): void }).buildPathTween(),
);
await preview.seek(4);
const x = await preview.frame.evaluate(() =>
Number(
(
window as unknown as { gsap: { getProperty(t: string, p: string): unknown } }
).gsap.getProperty("#target", "x"),
),
);
expect(x).toBeCloseTo(50, 0);
await preview.page.close();
},
);
// fails without the fix: every preview Studio connected to requested the plugin.
it.each(MODES)(
"a page the preview builder marked as path-free requests no plugin (%s)",
async (mode) => {
const marked = previewHtml().replace(
STUDIO_MARK,
`${STUDIO_MARK}<meta name="${NO_PATH_TWEEN_META}">`,
);
const preview = await openSharedPreview(browser, studioBundle, marked, mode);
await connect(preview.page);
expect(await pluginScripts(preview)).toBe(0);
await preview.page.close();
},
);
// fails without the fix: all but "still recovers an older script refusal after an unrelated successful patch",
// which guards the coverage rule against dropping a refusal no re-run carries.
describe("late answers held in transit, sealed", () => {
@@ -127,12 +127,13 @@ function holdReplies() {
});
}
/** Opens the preview in Studio's page; the plugin request waits until `release` is called. */
/** Opens the preview in Studio's page; the plugin request waits until `release`; a `scripts` URL gets its script. */
export async function openPreview(
browser: Browser,
studioBundle: string,
html: string,
mode: string,
scripts: Record<string, string> = {},
) {
const page: Page = await browser.newPage();
const plugin = readFileSync(require.resolve("gsap/dist/MotionPathPlugin.min.js"), "utf8");
@@ -140,6 +141,9 @@ export async function openPreview(
let holding = true;
await page.setRequestInterception(true);
page.on("request", (request) => {
const script = scripts[request.url()];
if (script !== undefined)
return void request.respond({ status: 200, contentType: "text/javascript", body: script });
if (!/MotionPathPlugin/.test(request.url())) return void request.continue();
const serve = () =>
request.respond({ status: 200, contentType: "text/javascript", body: plugin });