Skip to content

Commit 6f3543e

Browse files
committed
fix(producer): a composition with no timeline-registering script no longer waits 45 s at setup
The render waited the full timeout for every composition that never registers a timeline, such as one driven by canvas or requestAnimationFrame.
1 parent 85dcc19 commit 6f3543e

7 files changed

Lines changed: 172 additions & 7 deletions

File tree

‎packages/core/src/compiler/compositionScoping.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { describe, expect, it, vi } from "vitest";
22
import { parseHTML } from "linkedom";
33
import { JSDOM } from "jsdom";
44
import {
5+
AUTHORED_SOURCE_BEGIN,
6+
AUTHORED_SOURCE_END,
57
buildVariablesByCompScript,
68
dedupeFontFaceRules,
79
scopeCssToComposition,
@@ -1536,3 +1538,13 @@ describe("composition scoping – renamed-id selector runtime", () => {
15361538
expect(captured.bracket).toBe("circle");
15371539
});
15381540
});
1541+
1542+
describe("wrapScopedCompositionScript — authored source delimiters", () => {
1543+
it("puts exactly the authored source between the markers, apart from the wrapper's own __timelines use", () => {
1544+
const wrapped = wrapScopedCompositionScript("draw();", "scene");
1545+
const authored = wrapped.split(AUTHORED_SOURCE_BEGIN)[1]!.split(AUTHORED_SOURCE_END)[0]!;
1546+
expect(authored.trim()).toBe("draw();");
1547+
expect(wrapped).toContain("__timelines");
1548+
expect(wrapped.replace(authored, "")).toContain("__timelines");
1549+
});
1550+
});

‎packages/core/src/compiler/compositionScoping.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,10 @@ const SCOPED_HYPERFRAMES_EXPRESSION = `!__hfBaseHyperframes
375375
},
376376
})`;
377377

378+
// Bound the authored part of a wrapped script: the wrapper itself mentions __timelines.
379+
export const AUTHORED_SOURCE_BEGIN = "/*hf-authored-begin*/";
380+
export const AUTHORED_SOURCE_END = "/*hf-authored-end*/";
381+
378382
export function scopedModulePrelude(
379383
timelineCompositionId: string,
380384
compositionSrc?: string | null,
@@ -677,7 +681,9 @@ export function wrapScopedCompositionScript(
677681
if (typeof report === "function") report("start", __hfCompositionSrc || "index.html");
678682
try {
679683
(function(document, gsap, window, __hyperframes) {
684+
${AUTHORED_SOURCE_BEGIN}
680685
${source.replace(/<\/(script)/gi, "<\\/$1")}
686+
${AUTHORED_SOURCE_END}
681687
}).call(window, __hfScopedDocument, __hfScopedGsap, __hfScopedWindow, __hfScopedHyperframes);
682688
} catch (_err) {
683689
console.error(__hfErrorLabel, __hfCompId, _err);

‎packages/core/src/compiler/inlineSubCompositions.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ import {
2727
import { warnUnknownEnumValues } from "../runtime/getVariables";
2828
import {
2929
createCompositionCssScoper,
30+
AUTHORED_SOURCE_BEGIN,
31+
AUTHORED_SOURCE_END,
3032
wrapInlineScriptWithErrorBoundary,
3133
scopedModulePrelude,
3234
wrapScopedCompositionScript,
@@ -627,7 +629,9 @@ export function inlineSubCompositions(
627629
const prelude = scriptCompositionId
628630
? scopedModulePrelude(runtimeCompId || scopeCompId || scriptCompositionId, src)
629631
: "";
630-
moduleScripts.push(prelude + (scriptEl.textContent || ""));
632+
moduleScripts.push(
633+
`${prelude}${AUTHORED_SOURCE_BEGIN}\n${scriptEl.textContent || ""}\n${AUTHORED_SOURCE_END}`,
634+
);
631635
} else if (externalSrc) {
632636
if (!externalScriptSrcs.includes(externalSrc)) {
633637
externalScriptSrcs.push(externalSrc);

‎packages/core/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,7 @@ export {
186186
type SubCompositionValidityReason,
187187
} from "./compiler/subCompositionValidity";
188188
export { RUNTIME_BOOTSTRAP_ATTR, stripEmbeddedRuntimeScripts } from "./compiler/htmlDocument";
189+
export { AUTHORED_SOURCE_BEGIN, AUTHORED_SOURCE_END } from "./compiler/compositionScoping";
189190
export { COMPOSITION_SOURCE_URL } from "./compiler/scriptRuns";
190191
export { queryByAttr } from "./utils/cssSelector";
191192
export {

‎packages/engine/src/services/frameCapture-subTimelinePoll.test.ts‎

Lines changed: 98 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,16 @@
88

99
import { describe, expect, it, vi } from "vitest";
1010
import type { Page } from "puppeteer-core";
11-
import { pollSubCompositionTimelines } from "./frameCapture.js";
11+
import { parseHTML } from "linkedom";
12+
import { AUTHORED_SOURCE_BEGIN, AUTHORED_SOURCE_END } from "@hyperframes/core";
13+
import { authorScriptsMayRegisterTimelines, pollSubCompositionTimelines } from "./frameCapture.js";
1214

15+
// A function argument is the author-script scan; these tests model pages whose scripts may register.
1316
function makeMockPage(evaluateResults: (expr: string) => unknown): Page {
1417
return {
15-
evaluate: vi.fn(async (expr: string) => evaluateResults(expr)),
18+
evaluate: vi.fn(async (expr: string | (() => unknown)) =>
19+
typeof expr === "function" ? true : evaluateResults(expr),
20+
),
1621
} as unknown as Page;
1722
}
1823

@@ -21,8 +26,8 @@ describe("pollSubCompositionTimelines fail-fast", () => {
2126
const page = makeMockPage(() => true);
2227
const outcome = await pollSubCompositionTimelines(page, 1_000, { intervalMs: 10 });
2328
expect(outcome).toBe("ready");
24-
// Second evaluate is the __hfForceTimelineRebind call.
25-
expect((page.evaluate as ReturnType<typeof vi.fn>).mock.calls.length).toBe(2);
29+
// Script scan, readiness check, then the __hfForceTimelineRebind call.
30+
expect((page.evaluate as ReturnType<typeof vi.fn>).mock.calls.length).toBe(3);
2631
});
2732

2833
it("bails after the grace window when a script resource failed to load", async () => {
@@ -127,3 +132,92 @@ describe("pollSubCompositionTimelines fail-fast", () => {
127132
expect(outcome).toBe("ready");
128133
});
129134
});
135+
136+
describe("pollSubCompositionTimelines when no author script can register a timeline", () => {
137+
it("is ready at once instead of waiting out the timeout", async () => {
138+
const evaluate = vi.fn(async (expr: string | (() => unknown)) =>
139+
typeof expr === "function"
140+
? false
141+
: expr.includes("__hfForceTimelineRebind")
142+
? undefined
143+
: false,
144+
);
145+
const started = Date.now();
146+
const outcome = await pollSubCompositionTimelines({ evaluate } as unknown as Page, 60_000, {
147+
intervalMs: 10,
148+
getScriptLoadFailures: () => [],
149+
});
150+
expect(outcome).toBe("ready");
151+
expect(Date.now() - started).toBeLessThan(2_000);
152+
});
153+
});
154+
155+
describe("authorScriptsMayRegisterTimelines", () => {
156+
const RUNTIME_ATTR = "data-hyperframes-preview-runtime";
157+
158+
async function scan(html: string, files: Record<string, string> = {}): Promise<boolean> {
159+
const { document } = parseHTML(html);
160+
Object.defineProperty(document, "readyState", { value: "complete" });
161+
vi.stubGlobal("document", document);
162+
vi.stubGlobal("location", new URL("http://localhost:3000/index.html"));
163+
vi.stubGlobal("fetch", async (url: URL) => ({
164+
text: async () => {
165+
const body = files[url.pathname];
166+
if (body === undefined) throw new Error("404");
167+
return body;
168+
},
169+
}));
170+
try {
171+
return await authorScriptsMayRegisterTimelines(
172+
RUNTIME_ATTR,
173+
AUTHORED_SOURCE_BEGIN,
174+
AUTHORED_SOURCE_END,
175+
);
176+
} finally {
177+
vi.unstubAllGlobals();
178+
}
179+
}
180+
181+
it("is false for scripts that never mention a timeline registration", async () => {
182+
expect(
183+
await scan(
184+
`<body><script>draw()</script><template><script>animate()</script></template></body>`,
185+
),
186+
).toBe(false);
187+
});
188+
189+
it("reads only the authored part of a scoped wrapper, which mentions __timelines itself", async () => {
190+
const wrapped = (source: string) =>
191+
`<body><script>(function(){ window.__timelines = window.__timelines || {};\n${AUTHORED_SOURCE_BEGIN}\n${source}\n${AUTHORED_SOURCE_END}\n})();</script></body>`;
192+
expect(await scan(wrapped("draw()"))).toBe(false);
193+
expect(await scan(wrapped("window.__timelines['a'] = tl"))).toBe(true);
194+
});
195+
196+
it("ignores the runtime, which mentions __timelines itself", async () => {
197+
expect(
198+
await scan(`<body><script ${RUNTIME_ATTR}>window.__timelines = {}</script></body>`),
199+
).toBe(false);
200+
});
201+
202+
it("is true when an inline script or a template script registers one", async () => {
203+
expect(await scan(`<body><script>window.__timelines["a"] = tl</script></body>`)).toBe(true);
204+
expect(
205+
await scan(`<body><template><script>window.__timelines.b = tl</script></template></body>`),
206+
).toBe(true);
207+
});
208+
209+
it("reads same-origin scripts and answers true for ones it cannot read", async () => {
210+
expect(await scan(`<body><script src="/a.js"></script></body>`, { "/a.js": "draw()" })).toBe(
211+
false,
212+
);
213+
expect(
214+
await scan(`<body><script src="/a.js"></script></body>`, {
215+
"/a.js": "window.__timelines.x = 1",
216+
}),
217+
).toBe(true);
218+
expect(await scan(`<body><script src="/missing.js"></script></body>`)).toBe(true);
219+
expect(await scan(`<body><script src="https://cdn.example.com/lib.js"></script></body>`)).toBe(
220+
true,
221+
);
222+
});
223+
});

‎packages/engine/src/services/frameCapture-subTimelineWarning.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,8 @@ describe("pollSubCompositionTimelines pending-id reporting", () => {
171171
function pageReturning(enumerateResult: unknown) {
172172
const matched = { count: 0 };
173173
const page = {
174-
evaluate: vi.fn(async (expr: string) => {
174+
evaluate: vi.fn(async (expr: string | (() => unknown)) => {
175+
if (typeof expr === "function") return true;
175176
if (!expr.includes("m.push(")) return false;
176177
matched.count++;
177178
return enumerateResult;

‎packages/engine/src/services/frameCapture.ts‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ import {
2424
quantizeTimeToFrame,
2525
fpsToNumber,
2626
resolveAuthoredTimingWindow,
27+
AUTHORED_SOURCE_BEGIN,
28+
AUTHORED_SOURCE_END,
29+
RUNTIME_BOOTSTRAP_ATTR,
2730
SCENE_CALLBACK_ERROR_PREFIX,
2831
type RawAuthoredTiming,
2932
} from "@hyperframes/core";
@@ -2061,6 +2064,44 @@ export interface IsolatedComposition {
20612064
elementId: string | null;
20622065
}
20632066

2067+
// Runs in the page. False once every inline, template and same-origin script is read and none
2068+
// mentions __timelines; an unreadable script or a page still loading answers true.
2069+
export async function authorScriptsMayRegisterTimelines(
2070+
runtimeAttr: string,
2071+
authoredBegin: string,
2072+
authoredEnd: string,
2073+
): Promise<boolean> {
2074+
if (document.readyState !== "complete") return true;
2075+
const scripts = [
2076+
...Array.from(document.querySelectorAll("script")),
2077+
...Array.from(document.querySelectorAll("template")).flatMap((t) =>
2078+
Array.from(t.content.querySelectorAll("script")),
2079+
),
2080+
].filter((script) => !script.hasAttribute(runtimeAttr));
2081+
for (const script of scripts) {
2082+
if (!script.src) {
2083+
const text = script.textContent ?? "";
2084+
const authored = text.includes(authoredBegin)
2085+
? text
2086+
.split(authoredBegin)
2087+
.slice(1)
2088+
.map((region) => region.split(authoredEnd)[0])
2089+
.join("\n")
2090+
: text;
2091+
if (authored.includes("__timelines")) return true;
2092+
continue;
2093+
}
2094+
const url = new URL(script.src, location.href);
2095+
if (url.origin !== location.origin) return true;
2096+
try {
2097+
if ((await (await fetch(url)).text()).includes("__timelines")) return true;
2098+
} catch {
2099+
return true;
2100+
}
2101+
}
2102+
return false;
2103+
}
2104+
20642105
export interface SubTimelinePollOptions {
20652106
intervalMs?: number;
20662107
// Fail-fast: a script resource that failed to load can never register its timeline,
@@ -2116,7 +2157,13 @@ export async function pollSubCompositionTimelines(
21162157
// A page error is given its grace from when it first appeared, not from when the poll began.
21172158
let errorSeenAt: number | undefined;
21182159
for (;;) {
2119-
ready = Boolean(await page.evaluate(expression));
2160+
ready =
2161+
!(await page.evaluate(
2162+
authorScriptsMayRegisterTimelines,
2163+
RUNTIME_BOOTSTRAP_ATTR,
2164+
AUTHORED_SOURCE_BEGIN,
2165+
AUTHORED_SOURCE_END,
2166+
)) || Boolean(await page.evaluate(expression));
21202167
if (ready || shouldStop?.()) break;
21212168
const now = Date.now();
21222169
if (now >= deadline) break;

0 commit comments

Comments
 (0)