fix(player): a sealed film no longer shows failed to load while its runtime starts (#8472)

* fix(player): a sealed film is ready from its document before its runtime boots

* test(core): the static composition post reaches a parent frame while the page parses

* refactor(core): keep the static read's bounds inside their file
This commit is contained in:
Miguel Ángel
2026-11-22 10:16:07 +00:00
committed by GitHub
parent 61008a40dd
commit 835e660e0e
10 changed files with 308 additions and 16 deletions
@@ -14,6 +14,19 @@ export function parseCompositionDimension(value: string | null | undefined): num
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
}
/** The composition's size as a document alone gives it: the composition root's, else any element that declares both. */
export function readCompositionSizeFromDocument(
doc: ParentNode | null | undefined,
): { width: number; height: number } | null {
const root =
doc?.querySelector("[data-composition-id][data-width][data-height]") ??
doc?.querySelector("[data-width][data-height]");
if (!root) return null;
const width = parseCompositionDimension(root.getAttribute("data-width"));
const height = parseCompositionDimension(root.getAttribute("data-height"));
return width !== null && height !== null ? { width, height } : null;
}
export function findRootCompositionElement(doc: ParentNode = document): HTMLElement | null {
const explicitRoot = doc.querySelector('[data-composition-id][data-root="true"]');
if (isHtmlElement(explicitRoot)) return explicitRoot;
+46 -2
View File
@@ -2,13 +2,17 @@ import {
resolveCompositionDuration,
type CompositionDurationResult,
} from "@hyperframes/parsers/composition-duration";
import { findRootCompositionElement, parseCompositionDimension } from "./compositionDimension";
import {
findRootCompositionElement,
parseCompositionDimension,
readCompositionSizeFromDocument,
} from "./compositionDimension";
import { isMediaElement } from "./domRealm";
import { parseStrictFiniteTimingNumber, resolveMediaElementDurationSeconds } from "./playbackRate";
import { createRuntimeStartTimeResolver } from "./startResolver";
import { createRuntimeState } from "./state";
export { findRootCompositionElement };
export { findRootCompositionElement, readCompositionSizeFromDocument };
export const LOOP_INFLATED_TIMELINE_SECONDS = 7200;
@@ -204,3 +208,43 @@ export function readStaticCompositionMeta(
});
return { ...readCompositionSize(root), fps: createRuntimeState().canonicalFps, durationSeconds };
}
export const STATIC_COMPOSITION = "static-composition";
const MAX_STATIC_DURATION_SECONDS = 86_400;
const MAX_STATIC_DIMENSION = 16_384;
export type StaticComposition = {
durationSeconds: number;
compositionSize: { width: number; height: number } | null;
};
/** What the document alone says of its composition: the probe reads it, a sealed frame's runtime posts it. */
export function readStaticComposition(doc: Document): StaticComposition | null {
const durationSeconds = readStaticCompositionMeta(doc)?.durationSeconds ?? 0;
if (!(durationSeconds > 0)) return null;
return { durationSeconds, compositionSize: readCompositionSizeFromDocument(doc) };
}
const boundedDimension = (value: unknown): number | null =>
typeof value === "number" && Number.isInteger(value) && value > 0 && value <= MAX_STATIC_DIMENSION
? value
: null;
/** A posted read with a finite length in (0, a day] and no size or a whole bounded one, else null. */
export function parseStaticComposition(data: Record<string, unknown>): StaticComposition | null {
const seconds = data["durationSeconds"];
if (
typeof seconds !== "number" ||
!Number.isFinite(seconds) ||
seconds <= 0 ||
seconds > MAX_STATIC_DURATION_SECONDS
)
return null;
const { width, height } = data;
if (width == null && height == null) return { durationSeconds: seconds, compositionSize: null };
const w = boundedDimension(width);
const h = boundedDimension(height);
return w !== null && h !== null
? { durationSeconds: seconds, compositionSize: { width: w, height: h } }
: null;
}
+3
View File
@@ -21,6 +21,7 @@ import { trackAcceleratedCanvases } from "./captureMotionBlur";
import { parkFarScenesAtBoot } from "./sceneWindow";
import { installPausedVideoCallbacks } from "./pausedVideoCallbacks";
import { corsForSealedMedia } from "./sealedMediaCors";
import { postStaticCompositionWhenParsed } from "./staticCompositionPost";
type HyperframeWindow = Window & {
__hyperframeRuntimeBootstrapped?: boolean;
@@ -101,6 +102,8 @@ function startAfterCompositionScripts(): void {
}
}
postStaticCompositionWhenParsed();
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", startAfterCompositionScripts, { once: true });
} else {
@@ -0,0 +1,58 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { postStaticCompositionWhenParsed } from "./staticCompositionPost";
const ROOT =
'<div data-composition-id="main" data-duration="10" data-width="1920" data-height="1080"></div>';
/** A frame's view of its parent: a window that only records posts. */
function framed() {
const posts: unknown[] = [];
const parent = { postMessage: (message: unknown) => posts.push(message) };
vi.spyOn(window, "parent", "get").mockReturnValue(parent as unknown as Window);
return posts;
}
const sent = (posts: unknown[]) =>
posts.map((post) => {
const { type, durationSeconds, width, height } = post as Record<string, unknown>;
return { type, durationSeconds, width, height };
});
describe("postStaticCompositionWhenParsed", () => {
afterEach(() => {
vi.restoreAllMocks();
document.body.innerHTML = "";
});
it("tells a parent frame the document's length and size, once", () => {
const posts = framed();
document.body.innerHTML = ROOT;
postStaticCompositionWhenParsed();
expect(sent(posts)).toEqual([
{ type: "static-composition", durationSeconds: 10, width: 1920, height: 1080 },
]);
});
it("posts nothing from a top-level page", () => {
const post = vi.spyOn(window, "postMessage");
document.body.innerHTML = ROOT;
postStaticCompositionWhenParsed();
expect(post).not.toHaveBeenCalled();
});
it("posts while the page still parses, once the root declares its length", async () => {
const posts = framed();
vi.spyOn(document, "readyState", "get").mockReturnValue("loading");
postStaticCompositionWhenParsed();
document.body.innerHTML = '<div data-composition-id="main"></div>';
await Promise.resolve();
expect(posts).toEqual([]);
document.body.innerHTML = ROOT;
await Promise.resolve();
expect(sent(posts)).toEqual([
{ type: "static-composition", durationSeconds: 10, width: 1920, height: 1080 },
]);
document.dispatchEvent(new Event("DOMContentLoaded"));
expect(posts).toHaveLength(1);
});
});
@@ -0,0 +1,43 @@
import { postRuntimeMessage } from "./bridge";
import {
findRootCompositionElement,
readStaticComposition,
STATIC_COMPOSITION,
} from "./compositionLength";
/** Posts the document's static read once, as soon as it is whole: when the root is parsed if it declares its length,
* else at DOMContentLoaded. A parent that can't read the frame is then ready when one that can would be. */
export function postStaticCompositionWhenParsed(doc: Document = document): void {
// A top-level page (a render) has no parent to tell, and the read walks every clip.
if (window.parent === window) return;
let posted = false;
const post = (): void => {
if (posted) return;
posted = true;
const read = readStaticComposition(doc);
if (!read) return;
postRuntimeMessage({
source: "hf-preview",
type: STATIC_COMPOSITION,
durationSeconds: read.durationSeconds,
width: read.compositionSize?.width ?? null,
height: read.compositionSize?.height ?? null,
});
};
const declared = () => findRootCompositionElement(doc)?.hasAttribute("data-duration") === true;
if (doc.readyState !== "loading" || declared()) return post();
const observer = new MutationObserver(() => {
if (!declared()) return;
observer.disconnect();
post();
});
observer.observe(doc, { childList: true, subtree: true });
doc.addEventListener(
"DOMContentLoaded",
() => {
observer.disconnect();
post();
},
{ once: true },
);
}
+10
View File
@@ -166,6 +166,15 @@ export type RuntimePickerCancelledMessage = {
type: "pick-mode-cancelled";
};
/** The document's own length and size, posted before the runtime boots (`compositionLength.readStaticComposition`). */
export type RuntimeStaticCompositionMessage = {
source: "hf-preview";
type: "static-composition";
durationSeconds: number;
width: number | null;
height: number | null;
};
export type RuntimeStageSizeMessage = {
source: "hf-preview";
type: "stage-size";
@@ -337,6 +346,7 @@ export type RuntimeOutboundMessage =
| RuntimePickerPickedManyMessage
| RuntimePickerCancelledMessage
| RuntimeStageSizeMessage
| RuntimeStaticCompositionMessage
| RuntimeMediaAutoplayBlockedMessage
| RuntimeReadyMessage
| RuntimeAssetsReadyMessage
+5 -12
View File
@@ -10,7 +10,10 @@
* `stop()` on disconnect or src change.
*/
import { readStaticCompositionMeta } from "@hyperframes/core/runtime/composition-length";
import {
readCompositionSizeFromDocument,
readStaticCompositionMeta,
} from "@hyperframes/core/runtime/composition-length";
import { STUDIO_PREVIEW_ERRORS } from "@hyperframes/core/studio-preview-mark";
import { shouldInjectRuntime } from "./shouldInjectRuntime.js";
import {
@@ -55,17 +58,7 @@ export function readPositiveDimension(value: string | null): number | null {
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
}
export function readCompositionSizeFromDocument(
doc: Document | null | undefined,
): { width: number; height: number } | null {
const root =
doc?.querySelector("[data-composition-id][data-width][data-height]") ??
doc?.querySelector("[data-width][data-height]");
if (!root) return null;
const width = readPositiveDimension(root.getAttribute("data-width"));
const height = readPositiveDimension(root.getAttribute("data-height"));
return width !== null && height !== null ? { width, height } : null;
}
export { readCompositionSizeFromDocument };
type ProbeOutcome =
| { kind: "ready"; result: ProbeResult }
+22 -2
View File
@@ -1,4 +1,5 @@
import { CompositionProbe, type ProbeResult, readPositiveDimension } from "./composition-probe.js";
import type { StaticComposition } from "@hyperframes/core/runtime/composition-length";
import { isControlsClick, setupControls, setupPoster } from "./controls-setup.js";
import { adoptShadowStyles, createCompositionIframe, scaleIframeToFit } from "./iframe-dom.js";
import { DirectTimelineClock } from "./direct-timeline-clock.js";
@@ -131,6 +132,7 @@ class HyperframesPlayer extends HTMLElement {
private probe: CompositionProbe;
private _ready = false;
private _readyBeforeRuntime = false;
private _readyDocument: Document | null = null;
private _connected = false;
private _assetsReady = false;
@@ -1288,6 +1290,7 @@ class HyperframesPlayer extends HTMLElement {
this._rejectRuntimeDataDelivery(channel, requestId, message),
onRuntimeTimelineReady: (duration, assetsReady) =>
this._onRuntimeTimelineReady(duration, assetsReady),
onStaticComposition: (read) => this._onStaticComposition(read),
setBuffering: (buffering) => this._setBuffering(buffering),
setRuntimeFps: (fps) => {
this._runtimeFps = fps;
@@ -1312,13 +1315,15 @@ class HyperframesPlayer extends HTMLElement {
}
private _onRuntimeTimelineReady(duration: number, assetsReady: boolean | undefined) {
if (this._ready) return;
if (this._ready && !this._readyBeforeRuntime) return;
const alreadyReady = this._readyBeforeRuntime;
this._readyBeforeRuntime = false;
this.probe.stop();
this._setDuration(duration);
this._directTimelineAdapter = null;
this._ready = true;
this.controlsApi?.updateTime(this._currentTime, duration);
this._dispatchReady();
if (!alreadyReady) this._dispatchReady();
const doc = this._getSameOriginIframeDocument();
if (doc) this._media.setupFromIframe(doc);
@@ -1329,6 +1334,19 @@ class HyperframesPlayer extends HTMLElement {
this._playWhenWanted();
}
/** A sealed frame's length and size from its document, as the probe reads them; play waits for the runtime. */
private _onStaticComposition({ durationSeconds, compositionSize }: StaticComposition) {
// An open frame's own poll reads the same thing.
if (this._ready || this._getSameOriginIframeDocument()) return;
this.probe.stop();
this._setDuration(durationSeconds);
if (compositionSize) this._setCompositionSize(compositionSize.width, compositionSize.height);
this._ready = true;
this._readyBeforeRuntime = true;
this.controlsApi?.updateTime(0, durationSeconds);
this._dispatchReady();
}
private _onProbeReady(result: ProbeResult) {
this._applyThenEmit(() => this._applyProbeResult(result));
}
@@ -1464,6 +1482,7 @@ class HyperframesPlayer extends HTMLElement {
this.probe.latchUntilNextLoad();
this.probe.stop();
this._ready = false;
this._readyBeforeRuntime = false;
this._readyDocument = null;
this._invalidateAssetsWait();
this._releaseDocument();
@@ -1616,6 +1635,7 @@ class HyperframesPlayer extends HTMLElement {
}
this._ready = false;
this._readyBeforeRuntime = false;
// The runtime installs its bridge once its scripts ran and posts `ready`, which can come before
// the iframe's load event. Do not erase that authoritative handshake here: doing so strands
// retained data set after load until a second `ready` that never comes. Source setters and
@@ -13,6 +13,11 @@ import {
import type { ShaderLoaderState } from "./shader-loader-state.js";
import type { ShaderTransitionState } from "./shader-options.js";
import { inspectRuntimeProtocol } from "@hyperframes/core/runtime/protocol";
import {
parseStaticComposition,
STATIC_COMPOSITION,
type StaticComposition,
} from "@hyperframes/core/runtime/composition-length";
type SceneRecord = { id: string; start: number; duration: number };
@@ -48,6 +53,8 @@ export interface MessageHandlerCallbacks extends PlaybackStateCallbacks {
* player uses this as the cross-origin readiness signal because the
* same-origin composition probe cannot inspect CDN iframes. */
onRuntimeTimelineReady: (duration: number, assetsReady: boolean | undefined) => void;
/** The frame's own static read, posted before its runtime boots, for a player that can't read the frame. */
onStaticComposition?: (read: StaticComposition) => void;
setBuffering?: (buffering: boolean) => void;
setRuntimeFps?: (fps: number) => void;
setRuntimeOwnsPlayRange?: (owns: boolean) => void;
@@ -96,6 +103,12 @@ export function handleRuntimeMessage(
return;
}
if (data["type"] === STATIC_COMPOSITION) {
const read = parseStaticComposition(data);
if (read) callbacks.onStaticComposition?.(read);
return;
}
if (data["type"] === "ready") {
callbacks.onRuntimeReady();
return;
@@ -0,0 +1,95 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
type Player = HTMLElement & {
ready: boolean;
duration: number;
iframeElement: HTMLIFrameElement;
_onIframeLoad(): void;
};
/** A player whose frame is sealed as the browser seals it: its window posts, its document can't be read. */
function framedPlayer(sealed = true) {
const player = document.createElement("hyperframes-player") as Player;
player.setAttribute("sandbox-origin", "");
document.body.appendChild(player);
const frame = player.iframeElement;
if (sealed) Object.defineProperty(frame, "contentDocument", { value: null, configurable: true });
const events: string[] = [];
player.addEventListener("error", (event: Event) =>
events.push(`error ${(event as CustomEvent<{ message?: string }>).detail?.message}`),
);
player.addEventListener("ready", () => events.push("ready"));
player._onIframeLoad();
const post = (
data: Record<string, unknown>,
source: MessageEventSource | null = frame.contentWindow,
) =>
window.dispatchEvent(
new MessageEvent("message", { source, data: { source: "hf-preview", ...data } }),
);
const postStatic = (over: Record<string, unknown> = {}, source?: MessageEventSource | null) =>
post(
{ type: "static-composition", durationSeconds: 4, width: 1080, height: 1920, ...over },
source,
);
const postTimeline = () => post({ type: "timeline", durationInFrames: 180, durationSeconds: 6 });
return { player, events, postStatic, postTimeline };
}
describe("a sealed film whose runtime boots after the 8 s check", () => {
beforeEach(async () => {
vi.useFakeTimers();
await import("./hyperframes-player.js");
});
afterEach(() => {
vi.useRealTimers();
document.body.innerHTML = "";
});
// fails without the fix: a sealed player could only wait for the runtime's timeline, so a film whose runtime booted
// at 10 s showed "Composition timeline not found after 8s" while the same film unsealed was ready from its document.
it("is ready from its document's static read, with no 8 s error, and the runtime's timeline still lands", () => {
const { player, events, postStatic, postTimeline } = framedPlayer();
vi.advanceTimersByTime(1000);
postStatic();
expect(events).toEqual(["ready"]);
expect(player.duration).toBe(4);
vi.advanceTimersByTime(9000);
expect(events).toEqual(["ready"]);
postTimeline();
expect(events).toEqual(["ready"]);
expect(player.duration).toBe(6);
});
it.each([
["a duration that is not a number", { durationSeconds: Number.NaN }],
["an infinite duration", { durationSeconds: Number.POSITIVE_INFINITY }],
["a zero duration", { durationSeconds: 0 }],
["a negative duration", { durationSeconds: -4 }],
["a duration past the bound", { durationSeconds: 1e9 }],
["a duration sent as text", { durationSeconds: "4" }],
["a width that is not a whole positive number", { width: 0.5 }],
["a height past the bound", { height: 1e7 }],
])("ignores a static read with %s", (_name, over) => {
const { player, events, postStatic } = framedPlayer();
postStatic(over);
vi.advanceTimersByTime(8000);
expect(events).toEqual(["error Composition timeline not found after 8s"]);
expect(player.ready).toBe(false);
});
it("ignores a static read posted by any window but its own frame", () => {
const { player, events, postStatic } = framedPlayer();
postStatic({}, window);
vi.advanceTimersByTime(8000);
expect(events).toEqual(["error Composition timeline not found after 8s"]);
expect(player.ready).toBe(false);
});
it("a frame whose document the player reads keeps its own probe and ignores the post", () => {
const { player, events, postStatic } = framedPlayer(false);
postStatic();
expect(events).toEqual([]);
expect(player.ready).toBe(false);
});
});